id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_bad_5591_0
/* * Edgeport USB Serial Converter driver * * Copyright (C) 2000-2002 Inside Out Networks, All rights reserved. * Copyright (C) 2001-2002 Greg Kroah-Hartman <greg@kroah.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. * * Supports the following devices: * EP/1 EP/2 EP/4 EP/21 EP/22 EP/221 EP/42 EP/421 WATCHPORT * * For questions or problems with this driver, contact Inside Out * Networks technical support, or Peter Berger <pberger@brimson.com>, * or Al Borchers <alborchers@steinerpoint.com>. */ #include <linux/kernel.h> #include <linux/jiffies.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/mutex.h> #include <linux/serial.h> #include <linux/kfifo.h> #include <linux/ioctl.h> #include <linux/firmware.h> #include <linux/uaccess.h> #include <linux/usb.h> #include <linux/usb/serial.h> #include "io_16654.h" #include "io_usbvend.h" #include "io_ti.h" #define DRIVER_AUTHOR "Greg Kroah-Hartman <greg@kroah.com> and David Iacovelli" #define DRIVER_DESC "Edgeport USB Serial Driver" #define EPROM_PAGE_SIZE 64 /* different hardware types */ #define HARDWARE_TYPE_930 0 #define HARDWARE_TYPE_TIUMP 1 /* IOCTL_PRIVATE_TI_GET_MODE Definitions */ #define TI_MODE_CONFIGURING 0 /* Device has not entered start device */ #define TI_MODE_BOOT 1 /* Staying in boot mode */ #define TI_MODE_DOWNLOAD 2 /* Made it to download mode */ #define TI_MODE_TRANSITIONING 3 /* Currently in boot mode but transitioning to download mode */ /* read urb state */ #define EDGE_READ_URB_RUNNING 0 #define EDGE_READ_URB_STOPPING 1 #define EDGE_READ_URB_STOPPED 2 #define EDGE_CLOSING_WAIT 4000 /* in .01 sec */ #define EDGE_OUT_BUF_SIZE 1024 /* Product information read from the Edgeport */ struct product_info { int TiMode; /* Current TI Mode */ __u8 hardware_type; /* Type of hardware */ } __attribute__((packed)); struct edgeport_port { __u16 uart_base; __u16 dma_address; __u8 shadow_msr; __u8 shadow_mcr; __u8 shadow_lsr; __u8 lsr_mask; __u32 ump_read_timeout; /* Number of milliseconds the UMP will wait without data before completing a read short */ int baud_rate; int close_pending; int lsr_event; struct async_icount icount; wait_queue_head_t delta_msr_wait; /* for handling sleeping while waiting for msr change to happen */ struct edgeport_serial *edge_serial; struct usb_serial_port *port; __u8 bUartMode; /* Port type, 0: RS232, etc. */ spinlock_t ep_lock; int ep_read_urb_state; int ep_write_urb_in_use; struct kfifo write_fifo; }; struct edgeport_serial { struct product_info product_info; u8 TI_I2C_Type; /* Type of I2C in UMP */ u8 TiReadI2C; /* Set to TRUE if we have read the I2c in Boot Mode */ struct mutex es_lock; int num_ports_open; struct usb_serial *serial; }; /* Devices that this driver supports */ static const struct usb_device_id edgeport_1port_id_table[] = { { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_1) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROXIMITY) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOTION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOISTURE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_TEMPERATURE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_HUMIDITY) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_POWER) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_LIGHT) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_RADIATION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_DISTANCE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_ACCELERATION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROX_DIST) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_HP4CD) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_PCI) }, { } }; static const struct usb_device_id edgeport_2port_id_table[] = { { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_421) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_42) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_221C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21C) }, /* The 4, 8 and 16 port devices show up as multiple 2 port devices */ { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4S) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8S) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416B) }, { } }; /* Devices that this driver supports */ static const struct usb_device_id id_table_combined[] = { { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_1) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROXIMITY) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOTION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOISTURE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_TEMPERATURE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_HUMIDITY) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_POWER) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_LIGHT) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_RADIATION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_DISTANCE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_ACCELERATION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROX_DIST) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_HP4CD) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_PCI) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_421) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_42) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_221C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4S) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8S) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416B) }, { } }; MODULE_DEVICE_TABLE(usb, id_table_combined); static unsigned char OperationalMajorVersion; static unsigned char OperationalMinorVersion; static unsigned short OperationalBuildNumber; static int closing_wait = EDGE_CLOSING_WAIT; static bool ignore_cpu_rev; static int default_uart_mode; /* RS232 */ static void edge_tty_recv(struct device *dev, struct tty_struct *tty, unsigned char *data, int length); static void stop_read(struct edgeport_port *edge_port); static int restart_read(struct edgeport_port *edge_port); static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port, struct ktermios *old_termios); static void edge_send(struct tty_struct *tty); /* sysfs attributes */ static int edge_create_sysfs_attrs(struct usb_serial_port *port); static int edge_remove_sysfs_attrs(struct usb_serial_port *port); static int ti_vread_sync(struct usb_device *dev, __u8 request, __u16 value, __u16 index, u8 *data, int size) { int status; status = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), request, (USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN), value, index, data, size, 1000); if (status < 0) return status; if (status != size) { dev_dbg(&dev->dev, "%s - wanted to write %d, but only wrote %d\n", __func__, size, status); return -ECOMM; } return 0; } static int ti_vsend_sync(struct usb_device *dev, __u8 request, __u16 value, __u16 index, u8 *data, int size) { int status; status = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), request, (USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT), value, index, data, size, 1000); if (status < 0) return status; if (status != size) { dev_dbg(&dev->dev, "%s - wanted to write %d, but only wrote %d\n", __func__, size, status); return -ECOMM; } return 0; } static int send_cmd(struct usb_device *dev, __u8 command, __u8 moduleid, __u16 value, u8 *data, int size) { return ti_vsend_sync(dev, command, value, moduleid, data, size); } /* clear tx/rx buffers and fifo in TI UMP */ static int purge_port(struct usb_serial_port *port, __u16 mask) { int port_number = port->number - port->serial->minor; dev_dbg(&port->dev, "%s - port %d, mask %x\n", __func__, port_number, mask); return send_cmd(port->serial->dev, UMPC_PURGE_PORT, (__u8)(UMPM_UART1_PORT + port_number), mask, NULL, 0); } /** * read_download_mem - Read edgeport memory from TI chip * @dev: usb device pointer * @start_address: Device CPU address at which to read * @length: Length of above data * @address_type: Can read both XDATA and I2C * @buffer: pointer to input data buffer */ static int read_download_mem(struct usb_device *dev, int start_address, int length, __u8 address_type, __u8 *buffer) { int status = 0; __u8 read_length; __be16 be_start_address; dev_dbg(&dev->dev, "%s - @ %x for %d\n", __func__, start_address, length); /* Read in blocks of 64 bytes * (TI firmware can't handle more than 64 byte reads) */ while (length) { if (length > 64) read_length = 64; else read_length = (__u8)length; if (read_length > 1) { dev_dbg(&dev->dev, "%s - @ %x for %d\n", __func__, start_address, read_length); } be_start_address = cpu_to_be16(start_address); status = ti_vread_sync(dev, UMPC_MEMORY_READ, (__u16)address_type, (__force __u16)be_start_address, buffer, read_length); if (status) { dev_dbg(&dev->dev, "%s - ERROR %x\n", __func__, status); return status; } if (read_length > 1) usb_serial_debug_data(&dev->dev, __func__, read_length, buffer); /* Update pointers/length */ start_address += read_length; buffer += read_length; length -= read_length; } return status; } static int read_ram(struct usb_device *dev, int start_address, int length, __u8 *buffer) { return read_download_mem(dev, start_address, length, DTK_ADDR_SPACE_XDATA, buffer); } /* Read edgeport memory to a given block */ static int read_boot_mem(struct edgeport_serial *serial, int start_address, int length, __u8 *buffer) { int status = 0; int i; for (i = 0; i < length; i++) { status = ti_vread_sync(serial->serial->dev, UMPC_MEMORY_READ, serial->TI_I2C_Type, (__u16)(start_address+i), &buffer[i], 0x01); if (status) { dev_dbg(&serial->serial->dev->dev, "%s - ERROR %x\n", __func__, status); return status; } } dev_dbg(&serial->serial->dev->dev, "%s - start_address = %x, length = %d\n", __func__, start_address, length); usb_serial_debug_data(&serial->serial->dev->dev, __func__, length, buffer); serial->TiReadI2C = 1; return status; } /* Write given block to TI EPROM memory */ static int write_boot_mem(struct edgeport_serial *serial, int start_address, int length, __u8 *buffer) { int status = 0; int i; u8 *temp; /* Must do a read before write */ if (!serial->TiReadI2C) { temp = kmalloc(1, GFP_KERNEL); if (!temp) { dev_err(&serial->serial->dev->dev, "%s - out of memory\n", __func__); return -ENOMEM; } status = read_boot_mem(serial, 0, 1, temp); kfree(temp); if (status) return status; } for (i = 0; i < length; ++i) { status = ti_vsend_sync(serial->serial->dev, UMPC_MEMORY_WRITE, buffer[i], (__u16)(i + start_address), NULL, 0); if (status) return status; } dev_dbg(&serial->serial->dev->dev, "%s - start_sddr = %x, length = %d\n", __func__, start_address, length); usb_serial_debug_data(&serial->serial->dev->dev, __func__, length, buffer); return status; } /* Write edgeport I2C memory to TI chip */ static int write_i2c_mem(struct edgeport_serial *serial, int start_address, int length, __u8 address_type, __u8 *buffer) { struct device *dev = &serial->serial->dev->dev; int status = 0; int write_length; __be16 be_start_address; /* We can only send a maximum of 1 aligned byte page at a time */ /* calculate the number of bytes left in the first page */ write_length = EPROM_PAGE_SIZE - (start_address & (EPROM_PAGE_SIZE - 1)); if (write_length > length) write_length = length; dev_dbg(dev, "%s - BytesInFirstPage Addr = %x, length = %d\n", __func__, start_address, write_length); usb_serial_debug_data(dev, __func__, write_length, buffer); /* Write first page */ be_start_address = cpu_to_be16(start_address); status = ti_vsend_sync(serial->serial->dev, UMPC_MEMORY_WRITE, (__u16)address_type, (__force __u16)be_start_address, buffer, write_length); if (status) { dev_dbg(dev, "%s - ERROR %d\n", __func__, status); return status; } length -= write_length; start_address += write_length; buffer += write_length; /* We should be aligned now -- can write max page size bytes at a time */ while (length) { if (length > EPROM_PAGE_SIZE) write_length = EPROM_PAGE_SIZE; else write_length = length; dev_dbg(dev, "%s - Page Write Addr = %x, length = %d\n", __func__, start_address, write_length); usb_serial_debug_data(dev, __func__, write_length, buffer); /* Write next page */ be_start_address = cpu_to_be16(start_address); status = ti_vsend_sync(serial->serial->dev, UMPC_MEMORY_WRITE, (__u16)address_type, (__force __u16)be_start_address, buffer, write_length); if (status) { dev_err(dev, "%s - ERROR %d\n", __func__, status); return status; } length -= write_length; start_address += write_length; buffer += write_length; } return status; } /* Examine the UMP DMA registers and LSR * * Check the MSBit of the X and Y DMA byte count registers. * A zero in this bit indicates that the TX DMA buffers are empty * then check the TX Empty bit in the UART. */ static int tx_active(struct edgeport_port *port) { int status; struct out_endpoint_desc_block *oedb; __u8 *lsr; int bytes_left = 0; oedb = kmalloc(sizeof(*oedb), GFP_KERNEL); if (!oedb) { dev_err(&port->port->dev, "%s - out of memory\n", __func__); return -ENOMEM; } lsr = kmalloc(1, GFP_KERNEL); /* Sigh, that's right, just one byte, as not all platforms can do DMA from stack */ if (!lsr) { kfree(oedb); return -ENOMEM; } /* Read the DMA Count Registers */ status = read_ram(port->port->serial->dev, port->dma_address, sizeof(*oedb), (void *)oedb); if (status) goto exit_is_tx_active; dev_dbg(&port->port->dev, "%s - XByteCount 0x%X\n", __func__, oedb->XByteCount); /* and the LSR */ status = read_ram(port->port->serial->dev, port->uart_base + UMPMEM_OFFS_UART_LSR, 1, lsr); if (status) goto exit_is_tx_active; dev_dbg(&port->port->dev, "%s - LSR = 0x%X\n", __func__, *lsr); /* If either buffer has data or we are transmitting then return TRUE */ if ((oedb->XByteCount & 0x80) != 0) bytes_left += 64; if ((*lsr & UMP_UART_LSR_TX_MASK) == 0) bytes_left += 1; /* We return Not Active if we get any kind of error */ exit_is_tx_active: dev_dbg(&port->port->dev, "%s - return %d\n", __func__, bytes_left); kfree(lsr); kfree(oedb); return bytes_left; } static void chase_port(struct edgeport_port *port, unsigned long timeout, int flush) { int baud_rate; struct tty_struct *tty = tty_port_tty_get(&port->port->port); struct usb_serial *serial = port->port->serial; wait_queue_t wait; unsigned long flags; if (!timeout) timeout = (HZ * EDGE_CLOSING_WAIT)/100; /* wait for data to drain from the buffer */ spin_lock_irqsave(&port->ep_lock, flags); init_waitqueue_entry(&wait, current); add_wait_queue(&tty->write_wait, &wait); for (;;) { set_current_state(TASK_INTERRUPTIBLE); if (kfifo_len(&port->write_fifo) == 0 || timeout == 0 || signal_pending(current) || serial->disconnected) /* disconnect */ break; spin_unlock_irqrestore(&port->ep_lock, flags); timeout = schedule_timeout(timeout); spin_lock_irqsave(&port->ep_lock, flags); } set_current_state(TASK_RUNNING); remove_wait_queue(&tty->write_wait, &wait); if (flush) kfifo_reset_out(&port->write_fifo); spin_unlock_irqrestore(&port->ep_lock, flags); tty_kref_put(tty); /* wait for data to drain from the device */ timeout += jiffies; while ((long)(jiffies - timeout) < 0 && !signal_pending(current) && !serial->disconnected) { /* not disconnected */ if (!tx_active(port)) break; msleep(10); } /* disconnected */ if (serial->disconnected) return; /* wait one more character time, based on baud rate */ /* (tx_active doesn't seem to wait for the last byte) */ baud_rate = port->baud_rate; if (baud_rate == 0) baud_rate = 50; msleep(max(1, DIV_ROUND_UP(10000, baud_rate))); } static int choose_config(struct usb_device *dev) { /* * There may be multiple configurations on this device, in which case * we would need to read and parse all of them to find out which one * we want. However, we just support one config at this point, * configuration # 1, which is Config Descriptor 0. */ dev_dbg(&dev->dev, "%s - Number of Interfaces = %d\n", __func__, dev->config->desc.bNumInterfaces); dev_dbg(&dev->dev, "%s - MAX Power = %d\n", __func__, dev->config->desc.bMaxPower * 2); if (dev->config->desc.bNumInterfaces != 1) { dev_err(&dev->dev, "%s - bNumInterfaces is not 1, ERROR!\n", __func__); return -ENODEV; } return 0; } static int read_rom(struct edgeport_serial *serial, int start_address, int length, __u8 *buffer) { int status; if (serial->product_info.TiMode == TI_MODE_DOWNLOAD) { status = read_download_mem(serial->serial->dev, start_address, length, serial->TI_I2C_Type, buffer); } else { status = read_boot_mem(serial, start_address, length, buffer); } return status; } static int write_rom(struct edgeport_serial *serial, int start_address, int length, __u8 *buffer) { if (serial->product_info.TiMode == TI_MODE_BOOT) return write_boot_mem(serial, start_address, length, buffer); if (serial->product_info.TiMode == TI_MODE_DOWNLOAD) return write_i2c_mem(serial, start_address, length, serial->TI_I2C_Type, buffer); return -EINVAL; } /* Read a descriptor header from I2C based on type */ static int get_descriptor_addr(struct edgeport_serial *serial, int desc_type, struct ti_i2c_desc *rom_desc) { int start_address; int status; /* Search for requested descriptor in I2C */ start_address = 2; do { status = read_rom(serial, start_address, sizeof(struct ti_i2c_desc), (__u8 *)rom_desc); if (status) return 0; if (rom_desc->Type == desc_type) return start_address; start_address = start_address + sizeof(struct ti_i2c_desc) + rom_desc->Size; } while ((start_address < TI_MAX_I2C_SIZE) && rom_desc->Type); return 0; } /* Validate descriptor checksum */ static int valid_csum(struct ti_i2c_desc *rom_desc, __u8 *buffer) { __u16 i; __u8 cs = 0; for (i = 0; i < rom_desc->Size; i++) cs = (__u8)(cs + buffer[i]); if (cs != rom_desc->CheckSum) { pr_debug("%s - Mismatch %x - %x", __func__, rom_desc->CheckSum, cs); return -EINVAL; } return 0; } /* Make sure that the I2C image is good */ static int check_i2c_image(struct edgeport_serial *serial) { struct device *dev = &serial->serial->dev->dev; int status = 0; struct ti_i2c_desc *rom_desc; int start_address = 2; __u8 *buffer; __u16 ttype; rom_desc = kmalloc(sizeof(*rom_desc), GFP_KERNEL); if (!rom_desc) { dev_err(dev, "%s - out of memory\n", __func__); return -ENOMEM; } buffer = kmalloc(TI_MAX_I2C_SIZE, GFP_KERNEL); if (!buffer) { dev_err(dev, "%s - out of memory when allocating buffer\n", __func__); kfree(rom_desc); return -ENOMEM; } /* Read the first byte (Signature0) must be 0x52 or 0x10 */ status = read_rom(serial, 0, 1, buffer); if (status) goto out; if (*buffer != UMP5152 && *buffer != UMP3410) { dev_err(dev, "%s - invalid buffer signature\n", __func__); status = -ENODEV; goto out; } do { /* Validate the I2C */ status = read_rom(serial, start_address, sizeof(struct ti_i2c_desc), (__u8 *)rom_desc); if (status) break; if ((start_address + sizeof(struct ti_i2c_desc) + rom_desc->Size) > TI_MAX_I2C_SIZE) { status = -ENODEV; dev_dbg(dev, "%s - structure too big, erroring out.\n", __func__); break; } dev_dbg(dev, "%s Type = 0x%x\n", __func__, rom_desc->Type); /* Skip type 2 record */ ttype = rom_desc->Type & 0x0f; if (ttype != I2C_DESC_TYPE_FIRMWARE_BASIC && ttype != I2C_DESC_TYPE_FIRMWARE_AUTO) { /* Read the descriptor data */ status = read_rom(serial, start_address + sizeof(struct ti_i2c_desc), rom_desc->Size, buffer); if (status) break; status = valid_csum(rom_desc, buffer); if (status) break; } start_address = start_address + sizeof(struct ti_i2c_desc) + rom_desc->Size; } while ((rom_desc->Type != I2C_DESC_TYPE_ION) && (start_address < TI_MAX_I2C_SIZE)); if ((rom_desc->Type != I2C_DESC_TYPE_ION) || (start_address > TI_MAX_I2C_SIZE)) status = -ENODEV; out: kfree(buffer); kfree(rom_desc); return status; } static int get_manuf_info(struct edgeport_serial *serial, __u8 *buffer) { int status; int start_address; struct ti_i2c_desc *rom_desc; struct edge_ti_manuf_descriptor *desc; struct device *dev = &serial->serial->dev->dev; rom_desc = kmalloc(sizeof(*rom_desc), GFP_KERNEL); if (!rom_desc) { dev_err(dev, "%s - out of memory\n", __func__); return -ENOMEM; } start_address = get_descriptor_addr(serial, I2C_DESC_TYPE_ION, rom_desc); if (!start_address) { dev_dbg(dev, "%s - Edge Descriptor not found in I2C\n", __func__); status = -ENODEV; goto exit; } /* Read the descriptor data */ status = read_rom(serial, start_address+sizeof(struct ti_i2c_desc), rom_desc->Size, buffer); if (status) goto exit; status = valid_csum(rom_desc, buffer); desc = (struct edge_ti_manuf_descriptor *)buffer; dev_dbg(dev, "%s - IonConfig 0x%x\n", __func__, desc->IonConfig); dev_dbg(dev, "%s - Version %d\n", __func__, desc->Version); dev_dbg(dev, "%s - Cpu/Board 0x%x\n", __func__, desc->CpuRev_BoardRev); dev_dbg(dev, "%s - NumPorts %d\n", __func__, desc->NumPorts); dev_dbg(dev, "%s - NumVirtualPorts %d\n", __func__, desc->NumVirtualPorts); dev_dbg(dev, "%s - TotalPorts %d\n", __func__, desc->TotalPorts); exit: kfree(rom_desc); return status; } /* Build firmware header used for firmware update */ static int build_i2c_fw_hdr(__u8 *header, struct device *dev) { __u8 *buffer; int buffer_size; int i; int err; __u8 cs = 0; struct ti_i2c_desc *i2c_header; struct ti_i2c_image_header *img_header; struct ti_i2c_firmware_rec *firmware_rec; const struct firmware *fw; const char *fw_name = "edgeport/down3.bin"; /* In order to update the I2C firmware we must change the type 2 record * to type 0xF2. This will force the UMP to come up in Boot Mode. * Then while in boot mode, the driver will download the latest * firmware (padded to 15.5k) into the UMP ram. And finally when the * device comes back up in download mode the driver will cause the new * firmware to be copied from the UMP Ram to I2C and the firmware will * update the record type from 0xf2 to 0x02. */ /* Allocate a 15.5k buffer + 2 bytes for version number * (Firmware Record) */ buffer_size = (((1024 * 16) - 512 ) + sizeof(struct ti_i2c_firmware_rec)); buffer = kmalloc(buffer_size, GFP_KERNEL); if (!buffer) { dev_err(dev, "%s - out of memory\n", __func__); return -ENOMEM; } // Set entire image of 0xffs memset(buffer, 0xff, buffer_size); err = request_firmware(&fw, fw_name, dev); if (err) { dev_err(dev, "Failed to load image \"%s\" err %d\n", fw_name, err); kfree(buffer); return err; } /* Save Download Version Number */ OperationalMajorVersion = fw->data[0]; OperationalMinorVersion = fw->data[1]; OperationalBuildNumber = fw->data[2] | (fw->data[3] << 8); /* Copy version number into firmware record */ firmware_rec = (struct ti_i2c_firmware_rec *)buffer; firmware_rec->Ver_Major = OperationalMajorVersion; firmware_rec->Ver_Minor = OperationalMinorVersion; /* Pointer to fw_down memory image */ img_header = (struct ti_i2c_image_header *)&fw->data[4]; memcpy(buffer + sizeof(struct ti_i2c_firmware_rec), &fw->data[4 + sizeof(struct ti_i2c_image_header)], le16_to_cpu(img_header->Length)); release_firmware(fw); for (i=0; i < buffer_size; i++) { cs = (__u8)(cs + buffer[i]); } kfree(buffer); /* Build new header */ i2c_header = (struct ti_i2c_desc *)header; firmware_rec = (struct ti_i2c_firmware_rec*)i2c_header->Data; i2c_header->Type = I2C_DESC_TYPE_FIRMWARE_BLANK; i2c_header->Size = (__u16)buffer_size; i2c_header->CheckSum = cs; firmware_rec->Ver_Major = OperationalMajorVersion; firmware_rec->Ver_Minor = OperationalMinorVersion; return 0; } /* Try to figure out what type of I2c we have */ static int i2c_type_bootmode(struct edgeport_serial *serial) { struct device *dev = &serial->serial->dev->dev; int status; u8 *data; data = kmalloc(1, GFP_KERNEL); if (!data) { dev_err(dev, "%s - out of memory\n", __func__); return -ENOMEM; } /* Try to read type 2 */ status = ti_vread_sync(serial->serial->dev, UMPC_MEMORY_READ, DTK_ADDR_SPACE_I2C_TYPE_II, 0, data, 0x01); if (status) dev_dbg(dev, "%s - read 2 status error = %d\n", __func__, status); else dev_dbg(dev, "%s - read 2 data = 0x%x\n", __func__, *data); if ((!status) && (*data == UMP5152 || *data == UMP3410)) { dev_dbg(dev, "%s - ROM_TYPE_II\n", __func__); serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II; goto out; } /* Try to read type 3 */ status = ti_vread_sync(serial->serial->dev, UMPC_MEMORY_READ, DTK_ADDR_SPACE_I2C_TYPE_III, 0, data, 0x01); if (status) dev_dbg(dev, "%s - read 3 status error = %d\n", __func__, status); else dev_dbg(dev, "%s - read 2 data = 0x%x\n", __func__, *data); if ((!status) && (*data == UMP5152 || *data == UMP3410)) { dev_dbg(dev, "%s - ROM_TYPE_III\n", __func__); serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_III; goto out; } dev_dbg(dev, "%s - Unknown\n", __func__); serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II; status = -ENODEV; out: kfree(data); return status; } static int bulk_xfer(struct usb_serial *serial, void *buffer, int length, int *num_sent) { int status; status = usb_bulk_msg(serial->dev, usb_sndbulkpipe(serial->dev, serial->port[0]->bulk_out_endpointAddress), buffer, length, num_sent, 1000); return status; } /* Download given firmware image to the device (IN BOOT MODE) */ static int download_code(struct edgeport_serial *serial, __u8 *image, int image_length) { int status = 0; int pos; int transfer; int done; /* Transfer firmware image */ for (pos = 0; pos < image_length; ) { /* Read the next buffer from file */ transfer = image_length - pos; if (transfer > EDGE_FW_BULK_MAX_PACKET_SIZE) transfer = EDGE_FW_BULK_MAX_PACKET_SIZE; /* Transfer data */ status = bulk_xfer(serial->serial, &image[pos], transfer, &done); if (status) break; /* Advance buffer pointer */ pos += done; } return status; } /* FIXME!!! */ static int config_boot_dev(struct usb_device *dev) { return 0; } static int ti_cpu_rev(struct edge_ti_manuf_descriptor *desc) { return TI_GET_CPU_REVISION(desc->CpuRev_BoardRev); } /** * DownloadTIFirmware - Download run-time operating firmware to the TI5052 * * This routine downloads the main operating code into the TI5052, using the * boot code already burned into E2PROM or ROM. */ static int download_fw(struct edgeport_serial *serial) { struct device *dev = &serial->serial->dev->dev; int status = 0; int start_address; struct edge_ti_manuf_descriptor *ti_manuf_desc; struct usb_interface_descriptor *interface; int download_cur_ver; int download_new_ver; /* This routine is entered by both the BOOT mode and the Download mode * We can determine which code is running by the reading the config * descriptor and if we have only one bulk pipe it is in boot mode */ serial->product_info.hardware_type = HARDWARE_TYPE_TIUMP; /* Default to type 2 i2c */ serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II; status = choose_config(serial->serial->dev); if (status) return status; interface = &serial->serial->interface->cur_altsetting->desc; if (!interface) { dev_err(dev, "%s - no interface set, error!\n", __func__); return -ENODEV; } /* * Setup initial mode -- the default mode 0 is TI_MODE_CONFIGURING * if we have more than one endpoint we are definitely in download * mode */ if (interface->bNumEndpoints > 1) serial->product_info.TiMode = TI_MODE_DOWNLOAD; else /* Otherwise we will remain in configuring mode */ serial->product_info.TiMode = TI_MODE_CONFIGURING; /********************************************************************/ /* Download Mode */ /********************************************************************/ if (serial->product_info.TiMode == TI_MODE_DOWNLOAD) { struct ti_i2c_desc *rom_desc; dev_dbg(dev, "%s - RUNNING IN DOWNLOAD MODE\n", __func__); status = check_i2c_image(serial); if (status) { dev_dbg(dev, "%s - DOWNLOAD MODE -- BAD I2C\n", __func__); return status; } /* Validate Hardware version number * Read Manufacturing Descriptor from TI Based Edgeport */ ti_manuf_desc = kmalloc(sizeof(*ti_manuf_desc), GFP_KERNEL); if (!ti_manuf_desc) { dev_err(dev, "%s - out of memory.\n", __func__); return -ENOMEM; } status = get_manuf_info(serial, (__u8 *)ti_manuf_desc); if (status) { kfree(ti_manuf_desc); return status; } /* Check version number of ION descriptor */ if (!ignore_cpu_rev && ti_cpu_rev(ti_manuf_desc) < 2) { dev_dbg(dev, "%s - Wrong CPU Rev %d (Must be 2)\n", __func__, ti_cpu_rev(ti_manuf_desc)); kfree(ti_manuf_desc); return -EINVAL; } rom_desc = kmalloc(sizeof(*rom_desc), GFP_KERNEL); if (!rom_desc) { dev_err(dev, "%s - out of memory.\n", __func__); kfree(ti_manuf_desc); return -ENOMEM; } /* Search for type 2 record (firmware record) */ start_address = get_descriptor_addr(serial, I2C_DESC_TYPE_FIRMWARE_BASIC, rom_desc); if (start_address != 0) { struct ti_i2c_firmware_rec *firmware_version; u8 *record; dev_dbg(dev, "%s - Found Type FIRMWARE (Type 2) record\n", __func__); firmware_version = kmalloc(sizeof(*firmware_version), GFP_KERNEL); if (!firmware_version) { dev_err(dev, "%s - out of memory.\n", __func__); kfree(rom_desc); kfree(ti_manuf_desc); return -ENOMEM; } /* Validate version number * Read the descriptor data */ status = read_rom(serial, start_address + sizeof(struct ti_i2c_desc), sizeof(struct ti_i2c_firmware_rec), (__u8 *)firmware_version); if (status) { kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return status; } /* Check version number of download with current version in I2c */ download_cur_ver = (firmware_version->Ver_Major << 8) + (firmware_version->Ver_Minor); download_new_ver = (OperationalMajorVersion << 8) + (OperationalMinorVersion); dev_dbg(dev, "%s - >> FW Versions Device %d.%d Driver %d.%d\n", __func__, firmware_version->Ver_Major, firmware_version->Ver_Minor, OperationalMajorVersion, OperationalMinorVersion); /* Check if we have an old version in the I2C and update if necessary */ if (download_cur_ver < download_new_ver) { dev_dbg(dev, "%s - Update I2C dld from %d.%d to %d.%d\n", __func__, firmware_version->Ver_Major, firmware_version->Ver_Minor, OperationalMajorVersion, OperationalMinorVersion); record = kmalloc(1, GFP_KERNEL); if (!record) { dev_err(dev, "%s - out of memory.\n", __func__); kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return -ENOMEM; } /* In order to update the I2C firmware we must * change the type 2 record to type 0xF2. This * will force the UMP to come up in Boot Mode. * Then while in boot mode, the driver will * download the latest firmware (padded to * 15.5k) into the UMP ram. Finally when the * device comes back up in download mode the * driver will cause the new firmware to be * copied from the UMP Ram to I2C and the * firmware will update the record type from * 0xf2 to 0x02. */ *record = I2C_DESC_TYPE_FIRMWARE_BLANK; /* Change the I2C Firmware record type to 0xf2 to trigger an update */ status = write_rom(serial, start_address, sizeof(*record), record); if (status) { kfree(record); kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return status; } /* verify the write -- must do this in order * for write to complete before we do the * hardware reset */ status = read_rom(serial, start_address, sizeof(*record), record); if (status) { kfree(record); kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return status; } if (*record != I2C_DESC_TYPE_FIRMWARE_BLANK) { dev_err(dev, "%s - error resetting device\n", __func__); kfree(record); kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return -ENODEV; } dev_dbg(dev, "%s - HARDWARE RESET\n", __func__); /* Reset UMP -- Back to BOOT MODE */ status = ti_vsend_sync(serial->serial->dev, UMPC_HARDWARE_RESET, 0, 0, NULL, 0); dev_dbg(dev, "%s - HARDWARE RESET return %d\n", __func__, status); /* return an error on purpose. */ kfree(record); kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return -ENODEV; } kfree(firmware_version); } /* Search for type 0xF2 record (firmware blank record) */ else if ((start_address = get_descriptor_addr(serial, I2C_DESC_TYPE_FIRMWARE_BLANK, rom_desc)) != 0) { #define HEADER_SIZE (sizeof(struct ti_i2c_desc) + \ sizeof(struct ti_i2c_firmware_rec)) __u8 *header; __u8 *vheader; header = kmalloc(HEADER_SIZE, GFP_KERNEL); if (!header) { dev_err(dev, "%s - out of memory.\n", __func__); kfree(rom_desc); kfree(ti_manuf_desc); return -ENOMEM; } vheader = kmalloc(HEADER_SIZE, GFP_KERNEL); if (!vheader) { dev_err(dev, "%s - out of memory.\n", __func__); kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return -ENOMEM; } dev_dbg(dev, "%s - Found Type BLANK FIRMWARE (Type F2) record\n", __func__); /* * In order to update the I2C firmware we must change * the type 2 record to type 0xF2. This will force the * UMP to come up in Boot Mode. Then while in boot * mode, the driver will download the latest firmware * (padded to 15.5k) into the UMP ram. Finally when the * device comes back up in download mode the driver * will cause the new firmware to be copied from the * UMP Ram to I2C and the firmware will update the * record type from 0xf2 to 0x02. */ status = build_i2c_fw_hdr(header, dev); if (status) { kfree(vheader); kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return -EINVAL; } /* Update I2C with type 0xf2 record with correct size and checksum */ status = write_rom(serial, start_address, HEADER_SIZE, header); if (status) { kfree(vheader); kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return -EINVAL; } /* verify the write -- must do this in order for write to complete before we do the hardware reset */ status = read_rom(serial, start_address, HEADER_SIZE, vheader); if (status) { dev_dbg(dev, "%s - can't read header back\n", __func__); kfree(vheader); kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return status; } if (memcmp(vheader, header, HEADER_SIZE)) { dev_dbg(dev, "%s - write download record failed\n", __func__); kfree(vheader); kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return -EINVAL; } kfree(vheader); kfree(header); dev_dbg(dev, "%s - Start firmware update\n", __func__); /* Tell firmware to copy download image into I2C */ status = ti_vsend_sync(serial->serial->dev, UMPC_COPY_DNLD_TO_I2C, 0, 0, NULL, 0); dev_dbg(dev, "%s - Update complete 0x%x\n", __func__, status); if (status) { dev_err(dev, "%s - UMPC_COPY_DNLD_TO_I2C failed\n", __func__); kfree(rom_desc); kfree(ti_manuf_desc); return status; } } // The device is running the download code kfree(rom_desc); kfree(ti_manuf_desc); return 0; } /********************************************************************/ /* Boot Mode */ /********************************************************************/ dev_dbg(dev, "%s - RUNNING IN BOOT MODE\n", __func__); /* Configure the TI device so we can use the BULK pipes for download */ status = config_boot_dev(serial->serial->dev); if (status) return status; if (le16_to_cpu(serial->serial->dev->descriptor.idVendor) != USB_VENDOR_ID_ION) { dev_dbg(dev, "%s - VID = 0x%x\n", __func__, le16_to_cpu(serial->serial->dev->descriptor.idVendor)); serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II; goto stayinbootmode; } /* We have an ION device (I2c Must be programmed) Determine I2C image type */ if (i2c_type_bootmode(serial)) goto stayinbootmode; /* Check for ION Vendor ID and that the I2C is valid */ if (!check_i2c_image(serial)) { struct ti_i2c_image_header *header; int i; __u8 cs = 0; __u8 *buffer; int buffer_size; int err; const struct firmware *fw; const char *fw_name = "edgeport/down3.bin"; /* Validate Hardware version number * Read Manufacturing Descriptor from TI Based Edgeport */ ti_manuf_desc = kmalloc(sizeof(*ti_manuf_desc), GFP_KERNEL); if (!ti_manuf_desc) { dev_err(dev, "%s - out of memory.\n", __func__); return -ENOMEM; } status = get_manuf_info(serial, (__u8 *)ti_manuf_desc); if (status) { kfree(ti_manuf_desc); goto stayinbootmode; } /* Check for version 2 */ if (!ignore_cpu_rev && ti_cpu_rev(ti_manuf_desc) < 2) { dev_dbg(dev, "%s - Wrong CPU Rev %d (Must be 2)\n", __func__, ti_cpu_rev(ti_manuf_desc)); kfree(ti_manuf_desc); goto stayinbootmode; } kfree(ti_manuf_desc); /* * In order to update the I2C firmware we must change the type * 2 record to type 0xF2. This will force the UMP to come up * in Boot Mode. Then while in boot mode, the driver will * download the latest firmware (padded to 15.5k) into the * UMP ram. Finally when the device comes back up in download * mode the driver will cause the new firmware to be copied * from the UMP Ram to I2C and the firmware will update the * record type from 0xf2 to 0x02. * * Do we really have to copy the whole firmware image, * or could we do this in place! */ /* Allocate a 15.5k buffer + 3 byte header */ buffer_size = (((1024 * 16) - 512) + sizeof(struct ti_i2c_image_header)); buffer = kmalloc(buffer_size, GFP_KERNEL); if (!buffer) { dev_err(dev, "%s - out of memory\n", __func__); return -ENOMEM; } /* Initialize the buffer to 0xff (pad the buffer) */ memset(buffer, 0xff, buffer_size); err = request_firmware(&fw, fw_name, dev); if (err) { dev_err(dev, "Failed to load image \"%s\" err %d\n", fw_name, err); kfree(buffer); return err; } memcpy(buffer, &fw->data[4], fw->size - 4); release_firmware(fw); for (i = sizeof(struct ti_i2c_image_header); i < buffer_size; i++) { cs = (__u8)(cs + buffer[i]); } header = (struct ti_i2c_image_header *)buffer; /* update length and checksum after padding */ header->Length = cpu_to_le16((__u16)(buffer_size - sizeof(struct ti_i2c_image_header))); header->CheckSum = cs; /* Download the operational code */ dev_dbg(dev, "%s - Downloading operational code image (TI UMP)\n", __func__); status = download_code(serial, buffer, buffer_size); kfree(buffer); if (status) { dev_dbg(dev, "%s - Error downloading operational code image\n", __func__); return status; } /* Device will reboot */ serial->product_info.TiMode = TI_MODE_TRANSITIONING; dev_dbg(dev, "%s - Download successful -- Device rebooting...\n", __func__); /* return an error on purpose */ return -ENODEV; } stayinbootmode: /* Eprom is invalid or blank stay in boot mode */ dev_dbg(dev, "%s - STAYING IN BOOT MODE\n", __func__); serial->product_info.TiMode = TI_MODE_BOOT; return 0; } static int ti_do_config(struct edgeport_port *port, int feature, int on) { int port_number = port->port->number - port->port->serial->minor; on = !!on; /* 1 or 0 not bitmask */ return send_cmd(port->port->serial->dev, feature, (__u8)(UMPM_UART1_PORT + port_number), on, NULL, 0); } static int restore_mcr(struct edgeport_port *port, __u8 mcr) { int status = 0; dev_dbg(&port->port->dev, "%s - %x\n", __func__, mcr); status = ti_do_config(port, UMPC_SET_CLR_DTR, mcr & MCR_DTR); if (status) return status; status = ti_do_config(port, UMPC_SET_CLR_RTS, mcr & MCR_RTS); if (status) return status; return ti_do_config(port, UMPC_SET_CLR_LOOPBACK, mcr & MCR_LOOPBACK); } /* Convert TI LSR to standard UART flags */ static __u8 map_line_status(__u8 ti_lsr) { __u8 lsr = 0; #define MAP_FLAG(flagUmp, flagUart) \ if (ti_lsr & flagUmp) \ lsr |= flagUart; MAP_FLAG(UMP_UART_LSR_OV_MASK, LSR_OVER_ERR) /* overrun */ MAP_FLAG(UMP_UART_LSR_PE_MASK, LSR_PAR_ERR) /* parity error */ MAP_FLAG(UMP_UART_LSR_FE_MASK, LSR_FRM_ERR) /* framing error */ MAP_FLAG(UMP_UART_LSR_BR_MASK, LSR_BREAK) /* break detected */ MAP_FLAG(UMP_UART_LSR_RX_MASK, LSR_RX_AVAIL) /* rx data available */ MAP_FLAG(UMP_UART_LSR_TX_MASK, LSR_TX_EMPTY) /* tx hold reg empty */ #undef MAP_FLAG return lsr; } static void handle_new_msr(struct edgeport_port *edge_port, __u8 msr) { struct async_icount *icount; struct tty_struct *tty; dev_dbg(&edge_port->port->dev, "%s - %02x\n", __func__, msr); if (msr & (EDGEPORT_MSR_DELTA_CTS | EDGEPORT_MSR_DELTA_DSR | EDGEPORT_MSR_DELTA_RI | EDGEPORT_MSR_DELTA_CD)) { icount = &edge_port->icount; /* update input line counters */ if (msr & EDGEPORT_MSR_DELTA_CTS) icount->cts++; if (msr & EDGEPORT_MSR_DELTA_DSR) icount->dsr++; if (msr & EDGEPORT_MSR_DELTA_CD) icount->dcd++; if (msr & EDGEPORT_MSR_DELTA_RI) icount->rng++; wake_up_interruptible(&edge_port->delta_msr_wait); } /* Save the new modem status */ edge_port->shadow_msr = msr & 0xf0; tty = tty_port_tty_get(&edge_port->port->port); /* handle CTS flow control */ if (tty && C_CRTSCTS(tty)) { if (msr & EDGEPORT_MSR_CTS) { tty->hw_stopped = 0; tty_wakeup(tty); } else { tty->hw_stopped = 1; } } tty_kref_put(tty); } static void handle_new_lsr(struct edgeport_port *edge_port, int lsr_data, __u8 lsr, __u8 data) { struct async_icount *icount; __u8 new_lsr = (__u8)(lsr & (__u8)(LSR_OVER_ERR | LSR_PAR_ERR | LSR_FRM_ERR | LSR_BREAK)); struct tty_struct *tty; dev_dbg(&edge_port->port->dev, "%s - %02x\n", __func__, new_lsr); edge_port->shadow_lsr = lsr; if (new_lsr & LSR_BREAK) /* * Parity and Framing errors only count if they * occur exclusive of a break being received. */ new_lsr &= (__u8)(LSR_OVER_ERR | LSR_BREAK); /* Place LSR data byte into Rx buffer */ if (lsr_data) { tty = tty_port_tty_get(&edge_port->port->port); if (tty) { edge_tty_recv(&edge_port->port->dev, tty, &data, 1); tty_kref_put(tty); } } /* update input line counters */ icount = &edge_port->icount; if (new_lsr & LSR_BREAK) icount->brk++; if (new_lsr & LSR_OVER_ERR) icount->overrun++; if (new_lsr & LSR_PAR_ERR) icount->parity++; if (new_lsr & LSR_FRM_ERR) icount->frame++; } static void edge_interrupt_callback(struct urb *urb) { struct edgeport_serial *edge_serial = urb->context; struct usb_serial_port *port; struct edgeport_port *edge_port; struct device *dev; unsigned char *data = urb->transfer_buffer; int length = urb->actual_length; int port_number; int function; int retval; __u8 lsr; __u8 msr; int status = urb->status; switch (status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status); return; default: dev_err(&urb->dev->dev, "%s - nonzero urb status received: " "%d\n", __func__, status); goto exit; } if (!length) { dev_dbg(&urb->dev->dev, "%s - no data in urb\n", __func__); goto exit; } dev = &edge_serial->serial->dev->dev; usb_serial_debug_data(dev, __func__, length, data); if (length != 2) { dev_dbg(dev, "%s - expecting packet of size 2, got %d\n", __func__, length); goto exit; } port_number = TIUMP_GET_PORT_FROM_CODE(data[0]); function = TIUMP_GET_FUNC_FROM_CODE(data[0]); dev_dbg(dev, "%s - port_number %d, function %d, info 0x%x\n", __func__, port_number, function, data[1]); port = edge_serial->serial->port[port_number]; edge_port = usb_get_serial_port_data(port); if (!edge_port) { dev_dbg(dev, "%s - edge_port not found\n", __func__); return; } switch (function) { case TIUMP_INTERRUPT_CODE_LSR: lsr = map_line_status(data[1]); if (lsr & UMP_UART_LSR_DATA_MASK) { /* Save the LSR event for bulk read completion routine */ dev_dbg(dev, "%s - LSR Event Port %u LSR Status = %02x\n", __func__, port_number, lsr); edge_port->lsr_event = 1; edge_port->lsr_mask = lsr; } else { dev_dbg(dev, "%s - ===== Port %d LSR Status = %02x ======\n", __func__, port_number, lsr); handle_new_lsr(edge_port, 0, lsr, 0); } break; case TIUMP_INTERRUPT_CODE_MSR: /* MSR */ /* Copy MSR from UMP */ msr = data[1]; dev_dbg(dev, "%s - ===== Port %u MSR Status = %02x ======\n", __func__, port_number, msr); handle_new_msr(edge_port, msr); break; default: dev_err(&urb->dev->dev, "%s - Unknown Interrupt code from UMP %x\n", __func__, data[1]); break; } exit: retval = usb_submit_urb(urb, GFP_ATOMIC); if (retval) dev_err(&urb->dev->dev, "%s - usb_submit_urb failed with result %d\n", __func__, retval); } static void edge_bulk_in_callback(struct urb *urb) { struct edgeport_port *edge_port = urb->context; struct device *dev = &edge_port->port->dev; unsigned char *data = urb->transfer_buffer; struct tty_struct *tty; int retval = 0; int port_number; int status = urb->status; switch (status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status); return; default: dev_err(&urb->dev->dev, "%s - nonzero read bulk status received: %d\n", __func__, status); } if (status == -EPIPE) goto exit; if (status) { dev_err(&urb->dev->dev, "%s - stopping read!\n", __func__); return; } port_number = edge_port->port->number - edge_port->port->serial->minor; if (edge_port->lsr_event) { edge_port->lsr_event = 0; dev_dbg(dev, "%s ===== Port %u LSR Status = %02x, Data = %02x ======\n", __func__, port_number, edge_port->lsr_mask, *data); handle_new_lsr(edge_port, 1, edge_port->lsr_mask, *data); /* Adjust buffer length/pointer */ --urb->actual_length; ++data; } tty = tty_port_tty_get(&edge_port->port->port); if (tty && urb->actual_length) { usb_serial_debug_data(dev, __func__, urb->actual_length, data); if (edge_port->close_pending) dev_dbg(dev, "%s - close pending, dropping data on the floor\n", __func__); else edge_tty_recv(dev, tty, data, urb->actual_length); edge_port->icount.rx += urb->actual_length; } tty_kref_put(tty); exit: /* continue read unless stopped */ spin_lock(&edge_port->ep_lock); if (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING) retval = usb_submit_urb(urb, GFP_ATOMIC); else if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPING) edge_port->ep_read_urb_state = EDGE_READ_URB_STOPPED; spin_unlock(&edge_port->ep_lock); if (retval) dev_err(dev, "%s - usb_submit_urb failed with result %d\n", __func__, retval); } static void edge_tty_recv(struct device *dev, struct tty_struct *tty, unsigned char *data, int length) { int queued; queued = tty_insert_flip_string(tty, data, length); if (queued < length) dev_err(dev, "%s - dropping data, %d bytes lost\n", __func__, length - queued); tty_flip_buffer_push(tty); } static void edge_bulk_out_callback(struct urb *urb) { struct usb_serial_port *port = urb->context; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int status = urb->status; struct tty_struct *tty; edge_port->ep_write_urb_in_use = 0; switch (status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status); return; default: dev_err_console(port, "%s - nonzero write bulk status " "received: %d\n", __func__, status); } /* send any buffered data */ tty = tty_port_tty_get(&port->port); edge_send(tty); tty_kref_put(tty); } static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) { struct edgeport_port *edge_port = usb_get_serial_port_data(port); struct edgeport_serial *edge_serial; struct usb_device *dev; struct urb *urb; int port_number; int status; u16 open_settings; u8 transaction_timeout; if (edge_port == NULL) return -ENODEV; port_number = port->number - port->serial->minor; switch (port_number) { case 0: edge_port->uart_base = UMPMEM_BASE_UART1; edge_port->dma_address = UMPD_OEDB1_ADDRESS; break; case 1: edge_port->uart_base = UMPMEM_BASE_UART2; edge_port->dma_address = UMPD_OEDB2_ADDRESS; break; default: dev_err(&port->dev, "Unknown port number!!!\n"); return -ENODEV; } dev_dbg(&port->dev, "%s - port_number = %d, uart_base = %04x, dma_address = %04x\n", __func__, port_number, edge_port->uart_base, edge_port->dma_address); dev = port->serial->dev; memset(&(edge_port->icount), 0x00, sizeof(edge_port->icount)); init_waitqueue_head(&edge_port->delta_msr_wait); /* turn off loopback */ status = ti_do_config(edge_port, UMPC_SET_CLR_LOOPBACK, 0); if (status) { dev_err(&port->dev, "%s - cannot send clear loopback command, %d\n", __func__, status); return status; } /* set up the port settings */ if (tty) edge_set_termios(tty, port, &tty->termios); /* open up the port */ /* milliseconds to timeout for DMA transfer */ transaction_timeout = 2; edge_port->ump_read_timeout = max(20, ((transaction_timeout * 3) / 2)); /* milliseconds to timeout for DMA transfer */ open_settings = (u8)(UMP_DMA_MODE_CONTINOUS | UMP_PIPE_TRANS_TIMEOUT_ENA | (transaction_timeout << 2)); dev_dbg(&port->dev, "%s - Sending UMPC_OPEN_PORT\n", __func__); /* Tell TI to open and start the port */ status = send_cmd(dev, UMPC_OPEN_PORT, (u8)(UMPM_UART1_PORT + port_number), open_settings, NULL, 0); if (status) { dev_err(&port->dev, "%s - cannot send open command, %d\n", __func__, status); return status; } /* Start the DMA? */ status = send_cmd(dev, UMPC_START_PORT, (u8)(UMPM_UART1_PORT + port_number), 0, NULL, 0); if (status) { dev_err(&port->dev, "%s - cannot send start DMA command, %d\n", __func__, status); return status; } /* Clear TX and RX buffers in UMP */ status = purge_port(port, UMP_PORT_DIR_OUT | UMP_PORT_DIR_IN); if (status) { dev_err(&port->dev, "%s - cannot send clear buffers command, %d\n", __func__, status); return status; } /* Read Initial MSR */ status = ti_vread_sync(dev, UMPC_READ_MSR, 0, (__u16)(UMPM_UART1_PORT + port_number), &edge_port->shadow_msr, 1); if (status) { dev_err(&port->dev, "%s - cannot send read MSR command, %d\n", __func__, status); return status; } dev_dbg(&port->dev, "ShadowMSR 0x%X\n", edge_port->shadow_msr); /* Set Initial MCR */ edge_port->shadow_mcr = MCR_RTS | MCR_DTR; dev_dbg(&port->dev, "ShadowMCR 0x%X\n", edge_port->shadow_mcr); edge_serial = edge_port->edge_serial; if (mutex_lock_interruptible(&edge_serial->es_lock)) return -ERESTARTSYS; if (edge_serial->num_ports_open == 0) { /* we are the first port to open, post the interrupt urb */ urb = edge_serial->serial->port[0]->interrupt_in_urb; if (!urb) { dev_err(&port->dev, "%s - no interrupt urb present, exiting\n", __func__); status = -EINVAL; goto release_es_lock; } urb->context = edge_serial; status = usb_submit_urb(urb, GFP_KERNEL); if (status) { dev_err(&port->dev, "%s - usb_submit_urb failed with value %d\n", __func__, status); goto release_es_lock; } } /* * reset the data toggle on the bulk endpoints to work around bug in * host controllers where things get out of sync some times */ usb_clear_halt(dev, port->write_urb->pipe); usb_clear_halt(dev, port->read_urb->pipe); /* start up our bulk read urb */ urb = port->read_urb; if (!urb) { dev_err(&port->dev, "%s - no read urb present, exiting\n", __func__); status = -EINVAL; goto unlink_int_urb; } edge_port->ep_read_urb_state = EDGE_READ_URB_RUNNING; urb->context = edge_port; status = usb_submit_urb(urb, GFP_KERNEL); if (status) { dev_err(&port->dev, "%s - read bulk usb_submit_urb failed with value %d\n", __func__, status); goto unlink_int_urb; } ++edge_serial->num_ports_open; goto release_es_lock; unlink_int_urb: if (edge_port->edge_serial->num_ports_open == 0) usb_kill_urb(port->serial->port[0]->interrupt_in_urb); release_es_lock: mutex_unlock(&edge_serial->es_lock); return status; } static void edge_close(struct usb_serial_port *port) { struct edgeport_serial *edge_serial; struct edgeport_port *edge_port; struct usb_serial *serial = port->serial; int port_number; edge_serial = usb_get_serial_data(port->serial); edge_port = usb_get_serial_port_data(port); if (edge_serial == NULL || edge_port == NULL) return; /* The bulkreadcompletion routine will check * this flag and dump add read data */ edge_port->close_pending = 1; /* chase the port close and flush */ chase_port(edge_port, (HZ * closing_wait) / 100, 1); usb_kill_urb(port->read_urb); usb_kill_urb(port->write_urb); edge_port->ep_write_urb_in_use = 0; /* assuming we can still talk to the device, * send a close port command to it */ dev_dbg(&port->dev, "%s - send umpc_close_port\n", __func__); port_number = port->number - port->serial->minor; mutex_lock(&serial->disc_mutex); if (!serial->disconnected) { send_cmd(serial->dev, UMPC_CLOSE_PORT, (__u8)(UMPM_UART1_PORT + port_number), 0, NULL, 0); } mutex_unlock(&serial->disc_mutex); mutex_lock(&edge_serial->es_lock); --edge_port->edge_serial->num_ports_open; if (edge_port->edge_serial->num_ports_open <= 0) { /* last port is now closed, let's shut down our interrupt urb */ usb_kill_urb(port->serial->port[0]->interrupt_in_urb); edge_port->edge_serial->num_ports_open = 0; } mutex_unlock(&edge_serial->es_lock); edge_port->close_pending = 0; } static int edge_write(struct tty_struct *tty, struct usb_serial_port *port, const unsigned char *data, int count) { struct edgeport_port *edge_port = usb_get_serial_port_data(port); if (count == 0) { dev_dbg(&port->dev, "%s - write request of 0 bytes\n", __func__); return 0; } if (edge_port == NULL) return -ENODEV; if (edge_port->close_pending == 1) return -ENODEV; count = kfifo_in_locked(&edge_port->write_fifo, data, count, &edge_port->ep_lock); edge_send(tty); return count; } static void edge_send(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; int count, result; struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); if (edge_port->ep_write_urb_in_use) { spin_unlock_irqrestore(&edge_port->ep_lock, flags); return; } count = kfifo_out(&edge_port->write_fifo, port->write_urb->transfer_buffer, port->bulk_out_size); if (count == 0) { spin_unlock_irqrestore(&edge_port->ep_lock, flags); return; } edge_port->ep_write_urb_in_use = 1; spin_unlock_irqrestore(&edge_port->ep_lock, flags); usb_serial_debug_data(&port->dev, __func__, count, port->write_urb->transfer_buffer); /* set up our urb */ port->write_urb->transfer_buffer_length = count; /* send the data out the bulk port */ result = usb_submit_urb(port->write_urb, GFP_ATOMIC); if (result) { dev_err_console(port, "%s - failed submitting write urb, error %d\n", __func__, result); edge_port->ep_write_urb_in_use = 0; /* TODO: reschedule edge_send */ } else edge_port->icount.tx += count; /* wakeup any process waiting for writes to complete */ /* there is now more room in the buffer for new writes */ if (tty) tty_wakeup(tty); } static int edge_write_room(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int room = 0; unsigned long flags; if (edge_port == NULL) return 0; if (edge_port->close_pending == 1) return 0; spin_lock_irqsave(&edge_port->ep_lock, flags); room = kfifo_avail(&edge_port->write_fifo); spin_unlock_irqrestore(&edge_port->ep_lock, flags); dev_dbg(&port->dev, "%s - returns %d\n", __func__, room); return room; } static int edge_chars_in_buffer(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int chars = 0; unsigned long flags; if (edge_port == NULL) return 0; if (edge_port->close_pending == 1) return 0; spin_lock_irqsave(&edge_port->ep_lock, flags); chars = kfifo_len(&edge_port->write_fifo); spin_unlock_irqrestore(&edge_port->ep_lock, flags); dev_dbg(&port->dev, "%s - returns %d\n", __func__, chars); return chars; } static void edge_throttle(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int status; if (edge_port == NULL) return; /* if we are implementing XON/XOFF, send the stop character */ if (I_IXOFF(tty)) { unsigned char stop_char = STOP_CHAR(tty); status = edge_write(tty, port, &stop_char, 1); if (status <= 0) { dev_err(&port->dev, "%s - failed to write stop character, %d\n", __func__, status); } } /* if we are implementing RTS/CTS, stop reads */ /* and the Edgeport will clear the RTS line */ if (C_CRTSCTS(tty)) stop_read(edge_port); } static void edge_unthrottle(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int status; if (edge_port == NULL) return; /* if we are implementing XON/XOFF, send the start character */ if (I_IXOFF(tty)) { unsigned char start_char = START_CHAR(tty); status = edge_write(tty, port, &start_char, 1); if (status <= 0) { dev_err(&port->dev, "%s - failed to write start character, %d\n", __func__, status); } } /* if we are implementing RTS/CTS, restart reads */ /* are the Edgeport will assert the RTS line */ if (C_CRTSCTS(tty)) { status = restart_read(edge_port); if (status) dev_err(&port->dev, "%s - read bulk usb_submit_urb failed: %d\n", __func__, status); } } static void stop_read(struct edgeport_port *edge_port) { unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); if (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING) edge_port->ep_read_urb_state = EDGE_READ_URB_STOPPING; edge_port->shadow_mcr &= ~MCR_RTS; spin_unlock_irqrestore(&edge_port->ep_lock, flags); } static int restart_read(struct edgeport_port *edge_port) { struct urb *urb; int status = 0; unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPED) { urb = edge_port->port->read_urb; status = usb_submit_urb(urb, GFP_ATOMIC); } edge_port->ep_read_urb_state = EDGE_READ_URB_RUNNING; edge_port->shadow_mcr |= MCR_RTS; spin_unlock_irqrestore(&edge_port->ep_lock, flags); return status; } static void change_port_settings(struct tty_struct *tty, struct edgeport_port *edge_port, struct ktermios *old_termios) { struct device *dev = &edge_port->port->dev; struct ump_uart_config *config; int baud; unsigned cflag; int status; int port_number = edge_port->port->number - edge_port->port->serial->minor; dev_dbg(dev, "%s - port %d\n", __func__, edge_port->port->number); config = kmalloc (sizeof (*config), GFP_KERNEL); if (!config) { tty->termios = *old_termios; dev_err(dev, "%s - out of memory\n", __func__); return; } cflag = tty->termios.c_cflag; config->wFlags = 0; /* These flags must be set */ config->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT; config->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR; config->bUartMode = (__u8)(edge_port->bUartMode); switch (cflag & CSIZE) { case CS5: config->bDataBits = UMP_UART_CHAR5BITS; dev_dbg(dev, "%s - data bits = 5\n", __func__); break; case CS6: config->bDataBits = UMP_UART_CHAR6BITS; dev_dbg(dev, "%s - data bits = 6\n", __func__); break; case CS7: config->bDataBits = UMP_UART_CHAR7BITS; dev_dbg(dev, "%s - data bits = 7\n", __func__); break; default: case CS8: config->bDataBits = UMP_UART_CHAR8BITS; dev_dbg(dev, "%s - data bits = 8\n", __func__); break; } if (cflag & PARENB) { if (cflag & PARODD) { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_ODDPARITY; dev_dbg(dev, "%s - parity = odd\n", __func__); } else { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_EVENPARITY; dev_dbg(dev, "%s - parity = even\n", __func__); } } else { config->bParity = UMP_UART_NOPARITY; dev_dbg(dev, "%s - parity = none\n", __func__); } if (cflag & CSTOPB) { config->bStopBits = UMP_UART_STOPBIT2; dev_dbg(dev, "%s - stop bits = 2\n", __func__); } else { config->bStopBits = UMP_UART_STOPBIT1; dev_dbg(dev, "%s - stop bits = 1\n", __func__); } /* figure out the flow control settings */ if (cflag & CRTSCTS) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW; config->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW; dev_dbg(dev, "%s - RTS/CTS is enabled\n", __func__); } else { dev_dbg(dev, "%s - RTS/CTS is disabled\n", __func__); tty->hw_stopped = 0; restart_read(edge_port); } /* if we are implementing XON/XOFF, set the start and stop character in the device */ config->cXon = START_CHAR(tty); config->cXoff = STOP_CHAR(tty); /* if we are implementing INBOUND XON/XOFF */ if (I_IXOFF(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_IN_X; dev_dbg(dev, "%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - INBOUND XON/XOFF is disabled\n", __func__); /* if we are implementing OUTBOUND XON/XOFF */ if (I_IXON(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X; dev_dbg(dev, "%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - OUTBOUND XON/XOFF is disabled\n", __func__); tty->termios.c_cflag &= ~CMSPAR; /* Round the baud rate */ baud = tty_get_baud_rate(tty); if (!baud) { /* pick a default, any default... */ baud = 9600; } else tty_encode_baud_rate(tty, baud, baud); edge_port->baud_rate = baud; config->wBaudRate = (__u16)((461550L + baud/2) / baud); /* FIXME: Recompute actual baud from divisor here */ dev_dbg(dev, "%s - baud rate = %d, wBaudRate = %d\n", __func__, baud, config->wBaudRate); dev_dbg(dev, "wBaudRate: %d\n", (int)(461550L / config->wBaudRate)); dev_dbg(dev, "wFlags: 0x%x\n", config->wFlags); dev_dbg(dev, "bDataBits: %d\n", config->bDataBits); dev_dbg(dev, "bParity: %d\n", config->bParity); dev_dbg(dev, "bStopBits: %d\n", config->bStopBits); dev_dbg(dev, "cXon: %d\n", config->cXon); dev_dbg(dev, "cXoff: %d\n", config->cXoff); dev_dbg(dev, "bUartMode: %d\n", config->bUartMode); /* move the word values into big endian mode */ cpu_to_be16s(&config->wFlags); cpu_to_be16s(&config->wBaudRate); status = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG, (__u8)(UMPM_UART1_PORT + port_number), 0, (__u8 *)config, sizeof(*config)); if (status) dev_dbg(dev, "%s - error %d when trying to write config to device\n", __func__, status); kfree(config); } static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port, struct ktermios *old_termios) { struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int cflag; cflag = tty->termios.c_cflag; dev_dbg(&port->dev, "%s - clfag %08x iflag %08x\n", __func__, tty->termios.c_cflag, tty->termios.c_iflag); dev_dbg(&port->dev, "%s - old clfag %08x old iflag %08x\n", __func__, old_termios->c_cflag, old_termios->c_iflag); dev_dbg(&port->dev, "%s - port %d\n", __func__, port->number); if (edge_port == NULL) return; /* change the port settings to the new ones specified */ change_port_settings(tty, edge_port, old_termios); } static int edge_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int mcr; unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); mcr = edge_port->shadow_mcr; if (set & TIOCM_RTS) mcr |= MCR_RTS; if (set & TIOCM_DTR) mcr |= MCR_DTR; if (set & TIOCM_LOOP) mcr |= MCR_LOOPBACK; if (clear & TIOCM_RTS) mcr &= ~MCR_RTS; if (clear & TIOCM_DTR) mcr &= ~MCR_DTR; if (clear & TIOCM_LOOP) mcr &= ~MCR_LOOPBACK; edge_port->shadow_mcr = mcr; spin_unlock_irqrestore(&edge_port->ep_lock, flags); restore_mcr(edge_port, mcr); return 0; } static int edge_tiocmget(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int result = 0; unsigned int msr; unsigned int mcr; unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); msr = edge_port->shadow_msr; mcr = edge_port->shadow_mcr; result = ((mcr & MCR_DTR) ? TIOCM_DTR: 0) /* 0x002 */ | ((mcr & MCR_RTS) ? TIOCM_RTS: 0) /* 0x004 */ | ((msr & EDGEPORT_MSR_CTS) ? TIOCM_CTS: 0) /* 0x020 */ | ((msr & EDGEPORT_MSR_CD) ? TIOCM_CAR: 0) /* 0x040 */ | ((msr & EDGEPORT_MSR_RI) ? TIOCM_RI: 0) /* 0x080 */ | ((msr & EDGEPORT_MSR_DSR) ? TIOCM_DSR: 0); /* 0x100 */ dev_dbg(&port->dev, "%s -- %x\n", __func__, result); spin_unlock_irqrestore(&edge_port->ep_lock, flags); return result; } static int edge_get_icount(struct tty_struct *tty, struct serial_icounter_struct *icount) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); struct async_icount *ic = &edge_port->icount; icount->cts = ic->cts; icount->dsr = ic->dsr; icount->rng = ic->rng; icount->dcd = ic->dcd; icount->tx = ic->tx; icount->rx = ic->rx; icount->frame = ic->frame; icount->parity = ic->parity; icount->overrun = ic->overrun; icount->brk = ic->brk; icount->buf_overrun = ic->buf_overrun; return 0; } static int get_serial_info(struct edgeport_port *edge_port, struct serial_struct __user *retinfo) { struct serial_struct tmp; if (!retinfo) return -EFAULT; memset(&tmp, 0, sizeof(tmp)); tmp.type = PORT_16550A; tmp.line = edge_port->port->serial->minor; tmp.port = edge_port->port->number; tmp.irq = 0; tmp.flags = ASYNC_SKIP_TEST | ASYNC_AUTO_IRQ; tmp.xmit_fifo_size = edge_port->port->bulk_out_size; tmp.baud_base = 9600; tmp.close_delay = 5*HZ; tmp.closing_wait = closing_wait; if (copy_to_user(retinfo, &tmp, sizeof(*retinfo))) return -EFAULT; return 0; } static int edge_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); struct async_icount cnow; struct async_icount cprev; dev_dbg(&port->dev, "%s - port %d, cmd = 0x%x\n", __func__, port->number, cmd); switch (cmd) { case TIOCGSERIAL: dev_dbg(&port->dev, "%s - TIOCGSERIAL\n", __func__); return get_serial_info(edge_port, (struct serial_struct __user *) arg); case TIOCMIWAIT: dev_dbg(&port->dev, "%s - TIOCMIWAIT\n", __func__); cprev = edge_port->icount; while (1) { interruptible_sleep_on(&edge_port->delta_msr_wait); /* see if a signal did it */ if (signal_pending(current)) return -ERESTARTSYS; cnow = edge_port->icount; if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr && cnow.dcd == cprev.dcd && cnow.cts == cprev.cts) return -EIO; /* no change => error */ if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) || ((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) || ((arg & TIOCM_CD) && (cnow.dcd != cprev.dcd)) || ((arg & TIOCM_CTS) && (cnow.cts != cprev.cts))) { return 0; } cprev = cnow; } /* not reached */ break; } return -ENOIOCTLCMD; } static void edge_break(struct tty_struct *tty, int break_state) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int status; int bv = 0; /* Off */ /* chase the port close */ chase_port(edge_port, 0, 0); if (break_state == -1) bv = 1; /* On */ status = ti_do_config(edge_port, UMPC_SET_CLR_BREAK, bv); if (status) dev_dbg(&port->dev, "%s - error %d sending break set/clear command.\n", __func__, status); } static int edge_startup(struct usb_serial *serial) { struct edgeport_serial *edge_serial; int status; /* create our private serial structure */ edge_serial = kzalloc(sizeof(struct edgeport_serial), GFP_KERNEL); if (edge_serial == NULL) { dev_err(&serial->dev->dev, "%s - Out of memory\n", __func__); return -ENOMEM; } mutex_init(&edge_serial->es_lock); edge_serial->serial = serial; usb_set_serial_data(serial, edge_serial); status = download_fw(edge_serial); if (status) { kfree(edge_serial); return status; } return 0; } static void edge_disconnect(struct usb_serial *serial) { } static void edge_release(struct usb_serial *serial) { kfree(usb_get_serial_data(serial)); } static int edge_port_probe(struct usb_serial_port *port) { struct edgeport_port *edge_port; int ret; edge_port = kzalloc(sizeof(*edge_port), GFP_KERNEL); if (!edge_port) return -ENOMEM; ret = kfifo_alloc(&edge_port->write_fifo, EDGE_OUT_BUF_SIZE, GFP_KERNEL); if (ret) { kfree(edge_port); return -ENOMEM; } spin_lock_init(&edge_port->ep_lock); edge_port->port = port; edge_port->edge_serial = usb_get_serial_data(port->serial); edge_port->bUartMode = default_uart_mode; usb_set_serial_port_data(port, edge_port); ret = edge_create_sysfs_attrs(port); if (ret) { kfifo_free(&edge_port->write_fifo); kfree(edge_port); return ret; } return 0; } static int edge_port_remove(struct usb_serial_port *port) { struct edgeport_port *edge_port; edge_port = usb_get_serial_port_data(port); edge_remove_sysfs_attrs(port); kfifo_free(&edge_port->write_fifo); kfree(edge_port); return 0; } /* Sysfs Attributes */ static ssize_t show_uart_mode(struct device *dev, struct device_attribute *attr, char *buf) { struct usb_serial_port *port = to_usb_serial_port(dev); struct edgeport_port *edge_port = usb_get_serial_port_data(port); return sprintf(buf, "%d\n", edge_port->bUartMode); } static ssize_t store_uart_mode(struct device *dev, struct device_attribute *attr, const char *valbuf, size_t count) { struct usb_serial_port *port = to_usb_serial_port(dev); struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int v = simple_strtoul(valbuf, NULL, 0); dev_dbg(dev, "%s: setting uart_mode = %d\n", __func__, v); if (v < 256) edge_port->bUartMode = v; else dev_err(dev, "%s - uart_mode %d is invalid\n", __func__, v); return count; } static DEVICE_ATTR(uart_mode, S_IWUSR | S_IRUGO, show_uart_mode, store_uart_mode); static int edge_create_sysfs_attrs(struct usb_serial_port *port) { return device_create_file(&port->dev, &dev_attr_uart_mode); } static int edge_remove_sysfs_attrs(struct usb_serial_port *port) { device_remove_file(&port->dev, &dev_attr_uart_mode); return 0; } static struct usb_serial_driver edgeport_1port_device = { .driver = { .owner = THIS_MODULE, .name = "edgeport_ti_1", }, .description = "Edgeport TI 1 port adapter", .id_table = edgeport_1port_id_table, .num_ports = 1, .open = edge_open, .close = edge_close, .throttle = edge_throttle, .unthrottle = edge_unthrottle, .attach = edge_startup, .disconnect = edge_disconnect, .release = edge_release, .port_probe = edge_port_probe, .port_remove = edge_port_remove, .ioctl = edge_ioctl, .set_termios = edge_set_termios, .tiocmget = edge_tiocmget, .tiocmset = edge_tiocmset, .get_icount = edge_get_icount, .write = edge_write, .write_room = edge_write_room, .chars_in_buffer = edge_chars_in_buffer, .break_ctl = edge_break, .read_int_callback = edge_interrupt_callback, .read_bulk_callback = edge_bulk_in_callback, .write_bulk_callback = edge_bulk_out_callback, }; static struct usb_serial_driver edgeport_2port_device = { .driver = { .owner = THIS_MODULE, .name = "edgeport_ti_2", }, .description = "Edgeport TI 2 port adapter", .id_table = edgeport_2port_id_table, .num_ports = 2, .open = edge_open, .close = edge_close, .throttle = edge_throttle, .unthrottle = edge_unthrottle, .attach = edge_startup, .disconnect = edge_disconnect, .release = edge_release, .port_probe = edge_port_probe, .port_remove = edge_port_remove, .ioctl = edge_ioctl, .set_termios = edge_set_termios, .tiocmget = edge_tiocmget, .tiocmset = edge_tiocmset, .write = edge_write, .write_room = edge_write_room, .chars_in_buffer = edge_chars_in_buffer, .break_ctl = edge_break, .read_int_callback = edge_interrupt_callback, .read_bulk_callback = edge_bulk_in_callback, .write_bulk_callback = edge_bulk_out_callback, }; static struct usb_serial_driver * const serial_drivers[] = { &edgeport_1port_device, &edgeport_2port_device, NULL }; module_usb_serial_driver(serial_drivers, id_table_combined); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); MODULE_FIRMWARE("edgeport/down3.bin"); module_param(closing_wait, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(closing_wait, "Maximum wait for data to drain, in .01 secs"); module_param(ignore_cpu_rev, bool, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(ignore_cpu_rev, "Ignore the cpu revision when connecting to a device"); module_param(default_uart_mode, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(default_uart_mode, "Default uart_mode, 0=RS232, ...");
./CrossVul/dataset_final_sorted/CWE-264/c/bad_5591_0
crossvul-cpp_data_bad_5655_0
/* -*- 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> * Copyright 2012, Sonny Karlsson * * 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 <string.h> #include <sys/stat.h> #include <unistd.h> /* network */ #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> /* Monkey API */ #include "MKPlugin.h" #include "mandril.h" MONKEY_PLUGIN("mandril", /* shortname */ "Mandril", /* name */ VERSION, /* version */ MK_PLUGIN_STAGE_10 | MK_PLUGIN_STAGE_30); /* hooks */ static struct mk_config *conf; /* Read database configuration parameters */ static int mk_security_conf(char *confdir) { int n; int ret = 0; unsigned long len; char *conf_path = NULL; char *_net, *_mask; struct mk_secure_ip_t *new_ip; struct mk_secure_url_t *new_url; struct mk_secure_deny_hotlink_t *new_deny_hotlink; struct mk_config_section *section; struct mk_config_entry *entry; struct mk_list *head; /* Read configuration */ mk_api->str_build(&conf_path, &len, "%s/mandril.conf", confdir); conf = mk_api->config_create(conf_path); section = mk_api->config_section_get(conf, "RULES"); mk_list_foreach(head, &section->entries) { entry = mk_list_entry(head, struct mk_config_entry, _head); /* Passing to internal struct */ if (strcasecmp(entry->key, "IP") == 0) { new_ip = mk_api->mem_alloc(sizeof(struct mk_secure_ip_t)); n = mk_api->str_search(entry->val, "/", 1); /* subnet */ if (n > 0) { /* split network addr and netmask */ _net = mk_api->str_copy_substr(entry->val, 0, n); _mask = mk_api->str_copy_substr(entry->val, n + 1, strlen(entry->val)); /* validations... */ if (!_net || !_mask) { mk_warn("Mandril: cannot parse entry '%s' in RULES section", entry->val); goto ip_next; } mk_info("network: '%s' mask: '%s'", _net, _mask); /* convert ip string to network address */ if (inet_aton(_net, &new_ip->ip) == 0) { mk_warn("Mandril: invalid ip address '%s' in RULES section", entry->val); goto ip_next; } /* parse mask */ new_ip->netmask = strtol(_mask, (char **) NULL, 10); if (new_ip->netmask <= 0 || new_ip->netmask >= 32) { mk_warn("Mandril: invalid mask value '%s' in RULES section", entry->val); goto ip_next; } /* complete struct data */ new_ip->is_subnet = MK_TRUE; new_ip->network = MK_NET_NETWORK(new_ip->ip.s_addr, new_ip->netmask); new_ip->hostmin = MK_NET_HOSTMIN(new_ip->ip.s_addr, new_ip->netmask); new_ip->hostmax = MK_NET_HOSTMAX(new_ip->ip.s_addr, new_ip->netmask); /* link node with main list */ mk_list_add(&new_ip->_head, &mk_secure_ip); /* * I know, you were instructed to hate 'goto' statements!, ok, show this * code to your teacher and let him blame :P */ ip_next: if (_net) { mk_api->mem_free(_net); } if (_mask) { mk_api->mem_free(_mask); } } else { /* normal IP address */ /* convert ip string to network address */ if (inet_aton(entry->val, &new_ip->ip) == 0) { mk_warn("Mandril: invalid ip address '%s' in RULES section", entry->val); } else { new_ip->is_subnet = MK_FALSE; mk_list_add(&new_ip->_head, &mk_secure_ip); } } } else if (strcasecmp(entry->key, "URL") == 0) { /* simple allcotion and data association */ new_url = mk_api->mem_alloc(sizeof(struct mk_secure_url_t)); new_url->criteria = entry->val; /* link node with main list */ mk_list_add(&new_url->_head, &mk_secure_url); } else if (strcasecmp(entry->key, "deny_hotlink") == 0) { new_deny_hotlink = mk_api->mem_alloc(sizeof(*new_deny_hotlink)); new_deny_hotlink->criteria = entry->val; mk_list_add(&new_deny_hotlink->_head, &mk_secure_deny_hotlink); } } mk_api->mem_free(conf_path); return ret; } static int mk_security_check_ip(int socket) { int network; struct mk_secure_ip_t *entry; struct mk_list *head; struct in_addr addr_t, *addr = &addr_t; socklen_t len = sizeof(addr); if (getpeername(socket, (struct sockaddr *)&addr_t, &len) < 0) { return -1; } PLUGIN_TRACE("[FD %i] Mandril validating IP address", socket); mk_list_foreach(head, &mk_secure_ip) { entry = mk_list_entry(head, struct mk_secure_ip_t, _head); if (entry->is_subnet == MK_TRUE) { /* Validate network */ network = MK_NET_NETWORK(addr->s_addr, entry->netmask); if (network != entry->network) { continue; } /* Validate host range */ if (addr->s_addr <= entry->hostmax && addr->s_addr >= entry->hostmin) { PLUGIN_TRACE("[FD %i] Mandril closing by rule in ranges", socket); return -1; } } else { if (addr->s_addr == entry->ip.s_addr) { PLUGIN_TRACE("[FD %i] Mandril closing by rule in IP match", socket); return -1; } } } return 0; } /* Check if the incoming URL is restricted for some rule */ static int mk_security_check_url(mk_ptr_t url) { int n; struct mk_list *head; struct mk_secure_url_t *entry; mk_list_foreach(head, &mk_secure_url) { entry = mk_list_entry(head, struct mk_secure_url_t, _head); n = mk_api->str_search_n(url.data, entry->criteria, MK_STR_INSENSITIVE, url.len); if (n >= 0) { return -1; } } return 0; } mk_ptr_t parse_referer_host(mk_ptr_t ref) { unsigned int i, beginHost, endHost; mk_ptr_t host; host.data = NULL; host.len = 0; // Find end of "protocol://" for (i = 0; i < ref.len && !(ref.data[i] == '/' && ref.data[i+1] == '/'); i++); if (i == ref.len) { goto error; } beginHost = i + 2; // Find end of any "user:password@" for (; i < ref.len && ref.data[i] != '@'; i++); if (i < ref.len) { beginHost = i + 1; } // Find end of "host", (beginning of :port or /path) for (i = beginHost; i < ref.len && ref.data[i] != ':' && ref.data[i] != '/'; i++); endHost = i; host.data = ref.data + beginHost; host.len = endHost - beginHost; return host; error: host.data = NULL; host.len = 0; return host; } static int mk_security_check_hotlink(mk_ptr_t url, mk_ptr_t host, mk_ptr_t referer) { mk_ptr_t ref_host = parse_referer_host(referer); unsigned int domains_matched = 0; int i = 0; const char *curA, *curB; struct mk_list *head; struct mk_secure_deny_hotlink_t *entry; if (ref_host.data == NULL) { return 0; } else if (host.data == NULL) { mk_err("No host data."); return -1; } mk_list_foreach(head, &mk_secure_url) { entry = mk_list_entry(head, struct mk_secure_deny_hotlink_t, _head); i = mk_api->str_search_n(url.data, entry->criteria, MK_STR_INSENSITIVE, url.len); if (i >= 0) { break; } } if (i < 0) { return 0; } curA = host.data + host.len; curB = ref_host.data + ref_host.len; // Match backwards from root domain. while (curA > host.data && curB > ref_host.data) { i++; curA--; curB--; if ((*curA == '.' && *curB == '.') || curA == host.data || curB == ref_host.data) { if (i < 1) { break; } else if (curA == host.data && !(curB == ref_host.data || *(curB - 1) == '.')) { break; } else if (curB == ref_host.data && !(curA == host.data || *(curA - 1) == '.')) { break; } else if (strncasecmp(curA, curB, i)) { break; } domains_matched += 1; i = 0; } } // Block connection if none or only top domain matched. return domains_matched >= 2 ? 0 : -1; } int _mkp_init(struct plugin_api **api, char *confdir) { mk_api = *api; /* Init security lists */ mk_list_init(&mk_secure_ip); mk_list_init(&mk_secure_url); mk_list_init(&mk_secure_deny_hotlink); /* Read configuration */ mk_security_conf(confdir); return 0; } void _mkp_exit() { } int _mkp_stage_10(unsigned int socket, struct sched_connection *conx) { (void) conx; /* Validate ip address with Mandril rules */ if (mk_security_check_ip(socket) != 0) { PLUGIN_TRACE("[FD %i] Mandril close connection", socket); return MK_PLUGIN_RET_CLOSE_CONX; } return MK_PLUGIN_RET_CONTINUE; } int _mkp_stage_30(struct plugin *p, struct client_session *cs, struct session_request *sr) { mk_ptr_t referer; (void) p; (void) cs; PLUGIN_TRACE("[FD %i] Mandril validating URL", cs->socket); if (mk_security_check_url(sr->uri) < 0) { PLUGIN_TRACE("[FD %i] Close connection, blocked URL", cs->socket); mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN); return MK_PLUGIN_RET_CLOSE_CONX; } PLUGIN_TRACE("[FD %d] Mandril validating hotlinking", cs->socket); referer = mk_api->header_get(&sr->headers_toc, "Referer", strlen("Referer")); if (mk_security_check_hotlink(sr->uri_processed, sr->host, referer) < 0) { PLUGIN_TRACE("[FD %i] Close connection, deny hotlinking.", cs->socket); mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN); return MK_PLUGIN_RET_CLOSE_CONX; } return MK_PLUGIN_RET_NOT_ME; }
./CrossVul/dataset_final_sorted/CWE-264/c/bad_5655_0
crossvul-cpp_data_good_5861_35
/* * Glue Code for x86_64/AVX2 assembler optimized version of Serpent * * Copyright © 2012-2013 Jussi Kivilinna <jussi.kivilinna@mbnet.fi> * * 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/types.h> #include <linux/crypto.h> #include <linux/err.h> #include <crypto/ablk_helper.h> #include <crypto/algapi.h> #include <crypto/ctr.h> #include <crypto/lrw.h> #include <crypto/xts.h> #include <crypto/serpent.h> #include <asm/xcr.h> #include <asm/xsave.h> #include <asm/crypto/serpent-avx.h> #include <asm/crypto/glue_helper.h> #define SERPENT_AVX2_PARALLEL_BLOCKS 16 /* 16-way AVX2 parallel cipher functions */ asmlinkage void serpent_ecb_enc_16way(struct serpent_ctx *ctx, u8 *dst, const u8 *src); asmlinkage void serpent_ecb_dec_16way(struct serpent_ctx *ctx, u8 *dst, const u8 *src); asmlinkage void serpent_cbc_dec_16way(void *ctx, u128 *dst, const u128 *src); asmlinkage void serpent_ctr_16way(void *ctx, u128 *dst, const u128 *src, le128 *iv); asmlinkage void serpent_xts_enc_16way(struct serpent_ctx *ctx, u8 *dst, const u8 *src, le128 *iv); asmlinkage void serpent_xts_dec_16way(struct serpent_ctx *ctx, u8 *dst, const u8 *src, le128 *iv); static const struct common_glue_ctx serpent_enc = { .num_funcs = 3, .fpu_blocks_limit = 8, .funcs = { { .num_blocks = 16, .fn_u = { .ecb = GLUE_FUNC_CAST(serpent_ecb_enc_16way) } }, { .num_blocks = 8, .fn_u = { .ecb = GLUE_FUNC_CAST(serpent_ecb_enc_8way_avx) } }, { .num_blocks = 1, .fn_u = { .ecb = GLUE_FUNC_CAST(__serpent_encrypt) } } } }; static const struct common_glue_ctx serpent_ctr = { .num_funcs = 3, .fpu_blocks_limit = 8, .funcs = { { .num_blocks = 16, .fn_u = { .ctr = GLUE_CTR_FUNC_CAST(serpent_ctr_16way) } }, { .num_blocks = 8, .fn_u = { .ctr = GLUE_CTR_FUNC_CAST(serpent_ctr_8way_avx) } }, { .num_blocks = 1, .fn_u = { .ctr = GLUE_CTR_FUNC_CAST(__serpent_crypt_ctr) } } } }; static const struct common_glue_ctx serpent_enc_xts = { .num_funcs = 3, .fpu_blocks_limit = 8, .funcs = { { .num_blocks = 16, .fn_u = { .xts = GLUE_XTS_FUNC_CAST(serpent_xts_enc_16way) } }, { .num_blocks = 8, .fn_u = { .xts = GLUE_XTS_FUNC_CAST(serpent_xts_enc_8way_avx) } }, { .num_blocks = 1, .fn_u = { .xts = GLUE_XTS_FUNC_CAST(serpent_xts_enc) } } } }; static const struct common_glue_ctx serpent_dec = { .num_funcs = 3, .fpu_blocks_limit = 8, .funcs = { { .num_blocks = 16, .fn_u = { .ecb = GLUE_FUNC_CAST(serpent_ecb_dec_16way) } }, { .num_blocks = 8, .fn_u = { .ecb = GLUE_FUNC_CAST(serpent_ecb_dec_8way_avx) } }, { .num_blocks = 1, .fn_u = { .ecb = GLUE_FUNC_CAST(__serpent_decrypt) } } } }; static const struct common_glue_ctx serpent_dec_cbc = { .num_funcs = 3, .fpu_blocks_limit = 8, .funcs = { { .num_blocks = 16, .fn_u = { .cbc = GLUE_CBC_FUNC_CAST(serpent_cbc_dec_16way) } }, { .num_blocks = 8, .fn_u = { .cbc = GLUE_CBC_FUNC_CAST(serpent_cbc_dec_8way_avx) } }, { .num_blocks = 1, .fn_u = { .cbc = GLUE_CBC_FUNC_CAST(__serpent_decrypt) } } } }; static const struct common_glue_ctx serpent_dec_xts = { .num_funcs = 3, .fpu_blocks_limit = 8, .funcs = { { .num_blocks = 16, .fn_u = { .xts = GLUE_XTS_FUNC_CAST(serpent_xts_dec_16way) } }, { .num_blocks = 8, .fn_u = { .xts = GLUE_XTS_FUNC_CAST(serpent_xts_dec_8way_avx) } }, { .num_blocks = 1, .fn_u = { .xts = GLUE_XTS_FUNC_CAST(serpent_xts_dec) } } } }; static int ecb_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_ecb_crypt_128bit(&serpent_enc, desc, dst, src, nbytes); } static int ecb_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_ecb_crypt_128bit(&serpent_dec, desc, dst, src, nbytes); } static int cbc_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_cbc_encrypt_128bit(GLUE_FUNC_CAST(__serpent_encrypt), desc, dst, src, nbytes); } static int cbc_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_cbc_decrypt_128bit(&serpent_dec_cbc, desc, dst, src, nbytes); } static int ctr_crypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_ctr_crypt_128bit(&serpent_ctr, desc, dst, src, nbytes); } static inline bool serpent_fpu_begin(bool fpu_enabled, unsigned int nbytes) { /* since reusing AVX functions, starts using FPU at 8 parallel blocks */ return glue_fpu_begin(SERPENT_BLOCK_SIZE, 8, NULL, fpu_enabled, nbytes); } static inline void serpent_fpu_end(bool fpu_enabled) { glue_fpu_end(fpu_enabled); } struct crypt_priv { struct serpent_ctx *ctx; bool fpu_enabled; }; static void encrypt_callback(void *priv, u8 *srcdst, unsigned int nbytes) { const unsigned int bsize = SERPENT_BLOCK_SIZE; struct crypt_priv *ctx = priv; int i; ctx->fpu_enabled = serpent_fpu_begin(ctx->fpu_enabled, nbytes); if (nbytes >= SERPENT_AVX2_PARALLEL_BLOCKS * bsize) { serpent_ecb_enc_16way(ctx->ctx, srcdst, srcdst); srcdst += bsize * SERPENT_AVX2_PARALLEL_BLOCKS; nbytes -= bsize * SERPENT_AVX2_PARALLEL_BLOCKS; } while (nbytes >= SERPENT_PARALLEL_BLOCKS * bsize) { serpent_ecb_enc_8way_avx(ctx->ctx, srcdst, srcdst); srcdst += bsize * SERPENT_PARALLEL_BLOCKS; nbytes -= bsize * SERPENT_PARALLEL_BLOCKS; } for (i = 0; i < nbytes / bsize; i++, srcdst += bsize) __serpent_encrypt(ctx->ctx, srcdst, srcdst); } static void decrypt_callback(void *priv, u8 *srcdst, unsigned int nbytes) { const unsigned int bsize = SERPENT_BLOCK_SIZE; struct crypt_priv *ctx = priv; int i; ctx->fpu_enabled = serpent_fpu_begin(ctx->fpu_enabled, nbytes); if (nbytes >= SERPENT_AVX2_PARALLEL_BLOCKS * bsize) { serpent_ecb_dec_16way(ctx->ctx, srcdst, srcdst); srcdst += bsize * SERPENT_AVX2_PARALLEL_BLOCKS; nbytes -= bsize * SERPENT_AVX2_PARALLEL_BLOCKS; } while (nbytes >= SERPENT_PARALLEL_BLOCKS * bsize) { serpent_ecb_dec_8way_avx(ctx->ctx, srcdst, srcdst); srcdst += bsize * SERPENT_PARALLEL_BLOCKS; nbytes -= bsize * SERPENT_PARALLEL_BLOCKS; } for (i = 0; i < nbytes / bsize; i++, srcdst += bsize) __serpent_decrypt(ctx->ctx, srcdst, srcdst); } static int lrw_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct serpent_lrw_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); be128 buf[SERPENT_AVX2_PARALLEL_BLOCKS]; struct crypt_priv crypt_ctx = { .ctx = &ctx->serpent_ctx, .fpu_enabled = false, }; struct lrw_crypt_req req = { .tbuf = buf, .tbuflen = sizeof(buf), .table_ctx = &ctx->lrw_table, .crypt_ctx = &crypt_ctx, .crypt_fn = encrypt_callback, }; int ret; desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP; ret = lrw_crypt(desc, dst, src, nbytes, &req); serpent_fpu_end(crypt_ctx.fpu_enabled); return ret; } static int lrw_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct serpent_lrw_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); be128 buf[SERPENT_AVX2_PARALLEL_BLOCKS]; struct crypt_priv crypt_ctx = { .ctx = &ctx->serpent_ctx, .fpu_enabled = false, }; struct lrw_crypt_req req = { .tbuf = buf, .tbuflen = sizeof(buf), .table_ctx = &ctx->lrw_table, .crypt_ctx = &crypt_ctx, .crypt_fn = decrypt_callback, }; int ret; desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP; ret = lrw_crypt(desc, dst, src, nbytes, &req); serpent_fpu_end(crypt_ctx.fpu_enabled); return ret; } static int xts_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct serpent_xts_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); return glue_xts_crypt_128bit(&serpent_enc_xts, desc, dst, src, nbytes, XTS_TWEAK_CAST(__serpent_encrypt), &ctx->tweak_ctx, &ctx->crypt_ctx); } static int xts_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct serpent_xts_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); return glue_xts_crypt_128bit(&serpent_dec_xts, desc, dst, src, nbytes, XTS_TWEAK_CAST(__serpent_encrypt), &ctx->tweak_ctx, &ctx->crypt_ctx); } static struct crypto_alg srp_algs[10] = { { .cra_name = "__ecb-serpent-avx2", .cra_driver_name = "__driver-ecb-serpent-avx2", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct serpent_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_list = LIST_HEAD_INIT(srp_algs[0].cra_list), .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .setkey = serpent_setkey, .encrypt = ecb_encrypt, .decrypt = ecb_decrypt, }, }, }, { .cra_name = "__cbc-serpent-avx2", .cra_driver_name = "__driver-cbc-serpent-avx2", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct serpent_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_list = LIST_HEAD_INIT(srp_algs[1].cra_list), .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .setkey = serpent_setkey, .encrypt = cbc_encrypt, .decrypt = cbc_decrypt, }, }, }, { .cra_name = "__ctr-serpent-avx2", .cra_driver_name = "__driver-ctr-serpent-avx2", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = 1, .cra_ctxsize = sizeof(struct serpent_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_list = LIST_HEAD_INIT(srp_algs[2].cra_list), .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = serpent_setkey, .encrypt = ctr_crypt, .decrypt = ctr_crypt, }, }, }, { .cra_name = "__lrw-serpent-avx2", .cra_driver_name = "__driver-lrw-serpent-avx2", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct serpent_lrw_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_list = LIST_HEAD_INIT(srp_algs[3].cra_list), .cra_exit = lrw_serpent_exit_tfm, .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE + SERPENT_BLOCK_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE + SERPENT_BLOCK_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = lrw_serpent_setkey, .encrypt = lrw_encrypt, .decrypt = lrw_decrypt, }, }, }, { .cra_name = "__xts-serpent-avx2", .cra_driver_name = "__driver-xts-serpent-avx2", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct serpent_xts_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_list = LIST_HEAD_INIT(srp_algs[4].cra_list), .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE * 2, .max_keysize = SERPENT_MAX_KEY_SIZE * 2, .ivsize = SERPENT_BLOCK_SIZE, .setkey = xts_serpent_setkey, .encrypt = xts_encrypt, .decrypt = xts_decrypt, }, }, }, { .cra_name = "ecb(serpent)", .cra_driver_name = "ecb-serpent-avx2", .cra_priority = 600, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_list = LIST_HEAD_INIT(srp_algs[5].cra_list), .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .setkey = ablk_set_key, .encrypt = ablk_encrypt, .decrypt = ablk_decrypt, }, }, }, { .cra_name = "cbc(serpent)", .cra_driver_name = "cbc-serpent-avx2", .cra_priority = 600, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_list = LIST_HEAD_INIT(srp_algs[6].cra_list), .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = ablk_set_key, .encrypt = __ablk_encrypt, .decrypt = ablk_decrypt, }, }, }, { .cra_name = "ctr(serpent)", .cra_driver_name = "ctr-serpent-avx2", .cra_priority = 600, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = 1, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_list = LIST_HEAD_INIT(srp_algs[7].cra_list), .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = ablk_set_key, .encrypt = ablk_encrypt, .decrypt = ablk_encrypt, .geniv = "chainiv", }, }, }, { .cra_name = "lrw(serpent)", .cra_driver_name = "lrw-serpent-avx2", .cra_priority = 600, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_list = LIST_HEAD_INIT(srp_algs[8].cra_list), .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE + SERPENT_BLOCK_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE + SERPENT_BLOCK_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = ablk_set_key, .encrypt = ablk_encrypt, .decrypt = ablk_decrypt, }, }, }, { .cra_name = "xts(serpent)", .cra_driver_name = "xts-serpent-avx2", .cra_priority = 600, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_list = LIST_HEAD_INIT(srp_algs[9].cra_list), .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE * 2, .max_keysize = SERPENT_MAX_KEY_SIZE * 2, .ivsize = SERPENT_BLOCK_SIZE, .setkey = ablk_set_key, .encrypt = ablk_encrypt, .decrypt = ablk_decrypt, }, }, } }; static int __init init(void) { u64 xcr0; if (!cpu_has_avx2 || !cpu_has_osxsave) { pr_info("AVX2 instructions are not detected.\n"); return -ENODEV; } xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK); if ((xcr0 & (XSTATE_SSE | XSTATE_YMM)) != (XSTATE_SSE | XSTATE_YMM)) { pr_info("AVX detected but unusable.\n"); return -ENODEV; } return crypto_register_algs(srp_algs, ARRAY_SIZE(srp_algs)); } static void __exit fini(void) { crypto_unregister_algs(srp_algs, ARRAY_SIZE(srp_algs)); } module_init(init); module_exit(fini); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Serpent Cipher Algorithm, AVX2 optimized"); MODULE_ALIAS_CRYPTO("serpent"); MODULE_ALIAS_CRYPTO("serpent-asm");
./CrossVul/dataset_final_sorted/CWE-264/c/good_5861_35
crossvul-cpp_data_bad_3524_6
/* * Generic HDLC support routines for Linux * Frame Relay support * * Copyright (C) 1999 - 2006 Krzysztof Halasa <khc@pm.waw.pl> * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License * as published by the Free Software Foundation. * Theory of PVC state DCE mode: (exist,new) -> 0,0 when "PVC create" or if "link unreliable" 0,x -> 1,1 if "link reliable" when sending FULL STATUS 1,1 -> 1,0 if received FULL STATUS ACK (active) -> 0 when "ifconfig PVC down" or "link unreliable" or "PVC create" -> 1 when "PVC up" and (exist,new) = 1,0 DTE mode: (exist,new,active) = FULL STATUS if "link reliable" = 0, 0, 0 if "link unreliable" No LMI: active = open and "link reliable" exist = new = not used CCITT LMI: ITU-T Q.933 Annex A ANSI LMI: ANSI T1.617 Annex D CISCO LMI: the original, aka "Gang of Four" LMI */ #include <linux/errno.h> #include <linux/etherdevice.h> #include <linux/hdlc.h> #include <linux/if_arp.h> #include <linux/inetdevice.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/pkt_sched.h> #include <linux/poll.h> #include <linux/rtnetlink.h> #include <linux/skbuff.h> #include <linux/slab.h> #undef DEBUG_PKT #undef DEBUG_ECN #undef DEBUG_LINK #undef DEBUG_PROTO #undef DEBUG_PVC #define FR_UI 0x03 #define FR_PAD 0x00 #define NLPID_IP 0xCC #define NLPID_IPV6 0x8E #define NLPID_SNAP 0x80 #define NLPID_PAD 0x00 #define NLPID_CCITT_ANSI_LMI 0x08 #define NLPID_CISCO_LMI 0x09 #define LMI_CCITT_ANSI_DLCI 0 /* LMI DLCI */ #define LMI_CISCO_DLCI 1023 #define LMI_CALLREF 0x00 /* Call Reference */ #define LMI_ANSI_LOCKSHIFT 0x95 /* ANSI locking shift */ #define LMI_ANSI_CISCO_REPTYPE 0x01 /* report type */ #define LMI_CCITT_REPTYPE 0x51 #define LMI_ANSI_CISCO_ALIVE 0x03 /* keep alive */ #define LMI_CCITT_ALIVE 0x53 #define LMI_ANSI_CISCO_PVCSTAT 0x07 /* PVC status */ #define LMI_CCITT_PVCSTAT 0x57 #define LMI_FULLREP 0x00 /* full report */ #define LMI_INTEGRITY 0x01 /* link integrity report */ #define LMI_SINGLE 0x02 /* single PVC report */ #define LMI_STATUS_ENQUIRY 0x75 #define LMI_STATUS 0x7D /* reply */ #define LMI_REPT_LEN 1 /* report type element length */ #define LMI_INTEG_LEN 2 /* link integrity element length */ #define LMI_CCITT_CISCO_LENGTH 13 /* LMI frame lengths */ #define LMI_ANSI_LENGTH 14 typedef struct { #if defined(__LITTLE_ENDIAN_BITFIELD) unsigned ea1: 1; unsigned cr: 1; unsigned dlcih: 6; unsigned ea2: 1; unsigned de: 1; unsigned becn: 1; unsigned fecn: 1; unsigned dlcil: 4; #else unsigned dlcih: 6; unsigned cr: 1; unsigned ea1: 1; unsigned dlcil: 4; unsigned fecn: 1; unsigned becn: 1; unsigned de: 1; unsigned ea2: 1; #endif }__packed fr_hdr; typedef struct pvc_device_struct { struct net_device *frad; struct net_device *main; struct net_device *ether; /* bridged Ethernet interface */ struct pvc_device_struct *next; /* Sorted in ascending DLCI order */ int dlci; int open_count; struct { unsigned int new: 1; unsigned int active: 1; unsigned int exist: 1; unsigned int deleted: 1; unsigned int fecn: 1; unsigned int becn: 1; unsigned int bandwidth; /* Cisco LMI reporting only */ }state; }pvc_device; struct frad_state { fr_proto settings; pvc_device *first_pvc; int dce_pvc_count; struct timer_list timer; unsigned long last_poll; int reliable; int dce_changed; int request; int fullrep_sent; u32 last_errors; /* last errors bit list */ u8 n391cnt; u8 txseq; /* TX sequence number */ u8 rxseq; /* RX sequence number */ }; static int fr_ioctl(struct net_device *dev, struct ifreq *ifr); static inline u16 q922_to_dlci(u8 *hdr) { return ((hdr[0] & 0xFC) << 2) | ((hdr[1] & 0xF0) >> 4); } static inline void dlci_to_q922(u8 *hdr, u16 dlci) { hdr[0] = (dlci >> 2) & 0xFC; hdr[1] = ((dlci << 4) & 0xF0) | 0x01; } static inline struct frad_state* state(hdlc_device *hdlc) { return(struct frad_state *)(hdlc->state); } static inline pvc_device* find_pvc(hdlc_device *hdlc, u16 dlci) { pvc_device *pvc = state(hdlc)->first_pvc; while (pvc) { if (pvc->dlci == dlci) return pvc; if (pvc->dlci > dlci) return NULL; /* the list is sorted */ pvc = pvc->next; } return NULL; } static pvc_device* add_pvc(struct net_device *dev, u16 dlci) { hdlc_device *hdlc = dev_to_hdlc(dev); pvc_device *pvc, **pvc_p = &state(hdlc)->first_pvc; while (*pvc_p) { if ((*pvc_p)->dlci == dlci) return *pvc_p; if ((*pvc_p)->dlci > dlci) break; /* the list is sorted */ pvc_p = &(*pvc_p)->next; } pvc = kzalloc(sizeof(pvc_device), GFP_ATOMIC); #ifdef DEBUG_PVC printk(KERN_DEBUG "add_pvc: allocated pvc %p, frad %p\n", pvc, dev); #endif if (!pvc) return NULL; pvc->dlci = dlci; pvc->frad = dev; pvc->next = *pvc_p; /* Put it in the chain */ *pvc_p = pvc; return pvc; } static inline int pvc_is_used(pvc_device *pvc) { return pvc->main || pvc->ether; } static inline void pvc_carrier(int on, pvc_device *pvc) { if (on) { if (pvc->main) if (!netif_carrier_ok(pvc->main)) netif_carrier_on(pvc->main); if (pvc->ether) if (!netif_carrier_ok(pvc->ether)) netif_carrier_on(pvc->ether); } else { if (pvc->main) if (netif_carrier_ok(pvc->main)) netif_carrier_off(pvc->main); if (pvc->ether) if (netif_carrier_ok(pvc->ether)) netif_carrier_off(pvc->ether); } } static inline void delete_unused_pvcs(hdlc_device *hdlc) { pvc_device **pvc_p = &state(hdlc)->first_pvc; while (*pvc_p) { if (!pvc_is_used(*pvc_p)) { pvc_device *pvc = *pvc_p; #ifdef DEBUG_PVC printk(KERN_DEBUG "freeing unused pvc: %p\n", pvc); #endif *pvc_p = pvc->next; kfree(pvc); continue; } pvc_p = &(*pvc_p)->next; } } static inline struct net_device** get_dev_p(pvc_device *pvc, int type) { if (type == ARPHRD_ETHER) return &pvc->ether; else return &pvc->main; } static int fr_hard_header(struct sk_buff **skb_p, u16 dlci) { u16 head_len; struct sk_buff *skb = *skb_p; switch (skb->protocol) { case cpu_to_be16(NLPID_CCITT_ANSI_LMI): head_len = 4; skb_push(skb, head_len); skb->data[3] = NLPID_CCITT_ANSI_LMI; break; case cpu_to_be16(NLPID_CISCO_LMI): head_len = 4; skb_push(skb, head_len); skb->data[3] = NLPID_CISCO_LMI; break; case cpu_to_be16(ETH_P_IP): head_len = 4; skb_push(skb, head_len); skb->data[3] = NLPID_IP; break; case cpu_to_be16(ETH_P_IPV6): head_len = 4; skb_push(skb, head_len); skb->data[3] = NLPID_IPV6; break; case cpu_to_be16(ETH_P_802_3): head_len = 10; if (skb_headroom(skb) < head_len) { struct sk_buff *skb2 = skb_realloc_headroom(skb, head_len); if (!skb2) return -ENOBUFS; dev_kfree_skb(skb); skb = *skb_p = skb2; } skb_push(skb, head_len); skb->data[3] = FR_PAD; skb->data[4] = NLPID_SNAP; skb->data[5] = FR_PAD; skb->data[6] = 0x80; skb->data[7] = 0xC2; skb->data[8] = 0x00; skb->data[9] = 0x07; /* bridged Ethernet frame w/out FCS */ break; default: head_len = 10; skb_push(skb, head_len); skb->data[3] = FR_PAD; skb->data[4] = NLPID_SNAP; skb->data[5] = FR_PAD; skb->data[6] = FR_PAD; skb->data[7] = FR_PAD; *(__be16*)(skb->data + 8) = skb->protocol; } dlci_to_q922(skb->data, dlci); skb->data[2] = FR_UI; return 0; } static int pvc_open(struct net_device *dev) { pvc_device *pvc = dev->ml_priv; if ((pvc->frad->flags & IFF_UP) == 0) return -EIO; /* Frad must be UP in order to activate PVC */ if (pvc->open_count++ == 0) { hdlc_device *hdlc = dev_to_hdlc(pvc->frad); if (state(hdlc)->settings.lmi == LMI_NONE) pvc->state.active = netif_carrier_ok(pvc->frad); pvc_carrier(pvc->state.active, pvc); state(hdlc)->dce_changed = 1; } return 0; } static int pvc_close(struct net_device *dev) { pvc_device *pvc = dev->ml_priv; if (--pvc->open_count == 0) { hdlc_device *hdlc = dev_to_hdlc(pvc->frad); if (state(hdlc)->settings.lmi == LMI_NONE) pvc->state.active = 0; if (state(hdlc)->settings.dce) { state(hdlc)->dce_changed = 1; pvc->state.active = 0; } } return 0; } static int pvc_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { pvc_device *pvc = dev->ml_priv; fr_proto_pvc_info info; if (ifr->ifr_settings.type == IF_GET_PROTO) { if (dev->type == ARPHRD_ETHER) ifr->ifr_settings.type = IF_PROTO_FR_ETH_PVC; else ifr->ifr_settings.type = IF_PROTO_FR_PVC; if (ifr->ifr_settings.size < sizeof(info)) { /* data size wanted */ ifr->ifr_settings.size = sizeof(info); return -ENOBUFS; } info.dlci = pvc->dlci; memcpy(info.master, pvc->frad->name, IFNAMSIZ); if (copy_to_user(ifr->ifr_settings.ifs_ifsu.fr_pvc_info, &info, sizeof(info))) return -EFAULT; return 0; } return -EINVAL; } static netdev_tx_t pvc_xmit(struct sk_buff *skb, struct net_device *dev) { pvc_device *pvc = dev->ml_priv; if (pvc->state.active) { if (dev->type == ARPHRD_ETHER) { int pad = ETH_ZLEN - skb->len; if (pad > 0) { /* Pad the frame with zeros */ int len = skb->len; if (skb_tailroom(skb) < pad) if (pskb_expand_head(skb, 0, pad, GFP_ATOMIC)) { dev->stats.tx_dropped++; dev_kfree_skb(skb); return NETDEV_TX_OK; } skb_put(skb, pad); memset(skb->data + len, 0, pad); } skb->protocol = cpu_to_be16(ETH_P_802_3); } if (!fr_hard_header(&skb, pvc->dlci)) { dev->stats.tx_bytes += skb->len; dev->stats.tx_packets++; if (pvc->state.fecn) /* TX Congestion counter */ dev->stats.tx_compressed++; skb->dev = pvc->frad; dev_queue_xmit(skb); return NETDEV_TX_OK; } } dev->stats.tx_dropped++; dev_kfree_skb(skb); return NETDEV_TX_OK; } static inline void fr_log_dlci_active(pvc_device *pvc) { netdev_info(pvc->frad, "DLCI %d [%s%s%s]%s %s\n", pvc->dlci, pvc->main ? pvc->main->name : "", pvc->main && pvc->ether ? " " : "", pvc->ether ? pvc->ether->name : "", pvc->state.new ? " new" : "", !pvc->state.exist ? "deleted" : pvc->state.active ? "active" : "inactive"); } static inline u8 fr_lmi_nextseq(u8 x) { x++; return x ? x : 1; } static void fr_lmi_send(struct net_device *dev, int fullrep) { hdlc_device *hdlc = dev_to_hdlc(dev); struct sk_buff *skb; pvc_device *pvc = state(hdlc)->first_pvc; int lmi = state(hdlc)->settings.lmi; int dce = state(hdlc)->settings.dce; int len = lmi == LMI_ANSI ? LMI_ANSI_LENGTH : LMI_CCITT_CISCO_LENGTH; int stat_len = (lmi == LMI_CISCO) ? 6 : 3; u8 *data; int i = 0; if (dce && fullrep) { len += state(hdlc)->dce_pvc_count * (2 + stat_len); if (len > HDLC_MAX_MRU) { netdev_warn(dev, "Too many PVCs while sending LMI full report\n"); return; } } skb = dev_alloc_skb(len); if (!skb) { netdev_warn(dev, "Memory squeeze on fr_lmi_send()\n"); return; } memset(skb->data, 0, len); skb_reserve(skb, 4); if (lmi == LMI_CISCO) { skb->protocol = cpu_to_be16(NLPID_CISCO_LMI); fr_hard_header(&skb, LMI_CISCO_DLCI); } else { skb->protocol = cpu_to_be16(NLPID_CCITT_ANSI_LMI); fr_hard_header(&skb, LMI_CCITT_ANSI_DLCI); } data = skb_tail_pointer(skb); data[i++] = LMI_CALLREF; data[i++] = dce ? LMI_STATUS : LMI_STATUS_ENQUIRY; if (lmi == LMI_ANSI) data[i++] = LMI_ANSI_LOCKSHIFT; data[i++] = lmi == LMI_CCITT ? LMI_CCITT_REPTYPE : LMI_ANSI_CISCO_REPTYPE; data[i++] = LMI_REPT_LEN; data[i++] = fullrep ? LMI_FULLREP : LMI_INTEGRITY; data[i++] = lmi == LMI_CCITT ? LMI_CCITT_ALIVE : LMI_ANSI_CISCO_ALIVE; data[i++] = LMI_INTEG_LEN; data[i++] = state(hdlc)->txseq = fr_lmi_nextseq(state(hdlc)->txseq); data[i++] = state(hdlc)->rxseq; if (dce && fullrep) { while (pvc) { data[i++] = lmi == LMI_CCITT ? LMI_CCITT_PVCSTAT : LMI_ANSI_CISCO_PVCSTAT; data[i++] = stat_len; /* LMI start/restart */ if (state(hdlc)->reliable && !pvc->state.exist) { pvc->state.exist = pvc->state.new = 1; fr_log_dlci_active(pvc); } /* ifconfig PVC up */ if (pvc->open_count && !pvc->state.active && pvc->state.exist && !pvc->state.new) { pvc_carrier(1, pvc); pvc->state.active = 1; fr_log_dlci_active(pvc); } if (lmi == LMI_CISCO) { data[i] = pvc->dlci >> 8; data[i + 1] = pvc->dlci & 0xFF; } else { data[i] = (pvc->dlci >> 4) & 0x3F; data[i + 1] = ((pvc->dlci << 3) & 0x78) | 0x80; data[i + 2] = 0x80; } if (pvc->state.new) data[i + 2] |= 0x08; else if (pvc->state.active) data[i + 2] |= 0x02; i += stat_len; pvc = pvc->next; } } skb_put(skb, i); skb->priority = TC_PRIO_CONTROL; skb->dev = dev; skb_reset_network_header(skb); dev_queue_xmit(skb); } static void fr_set_link_state(int reliable, struct net_device *dev) { hdlc_device *hdlc = dev_to_hdlc(dev); pvc_device *pvc = state(hdlc)->first_pvc; state(hdlc)->reliable = reliable; if (reliable) { netif_dormant_off(dev); state(hdlc)->n391cnt = 0; /* Request full status */ state(hdlc)->dce_changed = 1; if (state(hdlc)->settings.lmi == LMI_NONE) { while (pvc) { /* Activate all PVCs */ pvc_carrier(1, pvc); pvc->state.exist = pvc->state.active = 1; pvc->state.new = 0; pvc = pvc->next; } } } else { netif_dormant_on(dev); while (pvc) { /* Deactivate all PVCs */ pvc_carrier(0, pvc); pvc->state.exist = pvc->state.active = 0; pvc->state.new = 0; if (!state(hdlc)->settings.dce) pvc->state.bandwidth = 0; pvc = pvc->next; } } } static void fr_timer(unsigned long arg) { struct net_device *dev = (struct net_device *)arg; hdlc_device *hdlc = dev_to_hdlc(dev); int i, cnt = 0, reliable; u32 list; if (state(hdlc)->settings.dce) { reliable = state(hdlc)->request && time_before(jiffies, state(hdlc)->last_poll + state(hdlc)->settings.t392 * HZ); state(hdlc)->request = 0; } else { state(hdlc)->last_errors <<= 1; /* Shift the list */ if (state(hdlc)->request) { if (state(hdlc)->reliable) netdev_info(dev, "No LMI status reply received\n"); state(hdlc)->last_errors |= 1; } list = state(hdlc)->last_errors; for (i = 0; i < state(hdlc)->settings.n393; i++, list >>= 1) cnt += (list & 1); /* errors count */ reliable = (cnt < state(hdlc)->settings.n392); } if (state(hdlc)->reliable != reliable) { netdev_info(dev, "Link %sreliable\n", reliable ? "" : "un"); fr_set_link_state(reliable, dev); } if (state(hdlc)->settings.dce) state(hdlc)->timer.expires = jiffies + state(hdlc)->settings.t392 * HZ; else { if (state(hdlc)->n391cnt) state(hdlc)->n391cnt--; fr_lmi_send(dev, state(hdlc)->n391cnt == 0); state(hdlc)->last_poll = jiffies; state(hdlc)->request = 1; state(hdlc)->timer.expires = jiffies + state(hdlc)->settings.t391 * HZ; } state(hdlc)->timer.function = fr_timer; state(hdlc)->timer.data = arg; add_timer(&state(hdlc)->timer); } static int fr_lmi_recv(struct net_device *dev, struct sk_buff *skb) { hdlc_device *hdlc = dev_to_hdlc(dev); pvc_device *pvc; u8 rxseq, txseq; int lmi = state(hdlc)->settings.lmi; int dce = state(hdlc)->settings.dce; int stat_len = (lmi == LMI_CISCO) ? 6 : 3, reptype, error, no_ram, i; if (skb->len < (lmi == LMI_ANSI ? LMI_ANSI_LENGTH : LMI_CCITT_CISCO_LENGTH)) { netdev_info(dev, "Short LMI frame\n"); return 1; } if (skb->data[3] != (lmi == LMI_CISCO ? NLPID_CISCO_LMI : NLPID_CCITT_ANSI_LMI)) { netdev_info(dev, "Received non-LMI frame with LMI DLCI\n"); return 1; } if (skb->data[4] != LMI_CALLREF) { netdev_info(dev, "Invalid LMI Call reference (0x%02X)\n", skb->data[4]); return 1; } if (skb->data[5] != (dce ? LMI_STATUS_ENQUIRY : LMI_STATUS)) { netdev_info(dev, "Invalid LMI Message type (0x%02X)\n", skb->data[5]); return 1; } if (lmi == LMI_ANSI) { if (skb->data[6] != LMI_ANSI_LOCKSHIFT) { netdev_info(dev, "Not ANSI locking shift in LMI message (0x%02X)\n", skb->data[6]); return 1; } i = 7; } else i = 6; if (skb->data[i] != (lmi == LMI_CCITT ? LMI_CCITT_REPTYPE : LMI_ANSI_CISCO_REPTYPE)) { netdev_info(dev, "Not an LMI Report type IE (0x%02X)\n", skb->data[i]); return 1; } if (skb->data[++i] != LMI_REPT_LEN) { netdev_info(dev, "Invalid LMI Report type IE length (%u)\n", skb->data[i]); return 1; } reptype = skb->data[++i]; if (reptype != LMI_INTEGRITY && reptype != LMI_FULLREP) { netdev_info(dev, "Unsupported LMI Report type (0x%02X)\n", reptype); return 1; } if (skb->data[++i] != (lmi == LMI_CCITT ? LMI_CCITT_ALIVE : LMI_ANSI_CISCO_ALIVE)) { netdev_info(dev, "Not an LMI Link integrity verification IE (0x%02X)\n", skb->data[i]); return 1; } if (skb->data[++i] != LMI_INTEG_LEN) { netdev_info(dev, "Invalid LMI Link integrity verification IE length (%u)\n", skb->data[i]); return 1; } i++; state(hdlc)->rxseq = skb->data[i++]; /* TX sequence from peer */ rxseq = skb->data[i++]; /* Should confirm our sequence */ txseq = state(hdlc)->txseq; if (dce) state(hdlc)->last_poll = jiffies; error = 0; if (!state(hdlc)->reliable) error = 1; if (rxseq == 0 || rxseq != txseq) { /* Ask for full report next time */ state(hdlc)->n391cnt = 0; error = 1; } if (dce) { if (state(hdlc)->fullrep_sent && !error) { /* Stop sending full report - the last one has been confirmed by DTE */ state(hdlc)->fullrep_sent = 0; pvc = state(hdlc)->first_pvc; while (pvc) { if (pvc->state.new) { pvc->state.new = 0; /* Tell DTE that new PVC is now active */ state(hdlc)->dce_changed = 1; } pvc = pvc->next; } } if (state(hdlc)->dce_changed) { reptype = LMI_FULLREP; state(hdlc)->fullrep_sent = 1; state(hdlc)->dce_changed = 0; } state(hdlc)->request = 1; /* got request */ fr_lmi_send(dev, reptype == LMI_FULLREP ? 1 : 0); return 0; } /* DTE */ state(hdlc)->request = 0; /* got response, no request pending */ if (error) return 0; if (reptype != LMI_FULLREP) return 0; pvc = state(hdlc)->first_pvc; while (pvc) { pvc->state.deleted = 1; pvc = pvc->next; } no_ram = 0; while (skb->len >= i + 2 + stat_len) { u16 dlci; u32 bw; unsigned int active, new; if (skb->data[i] != (lmi == LMI_CCITT ? LMI_CCITT_PVCSTAT : LMI_ANSI_CISCO_PVCSTAT)) { netdev_info(dev, "Not an LMI PVC status IE (0x%02X)\n", skb->data[i]); return 1; } if (skb->data[++i] != stat_len) { netdev_info(dev, "Invalid LMI PVC status IE length (%u)\n", skb->data[i]); return 1; } i++; new = !! (skb->data[i + 2] & 0x08); active = !! (skb->data[i + 2] & 0x02); if (lmi == LMI_CISCO) { dlci = (skb->data[i] << 8) | skb->data[i + 1]; bw = (skb->data[i + 3] << 16) | (skb->data[i + 4] << 8) | (skb->data[i + 5]); } else { dlci = ((skb->data[i] & 0x3F) << 4) | ((skb->data[i + 1] & 0x78) >> 3); bw = 0; } pvc = add_pvc(dev, dlci); if (!pvc && !no_ram) { netdev_warn(dev, "Memory squeeze on fr_lmi_recv()\n"); no_ram = 1; } if (pvc) { pvc->state.exist = 1; pvc->state.deleted = 0; if (active != pvc->state.active || new != pvc->state.new || bw != pvc->state.bandwidth || !pvc->state.exist) { pvc->state.new = new; pvc->state.active = active; pvc->state.bandwidth = bw; pvc_carrier(active, pvc); fr_log_dlci_active(pvc); } } i += stat_len; } pvc = state(hdlc)->first_pvc; while (pvc) { if (pvc->state.deleted && pvc->state.exist) { pvc_carrier(0, pvc); pvc->state.active = pvc->state.new = 0; pvc->state.exist = 0; pvc->state.bandwidth = 0; fr_log_dlci_active(pvc); } pvc = pvc->next; } /* Next full report after N391 polls */ state(hdlc)->n391cnt = state(hdlc)->settings.n391; return 0; } static int fr_rx(struct sk_buff *skb) { struct net_device *frad = skb->dev; hdlc_device *hdlc = dev_to_hdlc(frad); fr_hdr *fh = (fr_hdr*)skb->data; u8 *data = skb->data; u16 dlci; pvc_device *pvc; struct net_device *dev = NULL; if (skb->len <= 4 || fh->ea1 || data[2] != FR_UI) goto rx_error; dlci = q922_to_dlci(skb->data); if ((dlci == LMI_CCITT_ANSI_DLCI && (state(hdlc)->settings.lmi == LMI_ANSI || state(hdlc)->settings.lmi == LMI_CCITT)) || (dlci == LMI_CISCO_DLCI && state(hdlc)->settings.lmi == LMI_CISCO)) { if (fr_lmi_recv(frad, skb)) goto rx_error; dev_kfree_skb_any(skb); return NET_RX_SUCCESS; } pvc = find_pvc(hdlc, dlci); if (!pvc) { #ifdef DEBUG_PKT netdev_info(frad, "No PVC for received frame's DLCI %d\n", dlci); #endif dev_kfree_skb_any(skb); return NET_RX_DROP; } if (pvc->state.fecn != fh->fecn) { #ifdef DEBUG_ECN printk(KERN_DEBUG "%s: DLCI %d FECN O%s\n", frad->name, dlci, fh->fecn ? "N" : "FF"); #endif pvc->state.fecn ^= 1; } if (pvc->state.becn != fh->becn) { #ifdef DEBUG_ECN printk(KERN_DEBUG "%s: DLCI %d BECN O%s\n", frad->name, dlci, fh->becn ? "N" : "FF"); #endif pvc->state.becn ^= 1; } if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL) { frad->stats.rx_dropped++; return NET_RX_DROP; } if (data[3] == NLPID_IP) { skb_pull(skb, 4); /* Remove 4-byte header (hdr, UI, NLPID) */ dev = pvc->main; skb->protocol = htons(ETH_P_IP); } else if (data[3] == NLPID_IPV6) { skb_pull(skb, 4); /* Remove 4-byte header (hdr, UI, NLPID) */ dev = pvc->main; skb->protocol = htons(ETH_P_IPV6); } else if (skb->len > 10 && data[3] == FR_PAD && data[4] == NLPID_SNAP && data[5] == FR_PAD) { u16 oui = ntohs(*(__be16*)(data + 6)); u16 pid = ntohs(*(__be16*)(data + 8)); skb_pull(skb, 10); switch ((((u32)oui) << 16) | pid) { case ETH_P_ARP: /* routed frame with SNAP */ case ETH_P_IPX: case ETH_P_IP: /* a long variant */ case ETH_P_IPV6: dev = pvc->main; skb->protocol = htons(pid); break; case 0x80C20007: /* bridged Ethernet frame */ if ((dev = pvc->ether) != NULL) skb->protocol = eth_type_trans(skb, dev); break; default: netdev_info(frad, "Unsupported protocol, OUI=%x PID=%x\n", oui, pid); dev_kfree_skb_any(skb); return NET_RX_DROP; } } else { netdev_info(frad, "Unsupported protocol, NLPID=%x length=%i\n", data[3], skb->len); dev_kfree_skb_any(skb); return NET_RX_DROP; } if (dev) { dev->stats.rx_packets++; /* PVC traffic */ dev->stats.rx_bytes += skb->len; if (pvc->state.becn) dev->stats.rx_compressed++; skb->dev = dev; netif_rx(skb); return NET_RX_SUCCESS; } else { dev_kfree_skb_any(skb); return NET_RX_DROP; } rx_error: frad->stats.rx_errors++; /* Mark error */ dev_kfree_skb_any(skb); return NET_RX_DROP; } static void fr_start(struct net_device *dev) { hdlc_device *hdlc = dev_to_hdlc(dev); #ifdef DEBUG_LINK printk(KERN_DEBUG "fr_start\n"); #endif if (state(hdlc)->settings.lmi != LMI_NONE) { state(hdlc)->reliable = 0; state(hdlc)->dce_changed = 1; state(hdlc)->request = 0; state(hdlc)->fullrep_sent = 0; state(hdlc)->last_errors = 0xFFFFFFFF; state(hdlc)->n391cnt = 0; state(hdlc)->txseq = state(hdlc)->rxseq = 0; init_timer(&state(hdlc)->timer); /* First poll after 1 s */ state(hdlc)->timer.expires = jiffies + HZ; state(hdlc)->timer.function = fr_timer; state(hdlc)->timer.data = (unsigned long)dev; add_timer(&state(hdlc)->timer); } else fr_set_link_state(1, dev); } static void fr_stop(struct net_device *dev) { hdlc_device *hdlc = dev_to_hdlc(dev); #ifdef DEBUG_LINK printk(KERN_DEBUG "fr_stop\n"); #endif if (state(hdlc)->settings.lmi != LMI_NONE) del_timer_sync(&state(hdlc)->timer); fr_set_link_state(0, dev); } static void fr_close(struct net_device *dev) { hdlc_device *hdlc = dev_to_hdlc(dev); pvc_device *pvc = state(hdlc)->first_pvc; while (pvc) { /* Shutdown all PVCs for this FRAD */ if (pvc->main) dev_close(pvc->main); if (pvc->ether) dev_close(pvc->ether); pvc = pvc->next; } } static void pvc_setup(struct net_device *dev) { dev->type = ARPHRD_DLCI; dev->flags = IFF_POINTOPOINT; dev->hard_header_len = 10; dev->addr_len = 2; dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; } static const struct net_device_ops pvc_ops = { .ndo_open = pvc_open, .ndo_stop = pvc_close, .ndo_change_mtu = hdlc_change_mtu, .ndo_start_xmit = pvc_xmit, .ndo_do_ioctl = pvc_ioctl, }; static int fr_add_pvc(struct net_device *frad, unsigned int dlci, int type) { hdlc_device *hdlc = dev_to_hdlc(frad); pvc_device *pvc; struct net_device *dev; int used; if ((pvc = add_pvc(frad, dlci)) == NULL) { netdev_warn(frad, "Memory squeeze on fr_add_pvc()\n"); return -ENOBUFS; } if (*get_dev_p(pvc, type)) return -EEXIST; used = pvc_is_used(pvc); if (type == ARPHRD_ETHER) dev = alloc_netdev(0, "pvceth%d", ether_setup); else dev = alloc_netdev(0, "pvc%d", pvc_setup); if (!dev) { netdev_warn(frad, "Memory squeeze on fr_pvc()\n"); delete_unused_pvcs(hdlc); return -ENOBUFS; } if (type == ARPHRD_ETHER) random_ether_addr(dev->dev_addr); else { *(__be16*)dev->dev_addr = htons(dlci); dlci_to_q922(dev->broadcast, dlci); } dev->netdev_ops = &pvc_ops; dev->mtu = HDLC_MAX_MTU; dev->tx_queue_len = 0; dev->ml_priv = pvc; if (register_netdevice(dev) != 0) { free_netdev(dev); delete_unused_pvcs(hdlc); return -EIO; } dev->destructor = free_netdev; *get_dev_p(pvc, type) = dev; if (!used) { state(hdlc)->dce_changed = 1; state(hdlc)->dce_pvc_count++; } return 0; } static int fr_del_pvc(hdlc_device *hdlc, unsigned int dlci, int type) { pvc_device *pvc; struct net_device *dev; if ((pvc = find_pvc(hdlc, dlci)) == NULL) return -ENOENT; if ((dev = *get_dev_p(pvc, type)) == NULL) return -ENOENT; if (dev->flags & IFF_UP) return -EBUSY; /* PVC in use */ unregister_netdevice(dev); /* the destructor will free_netdev(dev) */ *get_dev_p(pvc, type) = NULL; if (!pvc_is_used(pvc)) { state(hdlc)->dce_pvc_count--; state(hdlc)->dce_changed = 1; } delete_unused_pvcs(hdlc); return 0; } static void fr_destroy(struct net_device *frad) { hdlc_device *hdlc = dev_to_hdlc(frad); pvc_device *pvc = state(hdlc)->first_pvc; state(hdlc)->first_pvc = NULL; /* All PVCs destroyed */ state(hdlc)->dce_pvc_count = 0; state(hdlc)->dce_changed = 1; while (pvc) { pvc_device *next = pvc->next; /* destructors will free_netdev() main and ether */ if (pvc->main) unregister_netdevice(pvc->main); if (pvc->ether) unregister_netdevice(pvc->ether); kfree(pvc); pvc = next; } } static struct hdlc_proto proto = { .close = fr_close, .start = fr_start, .stop = fr_stop, .detach = fr_destroy, .ioctl = fr_ioctl, .netif_rx = fr_rx, .module = THIS_MODULE, }; static int fr_ioctl(struct net_device *dev, struct ifreq *ifr) { fr_proto __user *fr_s = ifr->ifr_settings.ifs_ifsu.fr; const size_t size = sizeof(fr_proto); fr_proto new_settings; hdlc_device *hdlc = dev_to_hdlc(dev); fr_proto_pvc pvc; int result; switch (ifr->ifr_settings.type) { case IF_GET_PROTO: if (dev_to_hdlc(dev)->proto != &proto) /* Different proto */ return -EINVAL; ifr->ifr_settings.type = IF_PROTO_FR; if (ifr->ifr_settings.size < size) { ifr->ifr_settings.size = size; /* data size wanted */ return -ENOBUFS; } if (copy_to_user(fr_s, &state(hdlc)->settings, size)) return -EFAULT; return 0; case IF_PROTO_FR: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (dev->flags & IFF_UP) return -EBUSY; if (copy_from_user(&new_settings, fr_s, size)) return -EFAULT; if (new_settings.lmi == LMI_DEFAULT) new_settings.lmi = LMI_ANSI; if ((new_settings.lmi != LMI_NONE && new_settings.lmi != LMI_ANSI && new_settings.lmi != LMI_CCITT && new_settings.lmi != LMI_CISCO) || new_settings.t391 < 1 || new_settings.t392 < 2 || new_settings.n391 < 1 || new_settings.n392 < 1 || new_settings.n393 < new_settings.n392 || new_settings.n393 > 32 || (new_settings.dce != 0 && new_settings.dce != 1)) return -EINVAL; result=hdlc->attach(dev, ENCODING_NRZ,PARITY_CRC16_PR1_CCITT); if (result) return result; if (dev_to_hdlc(dev)->proto != &proto) { /* Different proto */ result = attach_hdlc_protocol(dev, &proto, sizeof(struct frad_state)); if (result) return result; state(hdlc)->first_pvc = NULL; state(hdlc)->dce_pvc_count = 0; } memcpy(&state(hdlc)->settings, &new_settings, size); dev->type = ARPHRD_FRAD; return 0; case IF_PROTO_FR_ADD_PVC: case IF_PROTO_FR_DEL_PVC: case IF_PROTO_FR_ADD_ETH_PVC: case IF_PROTO_FR_DEL_ETH_PVC: if (dev_to_hdlc(dev)->proto != &proto) /* Different proto */ return -EINVAL; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&pvc, ifr->ifr_settings.ifs_ifsu.fr_pvc, sizeof(fr_proto_pvc))) return -EFAULT; if (pvc.dlci <= 0 || pvc.dlci >= 1024) return -EINVAL; /* Only 10 bits, DLCI 0 reserved */ if (ifr->ifr_settings.type == IF_PROTO_FR_ADD_ETH_PVC || ifr->ifr_settings.type == IF_PROTO_FR_DEL_ETH_PVC) result = ARPHRD_ETHER; /* bridged Ethernet device */ else result = ARPHRD_DLCI; if (ifr->ifr_settings.type == IF_PROTO_FR_ADD_PVC || ifr->ifr_settings.type == IF_PROTO_FR_ADD_ETH_PVC) return fr_add_pvc(dev, pvc.dlci, result); else return fr_del_pvc(hdlc, pvc.dlci, result); } return -EINVAL; } static int __init mod_init(void) { register_hdlc_protocol(&proto); return 0; } static void __exit mod_exit(void) { unregister_hdlc_protocol(&proto); } module_init(mod_init); module_exit(mod_exit); MODULE_AUTHOR("Krzysztof Halasa <khc@pm.waw.pl>"); MODULE_DESCRIPTION("Frame-Relay protocol support for generic HDLC"); MODULE_LICENSE("GPL v2");
./CrossVul/dataset_final_sorted/CWE-264/c/bad_3524_6
crossvul-cpp_data_good_5804_0
/* * transform.c: support for building and running transformers * * Copyright (C) 2007-2011 David Lutterkort * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Lutterkort <dlutter@redhat.com> */ #include <config.h> #include <fnmatch.h> #include <glob.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <selinux/selinux.h> #include <stdbool.h> #include "internal.h" #include "memory.h" #include "augeas.h" #include "syntax.h" #include "transform.h" #include "errcode.h" static const int fnm_flags = FNM_PATHNAME; static const int glob_flags = GLOB_NOSORT; /* Extension for newly created files */ #define EXT_AUGNEW ".augnew" /* Extension for backup files */ #define EXT_AUGSAVE ".augsave" /* Loaded files are tracked underneath METATREE. When a file with name * FNAME is loaded, certain entries are made under METATREE / FNAME: * path : path where tree for FNAME is put * mtime : time of last modification of the file as reported by stat(2) * lens/info : information about where the applied lens was loaded from * lens/id : unique hexadecimal id of the lens * error : indication of errors during processing FNAME, or NULL * if processing succeeded * error/pos : position in file where error occured (for get errors) * error/path: path to tree node where error occurred (for put errors) * error/message : human-readable error message */ static const char *const s_path = "path"; static const char *const s_lens = "lens"; static const char *const s_info = "info"; static const char *const s_mtime = "mtime"; static const char *const s_error = "error"; /* These are all put underneath "error" */ static const char *const s_pos = "pos"; static const char *const s_message = "message"; static const char *const s_line = "line"; static const char *const s_char = "char"; /* * Filters */ struct filter *make_filter(struct string *glb, unsigned int include) { struct filter *f; make_ref(f); f->glob = glb; f->include = include; return f; } void free_filter(struct filter *f) { if (f == NULL) return; assert(f->ref == 0); unref(f->next, filter); unref(f->glob, string); free(f); } static const char *pathbase(const char *path) { const char *p = strrchr(path, SEP); return (p == NULL) ? path : p + 1; } static bool is_excl(struct tree *f) { return streqv(f->label, "excl") && f->value != NULL; } static bool is_incl(struct tree *f) { return streqv(f->label, "incl") && f->value != NULL; } static bool is_regular_file(const char *path) { int r; struct stat st; r = stat(path, &st); if (r < 0) return false; return S_ISREG(st.st_mode); } static char *mtime_as_string(struct augeas *aug, const char *fname) { int r; struct stat st; char *result = NULL; if (fname == NULL) { result = strdup("0"); ERR_NOMEM(result == NULL, aug); goto done; } r = stat(fname, &st); if (r < 0) { /* If we fail to stat, silently ignore the error * and report an impossible mtime */ result = strdup("0"); ERR_NOMEM(result == NULL, aug); } else { r = xasprintf(&result, "%ld", (long) st.st_mtime); ERR_NOMEM(r < 0, aug); } done: return result; error: FREE(result); return NULL; } /* fnmatch(3) which will match // in a pattern to a path, like glob(3) does */ static int fnmatch_normalize(const char *pattern, const char *string, int flags) { int i, j, r; char *pattern_norm = NULL; r = ALLOC_N(pattern_norm, strlen(pattern) + 1); if (r < 0) goto error; for (i = 0, j = 0; i < strlen(pattern); i++) { if (pattern[i] != '/' || pattern[i+1] != '/') { pattern_norm[j] = pattern[i]; j++; } } pattern_norm[j] = 0; r = fnmatch(pattern_norm, string, flags); FREE(pattern_norm); return r; error: if (pattern_norm != NULL) FREE(pattern_norm); return -1; } static bool file_current(struct augeas *aug, const char *fname, struct tree *finfo) { struct tree *mtime = tree_child(finfo, s_mtime); struct tree *file = NULL, *path = NULL; int r; struct stat st; int64_t mtime_i; if (mtime == NULL || mtime->value == NULL) return false; r = xstrtoint64(mtime->value, 10, &mtime_i); if (r < 0) { /* Ignore silently and err on the side of caution */ return false; } r = stat(fname, &st); if (r < 0) return false; if (mtime_i != (int64_t) st.st_mtime) return false; path = tree_child(finfo, s_path); if (path == NULL) return false; file = tree_fpath(aug, path->value); return (file != NULL && ! file->dirty); } static int filter_generate(struct tree *xfm, const char *root, int *nmatches, char ***matches) { glob_t globbuf; int gl_flags = glob_flags; int r; int ret = 0; char **pathv = NULL; int pathc = 0; int root_prefix = strlen(root) - 1; *nmatches = 0; *matches = NULL; MEMZERO(&globbuf, 1); list_for_each(f, xfm->children) { char *globpat = NULL; if (! is_incl(f)) continue; pathjoin(&globpat, 2, root, f->value); r = glob(globpat, gl_flags, NULL, &globbuf); free(globpat); if (r != 0 && r != GLOB_NOMATCH) goto error; gl_flags |= GLOB_APPEND; } pathc = globbuf.gl_pathc; int pathind = 0; if (ALLOC_N(pathv, pathc) < 0) goto error; for (int i=0; i < pathc; i++) { const char *path = globbuf.gl_pathv[i] + root_prefix; bool include = true; list_for_each(e, xfm->children) { if (! is_excl(e)) continue; if (strchr(e->value, SEP) == NULL) path = pathbase(path); r = fnmatch_normalize(e->value, path, fnm_flags); if (r < 0) goto error; else if (r == 0) include = false; } if (include) include = is_regular_file(globbuf.gl_pathv[i]); if (include) { pathv[pathind] = strdup(globbuf.gl_pathv[i]); if (pathv[pathind] == NULL) goto error; pathind += 1; } } pathc = pathind; if (REALLOC_N(pathv, pathc) == -1) goto error; *matches = pathv; *nmatches = pathc; done: globfree(&globbuf); return ret; error: if (pathv != NULL) for (int i=0; i < pathc; i++) free(pathv[i]); free(pathv); ret = -1; goto done; } static int filter_matches(struct tree *xfm, const char *path) { int found = 0; list_for_each(f, xfm->children) { if (is_incl(f) && fnmatch_normalize(f->value, path, fnm_flags) == 0) { found = 1; break; } } if (! found) return 0; list_for_each(f, xfm->children) { if (is_excl(f) && (fnmatch_normalize(f->value, path, fnm_flags) == 0)) return 0; } return 1; } /* * Transformers */ struct transform *make_transform(struct lens *lens, struct filter *filter) { struct transform *xform; make_ref(xform); xform->lens = lens; xform->filter = filter; return xform; } void free_transform(struct transform *xform) { if (xform == NULL) return; assert(xform->ref == 0); unref(xform->lens, lens); unref(xform->filter, filter); free(xform); } static char *err_path(const char *filename) { char *result = NULL; if (filename == NULL) pathjoin(&result, 2, AUGEAS_META_FILES, s_error); else pathjoin(&result, 3, AUGEAS_META_FILES, filename, s_error); return result; } ATTRIBUTE_FORMAT(printf, 4, 5) static void err_set(struct augeas *aug, struct tree *err_info, const char *sub, const char *format, ...) { int r; va_list ap; char *value = NULL; struct tree *tree = NULL; va_start(ap, format); r = vasprintf(&value, format, ap); va_end(ap); if (r < 0) value = NULL; ERR_NOMEM(r < 0, aug); tree = tree_child_cr(err_info, sub); ERR_NOMEM(tree == NULL, aug); r = tree_set_value(tree, value); ERR_NOMEM(r < 0, aug); error: free(value); } /* Record an error in the tree. The error will show up underneath * /augeas/FILENAME/error if filename is not NULL, and underneath * /augeas/text/PATH otherwise. PATH is the path to the toplevel node in * the tree where the lens application happened. When STATUS is NULL, just * clear any error associated with FILENAME in the tree. */ static int store_error(struct augeas *aug, const char *filename, const char *path, const char *status, int errnum, const struct lns_error *err, const char *text) { struct tree *err_info = NULL, *finfo = NULL; char *fip = NULL; int r; int result = -1; if (filename != NULL) { r = pathjoin(&fip, 2, AUGEAS_META_FILES, filename); } else { r = pathjoin(&fip, 2, AUGEAS_META_TEXT, path); } ERR_NOMEM(r < 0, aug); finfo = tree_fpath_cr(aug, fip); ERR_BAIL(aug); if (status != NULL) { err_info = tree_child_cr(finfo, s_error); ERR_NOMEM(err_info == NULL, aug); r = tree_set_value(err_info, status); ERR_NOMEM(r < 0, aug); /* Errors from err_set are ignored on purpose. We try * to report as much as we can */ if (err != NULL) { if (err->pos >= 0) { size_t line, ofs; err_set(aug, err_info, s_pos, "%d", err->pos); if (text != NULL) { calc_line_ofs(text, err->pos, &line, &ofs); err_set(aug, err_info, s_line, "%zd", line); err_set(aug, err_info, s_char, "%zd", ofs); } } if (err->path != NULL) { err_set(aug, err_info, s_path, "%s%s", path, err->path); } if (err->lens != NULL) { char *fi = format_info(err->lens->info); if (fi != NULL) { err_set(aug, err_info, s_lens, "%s", fi); free(fi); } } err_set(aug, err_info, s_message, "%s", err->message); } else if (errnum != 0) { const char *msg = strerror(errnum); err_set(aug, err_info, s_message, "%s", msg); } } else { /* No error, nuke the error node if it exists */ err_info = tree_child(finfo, s_error); if (err_info != NULL) tree_unlink(aug, err_info); } tree_clean(finfo); result = 0; error: free(fip); return result; } /* Set up the file information in the /augeas tree. * * NODE must be the path to the file contents, and start with /files. * LENS is the lens used to transform the file. * Create entries under /augeas/NODE with some metadata about the file. * * Returns 0 on success, -1 on error */ static int add_file_info(struct augeas *aug, const char *node, struct lens *lens, const char *lens_name, const char *filename, bool force_reload) { struct tree *file, *tree; char *tmp = NULL; int r; char *path = NULL; int result = -1; if (lens == NULL) return -1; r = pathjoin(&path, 2, AUGEAS_META_TREE, node); ERR_NOMEM(r < 0, aug); file = tree_fpath_cr(aug, path); ERR_BAIL(aug); /* Set 'path' */ tree = tree_child_cr(file, s_path); ERR_NOMEM(tree == NULL, aug); r = tree_set_value(tree, node); ERR_NOMEM(r < 0, aug); /* Set 'mtime' */ if (force_reload) { tmp = strdup("0"); ERR_NOMEM(tmp == NULL, aug); } else { tmp = mtime_as_string(aug, filename); ERR_BAIL(aug); } tree = tree_child_cr(file, s_mtime); ERR_NOMEM(tree == NULL, aug); tree_store_value(tree, &tmp); /* Set 'lens/info' */ tmp = format_info(lens->info); ERR_NOMEM(tmp == NULL, aug); tree = tree_path_cr(file, 2, s_lens, s_info); ERR_NOMEM(tree == NULL, aug); r = tree_set_value(tree, tmp); ERR_NOMEM(r < 0, aug); FREE(tmp); /* Set 'lens' */ tree = tree->parent; r = tree_set_value(tree, lens_name); ERR_NOMEM(r < 0, aug); tree_clean(file); result = 0; error: free(path); free(tmp); return result; } static char *append_newline(char *text, size_t len) { /* Try to append a newline; this is a big hack to work */ /* around the fact that lenses generally break if the */ /* file does not end with a newline. */ if (len == 0 || text[len-1] != '\n') { if (REALLOC_N(text, len+2) == 0) { text[len] = '\n'; text[len+1] = '\0'; } } return text; } /* Turn the file name FNAME, which starts with aug->root, into * a path in the tree underneath /files */ static char *file_name_path(struct augeas *aug, const char *fname) { char *path = NULL; pathjoin(&path, 2, AUGEAS_FILES_TREE, fname + strlen(aug->root) - 1); return path; } /* Replace the subtree for FPATH with SUB */ static void tree_freplace(struct augeas *aug, const char *fpath, struct tree *sub) { struct tree *parent; parent = tree_fpath_cr(aug, fpath); ERR_RET(aug); tree_unlink_children(aug, parent); list_append(parent->children, sub); list_for_each(s, sub) { s->parent = parent; } } static int load_file(struct augeas *aug, struct lens *lens, const char *lens_name, char *filename) { char *text = NULL; const char *err_status = NULL; struct tree *tree = NULL; char *path = NULL; struct lns_error *err = NULL; struct span *span = NULL; int result = -1, r, text_len = 0; path = file_name_path(aug, filename); ERR_NOMEM(path == NULL, aug); r = add_file_info(aug, path, lens, lens_name, filename, false); if (r < 0) goto done; text = xread_file(filename); if (text == NULL) { err_status = "read_failed"; goto done; } text_len = strlen(text); text = append_newline(text, text_len); struct info *info; make_ref(info); make_ref(info->filename); info->filename->str = strdup(filename); info->error = aug->error; info->flags = aug->flags; info->first_line = 1; if (aug->flags & AUG_ENABLE_SPAN) { span = make_span(info); ERR_NOMEM(span == NULL, info); } tree = lns_get(info, lens, text, &err); unref(info, info); if (err != NULL) { err_status = "parse_failed"; goto done; } tree_freplace(aug, path, tree); ERR_BAIL(aug); /* top level node span entire file length */ if (span != NULL && tree != NULL) { tree->parent->span = span; tree->parent->span->span_start = 0; tree->parent->span->span_end = text_len; } tree = NULL; result = 0; done: store_error(aug, filename + strlen(aug->root) - 1, path, err_status, errno, err, text); error: free_lns_error(err); free(path); free_tree(tree); free(text); return result; } /* The lens for a transform can be referred to in one of two ways: * either by a fully qualified name "Module.lens" or by the special * syntax "@Module"; the latter means we should take the lens from the * autoload transform for Module */ static struct lens *lens_from_name(struct augeas *aug, const char *name) { struct lens *result = NULL; if (name[0] == '@') { struct module *modl = NULL; for (modl = aug->modules; modl != NULL && !streqv(modl->name, name + 1); modl = modl->next); ERR_THROW(modl == NULL, aug, AUG_ENOLENS, "Could not find module %s", name + 1); ERR_THROW(modl->autoload == NULL, aug, AUG_ENOLENS, "No autoloaded lens in module %s", name + 1); result = modl->autoload->lens; } else { result = lens_lookup(aug, name); } ERR_THROW(result == NULL, aug, AUG_ENOLENS, "Can not find lens %s", name); return result; error: return NULL; } int text_store(struct augeas *aug, const char *lens_path, const char *path, const char *text) { struct info *info = NULL; struct lns_error *err = NULL; struct tree *tree = NULL; struct span *span = NULL; int result = -1; const char *err_status = NULL; struct lens *lens = NULL; lens = lens_from_name(aug, lens_path); ERR_BAIL(aug); make_ref(info); info->first_line = 1; info->last_line = 1; info->first_column = 1; info->last_column = strlen(text); tree = lns_get(info, lens, text, &err); if (err != NULL) { err_status = "parse_failed"; goto error; } unref(info, info); tree_freplace(aug, path, tree); ERR_BAIL(aug); /* top level node span entire file length */ if (span != NULL && tree != NULL) { tree->parent->span = span; tree->parent->span->span_start = 0; tree->parent->span->span_end = strlen(text); } tree = NULL; result = 0; error: store_error(aug, NULL, path, err_status, errno, err, text); free_tree(tree); free_lns_error(err); return result; } const char *xfm_lens_name(struct tree *xfm) { struct tree *l = tree_child(xfm, s_lens); if (l == NULL) return "(unknown)"; if (l->value == NULL) return "(noname)"; return l->value; } static struct lens *xfm_lens(struct augeas *aug, struct tree *xfm, const char **lens_name) { struct tree *l = NULL; for (l = xfm->children; l != NULL && !streqv("lens", l->label); l = l->next); if (l == NULL || l->value == NULL) return NULL; *lens_name = l->value; return lens_from_name(aug, l->value); } static void xfm_error(struct tree *xfm, const char *msg) { char *v = msg ? strdup(msg) : NULL; char *l = strdup("error"); if (l == NULL || v == NULL) return; tree_append(xfm, l, v); } int transform_validate(struct augeas *aug, struct tree *xfm) { struct tree *l = NULL; for (struct tree *t = xfm->children; t != NULL; ) { if (streqv(t->label, "lens")) { l = t; } else if ((is_incl(t) || (is_excl(t) && strchr(t->value, SEP) != NULL)) && t->value[0] != SEP) { /* Normalize relative paths to absolute ones */ int r; r = REALLOC_N(t->value, strlen(t->value) + 2); ERR_NOMEM(r < 0, aug); memmove(t->value + 1, t->value, strlen(t->value) + 1); t->value[0] = SEP; } if (streqv(t->label, "error")) { struct tree *del = t; t = del->next; tree_unlink(aug, del); } else { t = t->next; } } if (l == NULL) { xfm_error(xfm, "missing a child with label 'lens'"); return -1; } if (l->value == NULL) { xfm_error(xfm, "the 'lens' node does not contain a lens name"); return -1; } lens_from_name(aug, l->value); ERR_BAIL(aug); return 0; error: xfm_error(xfm, aug->error->details); return -1; } void transform_file_error(struct augeas *aug, const char *status, const char *filename, const char *format, ...) { char *ep = err_path(filename); struct tree *err; char *msg; va_list ap; int r; err = tree_fpath_cr(aug, ep); if (err == NULL) return; tree_unlink_children(aug, err); tree_set_value(err, status); err = tree_child_cr(err, s_message); if (err == NULL) return; va_start(ap, format); r = vasprintf(&msg, format, ap); va_end(ap); if (r < 0) return; tree_set_value(err, msg); free(msg); } static struct tree *file_info(struct augeas *aug, const char *fname) { char *path = NULL; struct tree *result = NULL; int r; r = pathjoin(&path, 2, AUGEAS_META_FILES, fname); ERR_NOMEM(r < 0, aug); result = tree_fpath(aug, path); ERR_BAIL(aug); error: free(path); return result; } int transform_load(struct augeas *aug, struct tree *xfm) { int nmatches = 0; char **matches; const char *lens_name; struct lens *lens = xfm_lens(aug, xfm, &lens_name); int r; if (lens == NULL) { // FIXME: Record an error and return 0 return -1; } r = filter_generate(xfm, aug->root, &nmatches, &matches); if (r == -1) return -1; for (int i=0; i < nmatches; i++) { const char *filename = matches[i] + strlen(aug->root) - 1; struct tree *finfo = file_info(aug, filename); if (finfo != NULL && !finfo->dirty && tree_child(finfo, s_lens) != NULL) { const char *s = xfm_lens_name(finfo); char *fpath = file_name_path(aug, matches[i]); transform_file_error(aug, "mxfm_load", filename, "Lenses %s and %s could be used to load this file", s, lens_name); aug_rm(aug, fpath); free(fpath); } else if (!file_current(aug, matches[i], finfo)) { load_file(aug, lens, lens_name, matches[i]); } if (finfo != NULL) finfo->dirty = 0; FREE(matches[i]); } lens_release(lens); free(matches); return 0; } int transform_applies(struct tree *xfm, const char *path) { if (STRNEQLEN(path, AUGEAS_FILES_TREE, strlen(AUGEAS_FILES_TREE)) || path[strlen(AUGEAS_FILES_TREE)] != SEP) return 0; return filter_matches(xfm, path + strlen(AUGEAS_FILES_TREE)); } static int transfer_file_attrs(FILE *from, FILE *to, const char **err_status) { struct stat st; int ret = 0; int selinux_enabled = (is_selinux_enabled() > 0); security_context_t con = NULL; int from_fd = fileno(from); int to_fd = fileno(to); ret = fstat(from_fd, &st); if (ret < 0) { *err_status = "replace_stat"; return -1; } if (selinux_enabled) { if (fgetfilecon(from_fd, &con) < 0 && errno != ENOTSUP) { *err_status = "replace_getfilecon"; return -1; } } if (fchown(to_fd, st.st_uid, st.st_gid) < 0) { *err_status = "replace_chown"; return -1; } if (fchmod(to_fd, st.st_mode) < 0) { *err_status = "replace_chmod"; return -1; } if (selinux_enabled && con != NULL) { if (fsetfilecon(to_fd, con) < 0 && errno != ENOTSUP) { *err_status = "replace_setfilecon"; return -1; } freecon(con); } return 0; } /* Try to rename FROM to TO. If that fails with an error other than EXDEV * or EBUSY, return -1. If the failure is EXDEV or EBUSY (which we assume * means that FROM or TO is a bindmounted file), and COPY_IF_RENAME_FAILS * is true, copy the contents of FROM into TO and delete FROM. * * If COPY_IF_RENAME_FAILS and UNLINK_IF_RENAME_FAILS are true, and the above * copy mechanism is used, it will unlink the TO path and open with O_EXCL * to ensure we only copy *from* a bind mount rather than into an attacker's * mount placed at TO (e.g. for .augsave). * * Return 0 on success (either rename succeeded or we copied the contents * over successfully), -1 on failure. */ static int clone_file(const char *from, const char *to, const char **err_status, int copy_if_rename_fails, int unlink_if_rename_fails) { FILE *from_fp = NULL, *to_fp = NULL; char buf[BUFSIZ]; size_t len; int to_fd = -1, to_oflags, r; int result = -1; if (rename(from, to) == 0) return 0; if ((errno != EXDEV && errno != EBUSY) || !copy_if_rename_fails) { *err_status = "rename"; return -1; } /* rename not possible, copy file contents */ if (!(from_fp = fopen(from, "r"))) { *err_status = "clone_open_src"; goto done; } if (unlink_if_rename_fails) { r = unlink(to); if (r < 0) { *err_status = "clone_unlink_dst"; goto done; } } to_oflags = unlink_if_rename_fails ? O_EXCL : O_TRUNC; if ((to_fd = open(to, O_WRONLY|O_CREAT|to_oflags, S_IRUSR|S_IWUSR)) < 0) { *err_status = "clone_open_dst"; goto done; } if (!(to_fp = fdopen(to_fd, "w"))) { *err_status = "clone_fdopen_dst"; goto done; } if (transfer_file_attrs(from_fp, to_fp, err_status) < 0) goto done; while ((len = fread(buf, 1, BUFSIZ, from_fp)) > 0) { if (fwrite(buf, 1, len, to_fp) != len) { *err_status = "clone_write"; goto done; } } if (ferror(from_fp)) { *err_status = "clone_read"; goto done; } if (fflush(to_fp) != 0) { *err_status = "clone_flush"; goto done; } if (fsync(fileno(to_fp)) < 0) { *err_status = "clone_sync"; goto done; } result = 0; done: if (from_fp != NULL) fclose(from_fp); if (to_fp != NULL) { if (fclose(to_fp) != 0) { *err_status = "clone_fclose_dst"; result = -1; } } else if (to_fd >= 0 && close(to_fd) < 0) { *err_status = "clone_close_dst"; result = -1; } if (result != 0) unlink(to); if (result == 0) unlink(from); return result; } static char *strappend(const char *s1, const char *s2) { size_t len = strlen(s1) + strlen(s2); char *result = NULL, *p; if (ALLOC_N(result, len + 1) < 0) return NULL; p = stpcpy(result, s1); stpcpy(p, s2); return result; } static int file_saved_event(struct augeas *aug, const char *path) { const char *saved = strrchr(AUGEAS_EVENTS_SAVED, SEP) + 1; struct pathx *px; struct tree *dummy; int r; px = pathx_aug_parse(aug, aug->origin, NULL, AUGEAS_EVENTS_SAVED "[last()]", true); ERR_BAIL(aug); if (pathx_find_one(px, &dummy) == 1) { r = tree_insert(px, saved, 0); if (r < 0) goto error; } if (! tree_set(px, path)) goto error; free_pathx(px); return 0; error: free_pathx(px); return -1; } /* * Save TREE->CHILDREN into the file PATH using the lens from XFORM. Errors * are noted in the /augeas/files hierarchy in AUG->ORIGIN under * PATH/error. * * Writing the file happens by first writing into a temp file, transferring all * file attributes of PATH to the temp file, and then renaming the temp file * back to PATH. * * Temp files are created alongside the destination file to enable the rename, * which may be the canonical path (PATH_canon) if PATH is a symlink. * * If the AUG_SAVE_NEWFILE flag is set, instead rename to PATH.augnew rather * than PATH. If AUG_SAVE_BACKUP is set, move the original to PATH.augsave. * (Always PATH.aug{new,save} irrespective of whether PATH is a symlink.) * * If the rename fails, and the entry AUGEAS_COPY_IF_FAILURE exists in * AUG->ORIGIN, PATH is instead overwritten by copying file contents. * * The table below shows the locations for each permutation. * * PATH save flag temp file dest file backup? * regular - PATH.XXXX PATH - * regular BACKUP PATH.XXXX PATH PATH.augsave * regular NEWFILE PATH.augnew.XXXX PATH.augnew - * symlink - PATH_canon.XXXX PATH_canon - * symlink BACKUP PATH_canon.XXXX PATH_canon PATH.augsave * symlink NEWFILE PATH.augnew.XXXX PATH.augnew - * * Return 0 on success, -1 on failure. */ int transform_save(struct augeas *aug, struct tree *xfm, const char *path, struct tree *tree) { int fd; FILE *fp = NULL, *augorig_canon_fp = NULL; char *augtemp = NULL, *augnew = NULL, *augorig = NULL, *augsave = NULL; char *augorig_canon = NULL, *augdest = NULL; int augorig_exists; int copy_if_rename_fails = 0; char *text = NULL; const char *filename = path + strlen(AUGEAS_FILES_TREE) + 1; const char *err_status = NULL; char *dyn_err_status = NULL; struct lns_error *err = NULL; const char *lens_name; struct lens *lens = xfm_lens(aug, xfm, &lens_name); int result = -1, r; bool force_reload; errno = 0; if (lens == NULL) { err_status = "lens_name"; goto done; } copy_if_rename_fails = aug_get(aug, AUGEAS_COPY_IF_RENAME_FAILS, NULL) == 1; if (asprintf(&augorig, "%s%s", aug->root, filename) == -1) { augorig = NULL; goto done; } augorig_canon = canonicalize_file_name(augorig); augorig_exists = 1; if (augorig_canon == NULL) { if (errno == ENOENT) { augorig_canon = augorig; augorig_exists = 0; } else { err_status = "canon_augorig"; goto done; } } if (access(augorig_canon, R_OK) == 0) { augorig_canon_fp = fopen(augorig_canon, "r"); text = xfread_file(augorig_canon_fp); } else { text = strdup(""); } if (text == NULL) { err_status = "put_read"; goto done; } text = append_newline(text, strlen(text)); /* Figure out where to put the .augnew and temp file. If no .augnew file then put the temp file next to augorig_canon, else next to .augnew. */ if (aug->flags & AUG_SAVE_NEWFILE) { if (xasprintf(&augnew, "%s" EXT_AUGNEW, augorig) < 0) { err_status = "augnew_oom"; goto done; } augdest = augnew; } else { augdest = augorig_canon; } if (xasprintf(&augtemp, "%s.XXXXXX", augdest) < 0) { err_status = "augtemp_oom"; goto done; } // FIXME: We might have to create intermediate directories // to be able to write augnew, but we have no idea what permissions // etc. they should get. Just the process default ? fd = mkstemp(augtemp); if (fd < 0) { err_status = "mk_augtemp"; goto done; } fp = fdopen(fd, "w"); if (fp == NULL) { err_status = "open_augtemp"; goto done; } if (augorig_exists) { if (transfer_file_attrs(augorig_canon_fp, fp, &err_status) != 0) { err_status = "xfer_attrs"; goto done; } } else { /* Since mkstemp is used, the temp file will have secure permissions * instead of those implied by umask, so change them for new files */ mode_t curumsk = umask(022); umask(curumsk); if (fchmod(fileno(fp), 0666 & ~curumsk) < 0) { err_status = "create_chmod"; return -1; } } if (tree != NULL) lns_put(fp, lens, tree->children, text, &err); if (ferror(fp)) { err_status = "error_augtemp"; goto done; } if (fflush(fp) != 0) { err_status = "flush_augtemp"; goto done; } if (fsync(fileno(fp)) < 0) { err_status = "sync_augtemp"; goto done; } if (fclose(fp) != 0) { err_status = "close_augtemp"; fp = NULL; goto done; } fp = NULL; if (err != NULL) { err_status = err->pos >= 0 ? "parse_skel_failed" : "put_failed"; unlink(augtemp); goto done; } { char *new_text = xread_file(augtemp); int same = 0; if (new_text == NULL) { err_status = "read_augtemp"; goto done; } same = STREQ(text, new_text); FREE(new_text); if (same) { result = 0; unlink(augtemp); goto done; } else if (aug->flags & AUG_SAVE_NOOP) { result = 1; unlink(augtemp); goto done; } } if (!(aug->flags & AUG_SAVE_NEWFILE)) { if (augorig_exists && (aug->flags & AUG_SAVE_BACKUP)) { r = xasprintf(&augsave, "%s" EXT_AUGSAVE, augorig); if (r == -1) { augsave = NULL; goto done; } r = clone_file(augorig_canon, augsave, &err_status, 1, 1); if (r != 0) { dyn_err_status = strappend(err_status, "_augsave"); goto done; } } } r = clone_file(augtemp, augdest, &err_status, copy_if_rename_fails, 0); if (r != 0) { dyn_err_status = strappend(err_status, "_augtemp"); goto done; } result = 1; done: force_reload = aug->flags & AUG_SAVE_NEWFILE; r = add_file_info(aug, path, lens, lens_name, augorig, force_reload); if (r < 0) { err_status = "file_info"; result = -1; } if (result > 0) { r = file_saved_event(aug, path); if (r < 0) { err_status = "saved_event"; result = -1; } } { const char *emsg = dyn_err_status == NULL ? err_status : dyn_err_status; store_error(aug, filename, path, emsg, errno, err, text); } free(dyn_err_status); lens_release(lens); free(text); free(augtemp); free(augnew); if (augorig_canon != augorig) free(augorig_canon); free(augorig); free(augsave); free_lns_error(err); if (fp != NULL) fclose(fp); if (augorig_canon_fp != NULL) fclose(augorig_canon_fp); return result; } int text_retrieve(struct augeas *aug, const char *lens_name, const char *path, struct tree *tree, const char *text_in, char **text_out) { struct memstream ms; bool ms_open = false; const char *err_status = NULL; char *dyn_err_status = NULL; struct lns_error *err = NULL; struct lens *lens = NULL; int result = -1, r; MEMZERO(&ms, 1); errno = 0; lens = lens_from_name(aug, lens_name); if (lens == NULL) { err_status = "lens_name"; goto done; } r = init_memstream(&ms); if (r < 0) { err_status = "init_memstream"; goto done; } ms_open = true; if (tree != NULL) lns_put(ms.stream, lens, tree->children, text_in, &err); r = close_memstream(&ms); ms_open = false; if (r < 0) { err_status = "close_memstream"; goto done; } *text_out = ms.buf; ms.buf = NULL; if (err != NULL) { err_status = err->pos >= 0 ? "parse_skel_failed" : "put_failed"; goto done; } result = 0; done: { const char *emsg = dyn_err_status == NULL ? err_status : dyn_err_status; store_error(aug, NULL, path, emsg, errno, err, text_in); } free(dyn_err_status); lens_release(lens); if (result < 0) { free(*text_out); *text_out = NULL; } free_lns_error(err); if (ms_open) close_memstream(&ms); return result; } int remove_file(struct augeas *aug, struct tree *tree) { char *path = NULL; const char *filename = NULL; const char *err_status = NULL; char *dyn_err_status = NULL; char *augsave = NULL, *augorig = NULL, *augorig_canon = NULL; int r; path = path_of_tree(tree); if (path == NULL) { err_status = "path_of_tree"; goto error; } filename = path + strlen(AUGEAS_META_FILES); if ((augorig = strappend(aug->root, filename + 1)) == NULL) { err_status = "root_file"; goto error; } augorig_canon = canonicalize_file_name(augorig); if (augorig_canon == NULL) { if (errno == ENOENT) { goto done; } else { err_status = "canon_augorig"; goto error; } } r = file_saved_event(aug, path + strlen(AUGEAS_META_TREE)); if (r < 0) { err_status = "saved_event"; goto error; } if (aug->flags & AUG_SAVE_NOOP) goto done; if (aug->flags & AUG_SAVE_BACKUP) { /* Move file to one with extension .augsave */ r = asprintf(&augsave, "%s" EXT_AUGSAVE, augorig_canon); if (r == -1) { augsave = NULL; goto error; } r = clone_file(augorig_canon, augsave, &err_status, 1, 1); if (r != 0) { dyn_err_status = strappend(err_status, "_augsave"); goto error; } } else { /* Unlink file */ r = unlink(augorig_canon); if (r < 0) { err_status = "unlink_orig"; goto error; } } tree_unlink(aug, tree); done: free(path); free(augorig); free(augorig_canon); free(augsave); return 0; error: { const char *emsg = dyn_err_status == NULL ? err_status : dyn_err_status; store_error(aug, filename, path, emsg, errno, NULL, NULL); } free(path); free(augorig); free(augorig_canon); free(augsave); free(dyn_err_status); return -1; } /* * Local variables: * indent-tabs-mode: nil * c-indent-level: 4 * c-basic-offset: 4 * tab-width: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-264/c/good_5804_0
crossvul-cpp_data_bad_5749_0
/* * 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 Internet Protocol (IP) output module. * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Donald Becker, <becker@super.org> * Alan Cox, <Alan.Cox@linux.org> * Richard Underwood * Stefan Becker, <stefanb@yello.ping.de> * Jorge Cwik, <jorge@laser.satlink.net> * Arnt Gulbrandsen, <agulbra@nvg.unit.no> * Hirokazu Takahashi, <taka@valinux.co.jp> * * See ip_input.c for original log * * Fixes: * Alan Cox : Missing nonblock feature in ip_build_xmit. * Mike Kilburn : htons() missing in ip_build_xmit. * Bradford Johnson: Fix faulty handling of some frames when * no route is found. * Alexander Demenshin: Missing sk/skb free in ip_queue_xmit * (in case if packet not accepted by * output firewall rules) * Mike McLagan : Routing by source * Alexey Kuznetsov: use new route cache * Andi Kleen: Fix broken PMTU recovery and remove * some redundant tests. * Vitaly E. Lavrov : Transparent proxy revived after year coma. * Andi Kleen : Replace ip_reply with ip_send_reply. * Andi Kleen : Split fast and slow ip_build_xmit path * for decreased register pressure on x86 * and more readibility. * Marc Boucher : When call_out_firewall returns FW_QUEUE, * silently drop skb instead of failing with -EPERM. * Detlev Wengorz : Copy protocol for fragments. * Hirokazu Takahashi: HW checksumming for outgoing UDP * datagrams. * Hirokazu Takahashi: sendfile() on UDP works now. */ #include <asm/uaccess.h> #include <linux/module.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/string.h> #include <linux/errno.h> #include <linux/highmem.h> #include <linux/slab.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/in.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/proc_fs.h> #include <linux/stat.h> #include <linux/init.h> #include <net/snmp.h> #include <net/ip.h> #include <net/protocol.h> #include <net/route.h> #include <net/xfrm.h> #include <linux/skbuff.h> #include <net/sock.h> #include <net/arp.h> #include <net/icmp.h> #include <net/checksum.h> #include <net/inetpeer.h> #include <linux/igmp.h> #include <linux/netfilter_ipv4.h> #include <linux/netfilter_bridge.h> #include <linux/mroute.h> #include <linux/netlink.h> #include <linux/tcp.h> int sysctl_ip_default_ttl __read_mostly = IPDEFTTL; EXPORT_SYMBOL(sysctl_ip_default_ttl); /* Generate a checksum for an outgoing IP datagram. */ void ip_send_check(struct iphdr *iph) { iph->check = 0; iph->check = ip_fast_csum((unsigned char *)iph, iph->ihl); } EXPORT_SYMBOL(ip_send_check); int __ip_local_out(struct sk_buff *skb) { struct iphdr *iph = ip_hdr(skb); iph->tot_len = htons(skb->len); ip_send_check(iph); return nf_hook(NFPROTO_IPV4, NF_INET_LOCAL_OUT, skb, NULL, skb_dst(skb)->dev, dst_output); } int ip_local_out(struct sk_buff *skb) { int err; err = __ip_local_out(skb); if (likely(err == 1)) err = dst_output(skb); return err; } EXPORT_SYMBOL_GPL(ip_local_out); static inline int ip_select_ttl(struct inet_sock *inet, struct dst_entry *dst) { int ttl = inet->uc_ttl; if (ttl < 0) ttl = ip4_dst_hoplimit(dst); return ttl; } /* * Add an ip header to a skbuff and send it out. * */ int ip_build_and_send_pkt(struct sk_buff *skb, struct sock *sk, __be32 saddr, __be32 daddr, struct ip_options_rcu *opt) { struct inet_sock *inet = inet_sk(sk); struct rtable *rt = skb_rtable(skb); struct iphdr *iph; /* Build the IP header. */ skb_push(skb, sizeof(struct iphdr) + (opt ? opt->opt.optlen : 0)); skb_reset_network_header(skb); iph = ip_hdr(skb); iph->version = 4; iph->ihl = 5; iph->tos = inet->tos; if (ip_dont_fragment(sk, &rt->dst)) iph->frag_off = htons(IP_DF); else iph->frag_off = 0; iph->ttl = ip_select_ttl(inet, &rt->dst); iph->daddr = (opt && opt->opt.srr ? opt->opt.faddr : daddr); iph->saddr = saddr; iph->protocol = sk->sk_protocol; ip_select_ident(skb, &rt->dst, sk); if (opt && opt->opt.optlen) { iph->ihl += opt->opt.optlen>>2; ip_options_build(skb, &opt->opt, daddr, rt, 0); } skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; /* Send it out. */ return ip_local_out(skb); } EXPORT_SYMBOL_GPL(ip_build_and_send_pkt); static inline int ip_finish_output2(struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct rtable *rt = (struct rtable *)dst; struct net_device *dev = dst->dev; unsigned int hh_len = LL_RESERVED_SPACE(dev); struct neighbour *neigh; u32 nexthop; if (rt->rt_type == RTN_MULTICAST) { IP_UPD_PO_STATS(dev_net(dev), IPSTATS_MIB_OUTMCAST, skb->len); } else if (rt->rt_type == RTN_BROADCAST) IP_UPD_PO_STATS(dev_net(dev), IPSTATS_MIB_OUTBCAST, skb->len); /* Be paranoid, rather than too clever. */ if (unlikely(skb_headroom(skb) < hh_len && dev->header_ops)) { struct sk_buff *skb2; skb2 = skb_realloc_headroom(skb, LL_RESERVED_SPACE(dev)); if (skb2 == NULL) { kfree_skb(skb); return -ENOMEM; } if (skb->sk) skb_set_owner_w(skb2, skb->sk); consume_skb(skb); skb = skb2; } rcu_read_lock_bh(); nexthop = (__force u32) rt_nexthop(rt, ip_hdr(skb)->daddr); neigh = __ipv4_neigh_lookup_noref(dev, nexthop); if (unlikely(!neigh)) neigh = __neigh_create(&arp_tbl, &nexthop, dev, false); if (!IS_ERR(neigh)) { int res = dst_neigh_output(dst, neigh, skb); rcu_read_unlock_bh(); return res; } rcu_read_unlock_bh(); net_dbg_ratelimited("%s: No header cache and no neighbour!\n", __func__); kfree_skb(skb); return -EINVAL; } static int ip_finish_output(struct sk_buff *skb) { #if defined(CONFIG_NETFILTER) && defined(CONFIG_XFRM) /* Policy lookup after SNAT yielded a new policy */ if (skb_dst(skb)->xfrm != NULL) { IPCB(skb)->flags |= IPSKB_REROUTED; return dst_output(skb); } #endif if (skb->len > ip_skb_dst_mtu(skb) && !skb_is_gso(skb)) return ip_fragment(skb, ip_finish_output2); else return ip_finish_output2(skb); } int ip_mc_output(struct sk_buff *skb) { struct sock *sk = skb->sk; struct rtable *rt = skb_rtable(skb); struct net_device *dev = rt->dst.dev; /* * If the indicated interface is up and running, send the packet. */ IP_UPD_PO_STATS(dev_net(dev), IPSTATS_MIB_OUT, skb->len); skb->dev = dev; skb->protocol = htons(ETH_P_IP); /* * Multicasts are looped back for other local users */ if (rt->rt_flags&RTCF_MULTICAST) { if (sk_mc_loop(sk) #ifdef CONFIG_IP_MROUTE /* Small optimization: do not loopback not local frames, which returned after forwarding; they will be dropped by ip_mr_input in any case. Note, that local frames are looped back to be delivered to local recipients. This check is duplicated in ip_mr_input at the moment. */ && ((rt->rt_flags & RTCF_LOCAL) || !(IPCB(skb)->flags & IPSKB_FORWARDED)) #endif ) { struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC); if (newskb) NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING, newskb, NULL, newskb->dev, dev_loopback_xmit); } /* Multicasts with ttl 0 must not go beyond the host */ if (ip_hdr(skb)->ttl == 0) { kfree_skb(skb); return 0; } } if (rt->rt_flags&RTCF_BROADCAST) { struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC); if (newskb) NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING, newskb, NULL, newskb->dev, dev_loopback_xmit); } return NF_HOOK_COND(NFPROTO_IPV4, NF_INET_POST_ROUTING, skb, NULL, skb->dev, ip_finish_output, !(IPCB(skb)->flags & IPSKB_REROUTED)); } int ip_output(struct sk_buff *skb) { struct net_device *dev = skb_dst(skb)->dev; IP_UPD_PO_STATS(dev_net(dev), IPSTATS_MIB_OUT, skb->len); skb->dev = dev; skb->protocol = htons(ETH_P_IP); return NF_HOOK_COND(NFPROTO_IPV4, NF_INET_POST_ROUTING, skb, NULL, dev, ip_finish_output, !(IPCB(skb)->flags & IPSKB_REROUTED)); } /* * copy saddr and daddr, possibly using 64bit load/stores * Equivalent to : * iph->saddr = fl4->saddr; * iph->daddr = fl4->daddr; */ static void ip_copy_addrs(struct iphdr *iph, const struct flowi4 *fl4) { BUILD_BUG_ON(offsetof(typeof(*fl4), daddr) != offsetof(typeof(*fl4), saddr) + sizeof(fl4->saddr)); memcpy(&iph->saddr, &fl4->saddr, sizeof(fl4->saddr) + sizeof(fl4->daddr)); } int ip_queue_xmit(struct sk_buff *skb, struct flowi *fl) { struct sock *sk = skb->sk; struct inet_sock *inet = inet_sk(sk); struct ip_options_rcu *inet_opt; struct flowi4 *fl4; struct rtable *rt; struct iphdr *iph; int res; /* Skip all of this if the packet is already routed, * f.e. by something like SCTP. */ rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); fl4 = &fl->u.ip4; rt = skb_rtable(skb); if (rt != NULL) goto packet_routed; /* Make sure we can route this packet. */ rt = (struct rtable *)__sk_dst_check(sk, 0); if (rt == NULL) { __be32 daddr; /* Use correct destination address if we have options. */ daddr = inet->inet_daddr; 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; sk_setup_caps(sk, &rt->dst); } skb_dst_set_noref(skb, &rt->dst); packet_routed: if (inet_opt && inet_opt->opt.is_strictroute && rt->rt_uses_gateway) goto no_route; /* OK, we know where to send it, allocate and build IP header. */ skb_push(skb, sizeof(struct iphdr) + (inet_opt ? inet_opt->opt.optlen : 0)); skb_reset_network_header(skb); iph = ip_hdr(skb); *((__be16 *)iph) = htons((4 << 12) | (5 << 8) | (inet->tos & 0xff)); if (ip_dont_fragment(sk, &rt->dst) && !skb->local_df) iph->frag_off = htons(IP_DF); else iph->frag_off = 0; iph->ttl = ip_select_ttl(inet, &rt->dst); iph->protocol = sk->sk_protocol; ip_copy_addrs(iph, fl4); /* Transport layer set skb->h.foo itself. */ if (inet_opt && inet_opt->opt.optlen) { iph->ihl += inet_opt->opt.optlen >> 2; ip_options_build(skb, &inet_opt->opt, inet->inet_daddr, rt, 0); } ip_select_ident_more(skb, &rt->dst, sk, (skb_shinfo(skb)->gso_segs ?: 1) - 1); skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; res = ip_local_out(skb); rcu_read_unlock(); return res; no_route: rcu_read_unlock(); IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES); kfree_skb(skb); return -EHOSTUNREACH; } EXPORT_SYMBOL(ip_queue_xmit); static void ip_copy_metadata(struct sk_buff *to, struct sk_buff *from) { to->pkt_type = from->pkt_type; to->priority = from->priority; to->protocol = from->protocol; skb_dst_drop(to); skb_dst_copy(to, from); to->dev = from->dev; to->mark = from->mark; /* Copy the flags to each fragment. */ IPCB(to)->flags = IPCB(from)->flags; #ifdef CONFIG_NET_SCHED to->tc_index = from->tc_index; #endif nf_copy(to, from); #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE) to->nf_trace = from->nf_trace; #endif #if defined(CONFIG_IP_VS) || defined(CONFIG_IP_VS_MODULE) to->ipvs_property = from->ipvs_property; #endif skb_copy_secmark(to, from); } /* * This IP datagram is too large to be sent in one piece. Break it up into * smaller pieces (each of size equal to IP header plus * a block of the data of the original IP data part) that will yet fit in a * single device frame, and queue such a frame for sending. */ int ip_fragment(struct sk_buff *skb, int (*output)(struct sk_buff *)) { struct iphdr *iph; int ptr; struct net_device *dev; struct sk_buff *skb2; unsigned int mtu, hlen, left, len, ll_rs; int offset; __be16 not_last_frag; struct rtable *rt = skb_rtable(skb); int err = 0; dev = rt->dst.dev; /* * Point into the IP datagram header. */ iph = ip_hdr(skb); if (unlikely(((iph->frag_off & htons(IP_DF)) && !skb->local_df) || (IPCB(skb)->frag_max_size && IPCB(skb)->frag_max_size > dst_mtu(&rt->dst)))) { IP_INC_STATS(dev_net(dev), IPSTATS_MIB_FRAGFAILS); icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED, htonl(ip_skb_dst_mtu(skb))); kfree_skb(skb); return -EMSGSIZE; } /* * Setup starting values. */ hlen = iph->ihl * 4; mtu = dst_mtu(&rt->dst) - hlen; /* Size of data space */ #ifdef CONFIG_BRIDGE_NETFILTER if (skb->nf_bridge) mtu -= nf_bridge_mtu_reduction(skb); #endif IPCB(skb)->flags |= IPSKB_FRAG_COMPLETE; /* When frag_list is given, use it. First, check its validity: * some transformers could create wrong frag_list or break existing * one, it is not prohibited. In this case fall back to copying. * * LATER: this step can be merged to real generation of fragments, * we can switch to copy when see the first bad fragment. */ if (skb_has_frag_list(skb)) { struct sk_buff *frag, *frag2; int first_len = skb_pagelen(skb); if (first_len - hlen > mtu || ((first_len - hlen) & 7) || ip_is_fragment(iph) || skb_cloned(skb)) goto slow_path; skb_walk_frags(skb, frag) { /* Correct geometry. */ if (frag->len > mtu || ((frag->len & 7) && frag->next) || skb_headroom(frag) < hlen) goto slow_path_clean; /* Partially cloned skb? */ if (skb_shared(frag)) goto slow_path_clean; BUG_ON(frag->sk); if (skb->sk) { frag->sk = skb->sk; frag->destructor = sock_wfree; } skb->truesize -= frag->truesize; } /* Everything is OK. Generate! */ err = 0; offset = 0; frag = skb_shinfo(skb)->frag_list; skb_frag_list_init(skb); skb->data_len = first_len - skb_headlen(skb); skb->len = first_len; iph->tot_len = htons(first_len); iph->frag_off = htons(IP_MF); ip_send_check(iph); for (;;) { /* Prepare header of the next frame, * before previous one went down. */ if (frag) { frag->ip_summed = CHECKSUM_NONE; skb_reset_transport_header(frag); __skb_push(frag, hlen); skb_reset_network_header(frag); memcpy(skb_network_header(frag), iph, hlen); iph = ip_hdr(frag); iph->tot_len = htons(frag->len); ip_copy_metadata(frag, skb); if (offset == 0) ip_options_fragment(frag); offset += skb->len - hlen; iph->frag_off = htons(offset>>3); if (frag->next != NULL) iph->frag_off |= htons(IP_MF); /* Ready, complete checksum */ ip_send_check(iph); } err = output(skb); if (!err) IP_INC_STATS(dev_net(dev), IPSTATS_MIB_FRAGCREATES); if (err || !frag) break; skb = frag; frag = skb->next; skb->next = NULL; } if (err == 0) { IP_INC_STATS(dev_net(dev), IPSTATS_MIB_FRAGOKS); return 0; } while (frag) { skb = frag->next; kfree_skb(frag); frag = skb; } IP_INC_STATS(dev_net(dev), IPSTATS_MIB_FRAGFAILS); return err; slow_path_clean: skb_walk_frags(skb, frag2) { if (frag2 == frag) break; frag2->sk = NULL; frag2->destructor = NULL; skb->truesize += frag2->truesize; } } slow_path: /* for offloaded checksums cleanup checksum before fragmentation */ if ((skb->ip_summed == CHECKSUM_PARTIAL) && skb_checksum_help(skb)) goto fail; iph = ip_hdr(skb); left = skb->len - hlen; /* Space per frame */ ptr = hlen; /* Where to start from */ /* for bridged IP traffic encapsulated inside f.e. a vlan header, * we need to make room for the encapsulating header */ ll_rs = LL_RESERVED_SPACE_EXTRA(rt->dst.dev, nf_bridge_pad(skb)); /* * Fragment the datagram. */ offset = (ntohs(iph->frag_off) & IP_OFFSET) << 3; not_last_frag = iph->frag_off & htons(IP_MF); /* * Keep copying data until we run out. */ while (left > 0) { len = left; /* IF: it doesn't fit, use 'mtu' - the data space left */ if (len > mtu) len = mtu; /* IF: we are not sending up to and including the packet end then align the next start on an eight byte boundary */ if (len < left) { len &= ~7; } /* * Allocate buffer. */ if ((skb2 = alloc_skb(len+hlen+ll_rs, GFP_ATOMIC)) == NULL) { NETDEBUG(KERN_INFO "IP: frag: no memory for new fragment!\n"); err = -ENOMEM; goto fail; } /* * Set up data on packet */ ip_copy_metadata(skb2, skb); skb_reserve(skb2, ll_rs); skb_put(skb2, len + hlen); skb_reset_network_header(skb2); skb2->transport_header = skb2->network_header + hlen; /* * Charge the memory for the fragment to any owner * it might possess */ if (skb->sk) skb_set_owner_w(skb2, skb->sk); /* * Copy the packet header into the new buffer. */ skb_copy_from_linear_data(skb, skb_network_header(skb2), hlen); /* * Copy a block of the IP datagram. */ if (skb_copy_bits(skb, ptr, skb_transport_header(skb2), len)) BUG(); left -= len; /* * Fill in the new header fields. */ iph = ip_hdr(skb2); iph->frag_off = htons((offset >> 3)); /* ANK: dirty, but effective trick. Upgrade options only if * the segment to be fragmented was THE FIRST (otherwise, * options are already fixed) and make it ONCE * on the initial skb, so that all the following fragments * will inherit fixed options. */ if (offset == 0) ip_options_fragment(skb); /* * Added AC : If we are fragmenting a fragment that's not the * last fragment then keep MF on each bit */ if (left > 0 || not_last_frag) iph->frag_off |= htons(IP_MF); ptr += len; offset += len; /* * Put this fragment into the sending queue. */ iph->tot_len = htons(len + hlen); ip_send_check(iph); err = output(skb2); if (err) goto fail; IP_INC_STATS(dev_net(dev), IPSTATS_MIB_FRAGCREATES); } consume_skb(skb); IP_INC_STATS(dev_net(dev), IPSTATS_MIB_FRAGOKS); return err; fail: kfree_skb(skb); IP_INC_STATS(dev_net(dev), IPSTATS_MIB_FRAGFAILS); return err; } EXPORT_SYMBOL(ip_fragment); int ip_generic_getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb) { struct iovec *iov = from; if (skb->ip_summed == CHECKSUM_PARTIAL) { if (memcpy_fromiovecend(to, iov, offset, len) < 0) return -EFAULT; } else { __wsum csum = 0; if (csum_partial_copy_fromiovecend(to, iov, offset, len, &csum) < 0) return -EFAULT; skb->csum = csum_block_add(skb->csum, csum, odd); } return 0; } EXPORT_SYMBOL(ip_generic_getfrag); static inline __wsum csum_page(struct page *page, int offset, int copy) { char *kaddr; __wsum csum; kaddr = kmap(page); csum = csum_partial(kaddr + offset, copy, 0); kunmap(page); return csum; } static inline int ip_ufo_append_data(struct sock *sk, struct sk_buff_head *queue, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int transhdrlen, int maxfraglen, unsigned int flags) { struct sk_buff *skb; int err; /* There is support for UDP fragmentation offload by network * device, so create one single skb packet containing complete * udp datagram */ if ((skb = skb_peek_tail(queue)) == NULL) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (skb == NULL) return err; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb, fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_reset_network_header(skb); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->ip_summed = CHECKSUM_PARTIAL; skb->csum = 0; /* specify the length of each IP datagram fragment */ skb_shinfo(skb)->gso_size = maxfraglen - fragheaderlen; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; __skb_queue_tail(queue, skb); } return skb_append_datato_frags(sk, skb, getfrag, from, (length - transhdrlen)); } static int __ip_append_data(struct sock *sk, struct flowi4 *fl4, struct sk_buff_head *queue, struct inet_cork *cork, struct page_frag *pfrag, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, unsigned int flags) { struct inet_sock *inet = inet_sk(sk); struct sk_buff *skb; struct ip_options *opt = cork->opt; int hh_len; int exthdrlen; int mtu; int copy; int err; int offset = 0; unsigned int maxfraglen, fragheaderlen; int csummode = CHECKSUM_NONE; struct rtable *rt = (struct rtable *)cork->dst; skb = skb_peek_tail(queue); exthdrlen = !skb ? rt->dst.header_len : 0; mtu = cork->fragsize; hh_len = LL_RESERVED_SPACE(rt->dst.dev); fragheaderlen = sizeof(struct iphdr) + (opt ? opt->optlen : 0); maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen; if (cork->length + length > 0xFFFF - fragheaderlen) { ip_local_error(sk, EMSGSIZE, fl4->daddr, inet->inet_dport, mtu-exthdrlen); return -EMSGSIZE; } /* * transhdrlen > 0 means that this is the first fragment and we wish * it won't be fragmented in the future. */ if (transhdrlen && length + fragheaderlen <= mtu && rt->dst.dev->features & NETIF_F_V4_CSUM && !exthdrlen) csummode = CHECKSUM_PARTIAL; cork->length += length; if (((length > mtu) || (skb && skb_is_gso(skb))) && (sk->sk_protocol == IPPROTO_UDP) && (rt->dst.dev->features & NETIF_F_UFO) && !rt->dst.header_len) { err = ip_ufo_append_data(sk, queue, getfrag, from, length, hh_len, fragheaderlen, transhdrlen, maxfraglen, flags); if (err) goto error; return 0; } /* So, what's going on in the loop below? * * We use calculated fragment length to generate chained skb, * each of segments is IP fragment ready for sending to network after * adding appropriate IP header. */ if (!skb) goto alloc_new_skb; while (length > 0) { /* Check if the remaining data fits into current packet. */ copy = mtu - skb->len; if (copy < length) copy = maxfraglen - skb->len; if (copy <= 0) { char *data; unsigned int datalen; unsigned int fraglen; unsigned int fraggap; unsigned int alloclen; struct sk_buff *skb_prev; alloc_new_skb: skb_prev = skb; if (skb_prev) fraggap = skb_prev->len - maxfraglen; else fraggap = 0; /* * If remaining data exceeds the mtu, * we know we need more fragment(s). */ datalen = length + fraggap; if (datalen > mtu - fragheaderlen) datalen = maxfraglen - fragheaderlen; fraglen = datalen + fragheaderlen; if ((flags & MSG_MORE) && !(rt->dst.dev->features&NETIF_F_SG)) alloclen = mtu; else alloclen = fraglen; alloclen += exthdrlen; /* The last fragment gets additional space at tail. * Note, with MSG_MORE we overallocate on fragments, * because we have no idea what fragment will be * the last. */ if (datalen == length + fraggap) alloclen += rt->dst.trailer_len; if (transhdrlen) { skb = sock_alloc_send_skb(sk, alloclen + hh_len + 15, (flags & MSG_DONTWAIT), &err); } else { skb = NULL; if (atomic_read(&sk->sk_wmem_alloc) <= 2 * sk->sk_sndbuf) skb = sock_wmalloc(sk, alloclen + hh_len + 15, 1, sk->sk_allocation); if (unlikely(skb == NULL)) err = -ENOBUFS; else /* only the initial fragment is time stamped */ cork->tx_flags = 0; } if (skb == NULL) goto error; /* * Fill in the control structures */ skb->ip_summed = csummode; skb->csum = 0; skb_reserve(skb, hh_len); skb_shinfo(skb)->tx_flags = cork->tx_flags; /* * Find where to start putting bytes. */ data = skb_put(skb, fraglen + exthdrlen); skb_set_network_header(skb, exthdrlen); skb->transport_header = (skb->network_header + fragheaderlen); data += fragheaderlen + exthdrlen; if (fraggap) { skb->csum = skb_copy_and_csum_bits( skb_prev, maxfraglen, data + transhdrlen, fraggap, 0); skb_prev->csum = csum_sub(skb_prev->csum, skb->csum); data += fraggap; pskb_trim_unique(skb_prev, maxfraglen); } copy = datalen - transhdrlen - fraggap; if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) { err = -EFAULT; kfree_skb(skb); goto error; } offset += copy; length -= datalen - fraggap; transhdrlen = 0; exthdrlen = 0; csummode = CHECKSUM_NONE; /* * Put the packet on the pending queue. */ __skb_queue_tail(queue, skb); continue; } if (copy > length) copy = length; if (!(rt->dst.dev->features&NETIF_F_SG)) { unsigned int off; off = skb->len; if (getfrag(from, skb_put(skb, copy), offset, copy, off, skb) < 0) { __skb_trim(skb, off); err = -EFAULT; goto error; } } else { int i = skb_shinfo(skb)->nr_frags; err = -ENOMEM; if (!sk_page_frag_refill(sk, pfrag)) goto error; if (!skb_can_coalesce(skb, i, pfrag->page, pfrag->offset)) { err = -EMSGSIZE; if (i == MAX_SKB_FRAGS) goto error; __skb_fill_page_desc(skb, i, pfrag->page, pfrag->offset, 0); skb_shinfo(skb)->nr_frags = ++i; get_page(pfrag->page); } copy = min_t(int, copy, pfrag->size - pfrag->offset); if (getfrag(from, page_address(pfrag->page) + pfrag->offset, offset, copy, skb->len, skb) < 0) goto error_efault; pfrag->offset += copy; skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); skb->len += copy; skb->data_len += copy; skb->truesize += copy; atomic_add(copy, &sk->sk_wmem_alloc); } offset += copy; length -= copy; } return 0; error_efault: err = -EFAULT; error: cork->length -= length; IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTDISCARDS); return err; } static int ip_setup_cork(struct sock *sk, struct inet_cork *cork, struct ipcm_cookie *ipc, struct rtable **rtp) { struct inet_sock *inet = inet_sk(sk); struct ip_options_rcu *opt; struct rtable *rt; /* * setup for corking. */ opt = ipc->opt; if (opt) { if (cork->opt == NULL) { cork->opt = kmalloc(sizeof(struct ip_options) + 40, sk->sk_allocation); if (unlikely(cork->opt == NULL)) return -ENOBUFS; } memcpy(cork->opt, &opt->opt, sizeof(struct ip_options) + opt->opt.optlen); cork->flags |= IPCORK_OPT; cork->addr = ipc->addr; } rt = *rtp; if (unlikely(!rt)) return -EFAULT; /* * We steal reference to this route, caller should not release it */ *rtp = NULL; cork->fragsize = inet->pmtudisc == IP_PMTUDISC_PROBE ? rt->dst.dev->mtu : dst_mtu(&rt->dst); cork->dst = &rt->dst; cork->length = 0; cork->tx_flags = ipc->tx_flags; return 0; } /* * ip_append_data() and ip_append_page() can make one large IP datagram * from many pieces of data. Each pieces will be holded on the socket * until ip_push_pending_frames() is called. Each piece can be a page * or non-page data. * * Not only UDP, other transport protocols - e.g. raw sockets - can use * this interface potentially. * * LATER: length must be adjusted by pad at tail, when it is required. */ int ip_append_data(struct sock *sk, struct flowi4 *fl4, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, struct ipcm_cookie *ipc, struct rtable **rtp, unsigned int flags) { struct inet_sock *inet = inet_sk(sk); int err; if (flags&MSG_PROBE) return 0; if (skb_queue_empty(&sk->sk_write_queue)) { err = ip_setup_cork(sk, &inet->cork.base, ipc, rtp); if (err) return err; } else { transhdrlen = 0; } return __ip_append_data(sk, fl4, &sk->sk_write_queue, &inet->cork.base, sk_page_frag(sk), getfrag, from, length, transhdrlen, flags); } ssize_t ip_append_page(struct sock *sk, struct flowi4 *fl4, struct page *page, int offset, size_t size, int flags) { struct inet_sock *inet = inet_sk(sk); struct sk_buff *skb; struct rtable *rt; struct ip_options *opt = NULL; struct inet_cork *cork; int hh_len; int mtu; int len; int err; unsigned int maxfraglen, fragheaderlen, fraggap; if (inet->hdrincl) return -EPERM; if (flags&MSG_PROBE) return 0; if (skb_queue_empty(&sk->sk_write_queue)) return -EINVAL; cork = &inet->cork.base; rt = (struct rtable *)cork->dst; if (cork->flags & IPCORK_OPT) opt = cork->opt; if (!(rt->dst.dev->features&NETIF_F_SG)) return -EOPNOTSUPP; hh_len = LL_RESERVED_SPACE(rt->dst.dev); mtu = cork->fragsize; fragheaderlen = sizeof(struct iphdr) + (opt ? opt->optlen : 0); maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen; if (cork->length + size > 0xFFFF - fragheaderlen) { ip_local_error(sk, EMSGSIZE, fl4->daddr, inet->inet_dport, mtu); return -EMSGSIZE; } if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) return -EINVAL; cork->length += size; if ((size + skb->len > mtu) && (sk->sk_protocol == IPPROTO_UDP) && (rt->dst.dev->features & NETIF_F_UFO)) { skb_shinfo(skb)->gso_size = mtu - fragheaderlen; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; } while (size > 0) { int i; if (skb_is_gso(skb)) len = size; else { /* Check if the remaining data fits into current packet. */ len = mtu - skb->len; if (len < size) len = maxfraglen - skb->len; } if (len <= 0) { struct sk_buff *skb_prev; int alloclen; skb_prev = skb; fraggap = skb_prev->len - maxfraglen; alloclen = fragheaderlen + hh_len + fraggap + 15; skb = sock_wmalloc(sk, alloclen, 1, sk->sk_allocation); if (unlikely(!skb)) { err = -ENOBUFS; goto error; } /* * Fill in the control structures */ skb->ip_summed = CHECKSUM_NONE; skb->csum = 0; skb_reserve(skb, hh_len); /* * Find where to start putting bytes. */ skb_put(skb, fragheaderlen + fraggap); skb_reset_network_header(skb); skb->transport_header = (skb->network_header + fragheaderlen); if (fraggap) { skb->csum = skb_copy_and_csum_bits(skb_prev, maxfraglen, skb_transport_header(skb), fraggap, 0); skb_prev->csum = csum_sub(skb_prev->csum, skb->csum); pskb_trim_unique(skb_prev, maxfraglen); } /* * Put the packet on the pending queue. */ __skb_queue_tail(&sk->sk_write_queue, skb); continue; } i = skb_shinfo(skb)->nr_frags; if (len > size) len = size; if (skb_can_coalesce(skb, i, page, offset)) { skb_frag_size_add(&skb_shinfo(skb)->frags[i-1], len); } else if (i < MAX_SKB_FRAGS) { get_page(page); skb_fill_page_desc(skb, i, page, offset, len); } else { err = -EMSGSIZE; goto error; } if (skb->ip_summed == CHECKSUM_NONE) { __wsum csum; csum = csum_page(page, offset, len); skb->csum = csum_block_add(skb->csum, csum, skb->len); } skb->len += len; skb->data_len += len; skb->truesize += len; atomic_add(len, &sk->sk_wmem_alloc); offset += len; size -= len; } return 0; error: cork->length -= size; IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTDISCARDS); return err; } static void ip_cork_release(struct inet_cork *cork) { cork->flags &= ~IPCORK_OPT; kfree(cork->opt); cork->opt = NULL; dst_release(cork->dst); cork->dst = NULL; } /* * Combined all pending IP fragments on the socket as one IP datagram * and push them out. */ struct sk_buff *__ip_make_skb(struct sock *sk, struct flowi4 *fl4, struct sk_buff_head *queue, struct inet_cork *cork) { struct sk_buff *skb, *tmp_skb; struct sk_buff **tail_skb; struct inet_sock *inet = inet_sk(sk); struct net *net = sock_net(sk); struct ip_options *opt = NULL; struct rtable *rt = (struct rtable *)cork->dst; struct iphdr *iph; __be16 df = 0; __u8 ttl; if ((skb = __skb_dequeue(queue)) == NULL) goto out; tail_skb = &(skb_shinfo(skb)->frag_list); /* move skb->data to ip header from ext header */ if (skb->data < skb_network_header(skb)) __skb_pull(skb, skb_network_offset(skb)); while ((tmp_skb = __skb_dequeue(queue)) != NULL) { __skb_pull(tmp_skb, skb_network_header_len(skb)); *tail_skb = tmp_skb; tail_skb = &(tmp_skb->next); skb->len += tmp_skb->len; skb->data_len += tmp_skb->len; skb->truesize += tmp_skb->truesize; tmp_skb->destructor = NULL; tmp_skb->sk = NULL; } /* Unless user demanded real pmtu discovery (IP_PMTUDISC_DO), we allow * to fragment the frame generated here. No matter, what transforms * how transforms change size of the packet, it will come out. */ if (inet->pmtudisc < IP_PMTUDISC_DO) skb->local_df = 1; /* DF bit is set when we want to see DF on outgoing frames. * If local_df is set too, we still allow to fragment this frame * locally. */ if (inet->pmtudisc >= IP_PMTUDISC_DO || (skb->len <= dst_mtu(&rt->dst) && ip_dont_fragment(sk, &rt->dst))) df = htons(IP_DF); if (cork->flags & IPCORK_OPT) opt = cork->opt; if (rt->rt_type == RTN_MULTICAST) ttl = inet->mc_ttl; else ttl = ip_select_ttl(inet, &rt->dst); iph = ip_hdr(skb); iph->version = 4; iph->ihl = 5; iph->tos = inet->tos; iph->frag_off = df; iph->ttl = ttl; iph->protocol = sk->sk_protocol; ip_copy_addrs(iph, fl4); ip_select_ident(skb, &rt->dst, sk); if (opt) { iph->ihl += opt->optlen>>2; ip_options_build(skb, opt, cork->addr, rt, 0); } skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; /* * Steal rt from cork.dst to avoid a pair of atomic_inc/atomic_dec * on dst refcount */ cork->dst = NULL; skb_dst_set(skb, &rt->dst); if (iph->protocol == IPPROTO_ICMP) icmp_out_count(net, ((struct icmphdr *) skb_transport_header(skb))->type); ip_cork_release(cork); out: return skb; } int ip_send_skb(struct net *net, struct sk_buff *skb) { int err; err = ip_local_out(skb); if (err) { if (err > 0) err = net_xmit_errno(err); if (err) IP_INC_STATS(net, IPSTATS_MIB_OUTDISCARDS); } return err; } int ip_push_pending_frames(struct sock *sk, struct flowi4 *fl4) { struct sk_buff *skb; skb = ip_finish_skb(sk, fl4); if (!skb) return 0; /* Netfilter gets whole the not fragmented skb. */ return ip_send_skb(sock_net(sk), skb); } /* * Throw away all pending data on the socket. */ static void __ip_flush_pending_frames(struct sock *sk, struct sk_buff_head *queue, struct inet_cork *cork) { struct sk_buff *skb; while ((skb = __skb_dequeue_tail(queue)) != NULL) kfree_skb(skb); ip_cork_release(cork); } void ip_flush_pending_frames(struct sock *sk) { __ip_flush_pending_frames(sk, &sk->sk_write_queue, &inet_sk(sk)->cork.base); } struct sk_buff *ip_make_skb(struct sock *sk, struct flowi4 *fl4, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, struct ipcm_cookie *ipc, struct rtable **rtp, unsigned int flags) { struct inet_cork cork; struct sk_buff_head queue; int err; if (flags & MSG_PROBE) return NULL; __skb_queue_head_init(&queue); cork.flags = 0; cork.addr = 0; cork.opt = NULL; err = ip_setup_cork(sk, &cork, ipc, rtp); if (err) return ERR_PTR(err); err = __ip_append_data(sk, fl4, &queue, &cork, &current->task_frag, getfrag, from, length, transhdrlen, flags); if (err) { __ip_flush_pending_frames(sk, &queue, &cork); return ERR_PTR(err); } return __ip_make_skb(sk, fl4, &queue, &cork); } /* * Fetch data from kernel space and fill in checksum if needed. */ static int ip_reply_glue_bits(void *dptr, char *to, int offset, int len, int odd, struct sk_buff *skb) { __wsum csum; csum = csum_partial_copy_nocheck(dptr+offset, to, len, 0); skb->csum = csum_block_add(skb->csum, csum, odd); return 0; } /* * Generic function to send a packet as reply to another packet. * Used to send some TCP resets/acks so far. * * Use a fake percpu inet socket to avoid false sharing and contention. */ static DEFINE_PER_CPU(struct inet_sock, unicast_sock) = { .sk = { .__sk_common = { .skc_refcnt = ATOMIC_INIT(1), }, .sk_wmem_alloc = ATOMIC_INIT(1), .sk_allocation = GFP_ATOMIC, .sk_flags = (1UL << SOCK_USE_WRITE_QUEUE), }, .pmtudisc = IP_PMTUDISC_WANT, .uc_ttl = -1, }; void ip_send_unicast_reply(struct net *net, struct sk_buff *skb, __be32 daddr, __be32 saddr, const struct ip_reply_arg *arg, unsigned int len) { struct ip_options_data replyopts; struct ipcm_cookie ipc; struct flowi4 fl4; struct rtable *rt = skb_rtable(skb); struct sk_buff *nskb; struct sock *sk; struct inet_sock *inet; if (ip_options_echo(&replyopts.opt.opt, skb)) return; ipc.addr = daddr; ipc.opt = NULL; ipc.tx_flags = 0; if (replyopts.opt.opt.optlen) { ipc.opt = &replyopts.opt; if (replyopts.opt.opt.srr) daddr = replyopts.opt.opt.faddr; } flowi4_init_output(&fl4, arg->bound_dev_if, 0, RT_TOS(arg->tos), RT_SCOPE_UNIVERSE, ip_hdr(skb)->protocol, ip_reply_arg_flowi_flags(arg), daddr, saddr, tcp_hdr(skb)->source, tcp_hdr(skb)->dest); security_skb_classify_flow(skb, flowi4_to_flowi(&fl4)); rt = ip_route_output_key(net, &fl4); if (IS_ERR(rt)) return; inet = &get_cpu_var(unicast_sock); inet->tos = arg->tos; sk = &inet->sk; sk->sk_priority = skb->priority; sk->sk_protocol = ip_hdr(skb)->protocol; sk->sk_bound_dev_if = arg->bound_dev_if; sock_net_set(sk, net); __skb_queue_head_init(&sk->sk_write_queue); sk->sk_sndbuf = sysctl_wmem_default; ip_append_data(sk, &fl4, ip_reply_glue_bits, arg->iov->iov_base, len, 0, &ipc, &rt, MSG_DONTWAIT); nskb = skb_peek(&sk->sk_write_queue); if (nskb) { if (arg->csumoffset >= 0) *((__sum16 *)skb_transport_header(nskb) + arg->csumoffset) = csum_fold(csum_add(nskb->csum, arg->csum)); nskb->ip_summed = CHECKSUM_NONE; skb_orphan(nskb); skb_set_queue_mapping(nskb, skb_get_queue_mapping(skb)); ip_push_pending_frames(sk, &fl4); } put_cpu_var(unicast_sock); ip_rt_put(rt); } void __init ip_init(void) { ip_rt_init(); inet_initpeers(); #if defined(CONFIG_IP_MULTICAST) && defined(CONFIG_PROC_FS) igmp_mc_proc_init(); #endif }
./CrossVul/dataset_final_sorted/CWE-264/c/bad_5749_0
crossvul-cpp_data_bad_2287_4
/* * linux/fs/ext4/file.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/file.c * * Copyright (C) 1991, 1992 Linus Torvalds * * ext4 fs regular file handling primitives * * 64-bit file support on 64-bit platforms by Jakub Jelinek * (jj@sunsite.ms.mff.cuni.cz) */ #include <linux/time.h> #include <linux/fs.h> #include <linux/jbd2.h> #include <linux/mount.h> #include <linux/path.h> #include <linux/aio.h> #include <linux/quotaops.h> #include <linux/pagevec.h> #include "ext4.h" #include "ext4_jbd2.h" #include "xattr.h" #include "acl.h" /* * Called when an inode is released. Note that this is different * from ext4_file_open: open gets called at every open, but release * gets called only when /all/ the files are closed. */ static int ext4_release_file(struct inode *inode, struct file *filp) { if (ext4_test_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE)) { ext4_alloc_da_blocks(inode); ext4_clear_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE); } /* if we are the last writer on the inode, drop the block reservation */ if ((filp->f_mode & FMODE_WRITE) && (atomic_read(&inode->i_writecount) == 1) && !EXT4_I(inode)->i_reserved_data_blocks) { down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); up_write(&EXT4_I(inode)->i_data_sem); } if (is_dx(inode) && filp->private_data) ext4_htree_free_dir_info(filp->private_data); return 0; } void ext4_unwritten_wait(struct inode *inode) { wait_queue_head_t *wq = ext4_ioend_wq(inode); wait_event(*wq, (atomic_read(&EXT4_I(inode)->i_unwritten) == 0)); } /* * This tests whether the IO in question is block-aligned or not. * Ext4 utilizes unwritten extents when hole-filling during direct IO, and they * are converted to written only after the IO is complete. Until they are * mapped, these blocks appear as holes, so dio_zero_block() will assume that * it needs to zero out portions of the start and/or end block. If 2 AIO * threads are at work on the same unwritten block, they must be synchronized * or one thread will zero the other's data, causing corruption. */ static int ext4_unaligned_aio(struct inode *inode, struct iov_iter *from, loff_t pos) { struct super_block *sb = inode->i_sb; int blockmask = sb->s_blocksize - 1; if (pos >= i_size_read(inode)) return 0; if ((pos | iov_iter_alignment(from)) & blockmask) return 1; return 0; } static ssize_t ext4_file_write_iter(struct kiocb *iocb, struct iov_iter *from) { struct file *file = iocb->ki_filp; struct inode *inode = file_inode(iocb->ki_filp); struct mutex *aio_mutex = NULL; struct blk_plug plug; int o_direct = file->f_flags & O_DIRECT; int overwrite = 0; size_t length = iov_iter_count(from); ssize_t ret; loff_t pos = iocb->ki_pos; /* * Unaligned direct AIO must be serialized; see comment above * In the case of O_APPEND, assume that we must always serialize */ if (o_direct && ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) && !is_sync_kiocb(iocb) && (file->f_flags & O_APPEND || ext4_unaligned_aio(inode, from, pos))) { aio_mutex = ext4_aio_mutex(inode); mutex_lock(aio_mutex); ext4_unwritten_wait(inode); } mutex_lock(&inode->i_mutex); if (file->f_flags & O_APPEND) iocb->ki_pos = pos = i_size_read(inode); /* * If we have encountered a bitmap-format file, the size limit * is smaller than s_maxbytes, which is for extent-mapped files. */ if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) { struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); if ((pos > sbi->s_bitmap_maxbytes) || (pos == sbi->s_bitmap_maxbytes && length > 0)) { mutex_unlock(&inode->i_mutex); ret = -EFBIG; goto errout; } if (pos + length > sbi->s_bitmap_maxbytes) iov_iter_truncate(from, sbi->s_bitmap_maxbytes - pos); } if (o_direct) { blk_start_plug(&plug); iocb->private = &overwrite; /* check whether we do a DIO overwrite or not */ if (ext4_should_dioread_nolock(inode) && !aio_mutex && !file->f_mapping->nrpages && pos + length <= i_size_read(inode)) { struct ext4_map_blocks map; unsigned int blkbits = inode->i_blkbits; int err, len; map.m_lblk = pos >> blkbits; map.m_len = (EXT4_BLOCK_ALIGN(pos + length, blkbits) >> blkbits) - map.m_lblk; len = map.m_len; err = ext4_map_blocks(NULL, inode, &map, 0); /* * 'err==len' means that all of blocks has * been preallocated no matter they are * initialized or not. For excluding * unwritten extents, we need to check * m_flags. There are two conditions that * indicate for initialized extents. 1) If we * hit extent cache, EXT4_MAP_MAPPED flag is * returned; 2) If we do a real lookup, * non-flags are returned. So we should check * these two conditions. */ if (err == len && (map.m_flags & EXT4_MAP_MAPPED)) overwrite = 1; } } ret = __generic_file_write_iter(iocb, from); mutex_unlock(&inode->i_mutex); if (ret > 0) { ssize_t err; err = generic_write_sync(file, iocb->ki_pos - ret, ret); if (err < 0) ret = err; } if (o_direct) blk_finish_plug(&plug); errout: if (aio_mutex) mutex_unlock(aio_mutex); return ret; } static const struct vm_operations_struct ext4_file_vm_ops = { .fault = filemap_fault, .map_pages = filemap_map_pages, .page_mkwrite = ext4_page_mkwrite, .remap_pages = generic_file_remap_pages, }; static int ext4_file_mmap(struct file *file, struct vm_area_struct *vma) { struct address_space *mapping = file->f_mapping; if (!mapping->a_ops->readpage) return -ENOEXEC; file_accessed(file); vma->vm_ops = &ext4_file_vm_ops; return 0; } static int ext4_file_open(struct inode * inode, struct file * filp) { struct super_block *sb = inode->i_sb; struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); struct vfsmount *mnt = filp->f_path.mnt; struct path path; char buf[64], *cp; if (unlikely(!(sbi->s_mount_flags & EXT4_MF_MNTDIR_SAMPLED) && !(sb->s_flags & MS_RDONLY))) { sbi->s_mount_flags |= EXT4_MF_MNTDIR_SAMPLED; /* * Sample where the filesystem has been mounted and * store it in the superblock for sysadmin convenience * when trying to sort through large numbers of block * devices or filesystem images. */ memset(buf, 0, sizeof(buf)); path.mnt = mnt; path.dentry = mnt->mnt_root; cp = d_path(&path, buf, sizeof(buf)); if (!IS_ERR(cp)) { handle_t *handle; int err; handle = ext4_journal_start_sb(sb, EXT4_HT_MISC, 1); if (IS_ERR(handle)) return PTR_ERR(handle); err = ext4_journal_get_write_access(handle, sbi->s_sbh); if (err) { ext4_journal_stop(handle); return err; } strlcpy(sbi->s_es->s_last_mounted, cp, sizeof(sbi->s_es->s_last_mounted)); ext4_handle_dirty_super(handle, sb); ext4_journal_stop(handle); } } /* * Set up the jbd2_inode if we are opening the inode for * writing and the journal is present */ if (filp->f_mode & FMODE_WRITE) { int ret = ext4_inode_attach_jinode(inode); if (ret < 0) return ret; } return dquot_file_open(inode, filp); } /* * Here we use ext4_map_blocks() to get a block mapping for a extent-based * file rather than ext4_ext_walk_space() because we can introduce * SEEK_DATA/SEEK_HOLE for block-mapped and extent-mapped file at the same * function. When extent status tree has been fully implemented, it will * track all extent status for a file and we can directly use it to * retrieve the offset for SEEK_DATA/SEEK_HOLE. */ /* * When we retrieve the offset for SEEK_DATA/SEEK_HOLE, we would need to * lookup page cache to check whether or not there has some data between * [startoff, endoff] because, if this range contains an unwritten extent, * we determine this extent as a data or a hole according to whether the * page cache has data or not. */ static int ext4_find_unwritten_pgoff(struct inode *inode, int whence, struct ext4_map_blocks *map, loff_t *offset) { struct pagevec pvec; unsigned int blkbits; pgoff_t index; pgoff_t end; loff_t endoff; loff_t startoff; loff_t lastoff; int found = 0; blkbits = inode->i_sb->s_blocksize_bits; startoff = *offset; lastoff = startoff; endoff = (loff_t)(map->m_lblk + map->m_len) << blkbits; index = startoff >> PAGE_CACHE_SHIFT; end = endoff >> PAGE_CACHE_SHIFT; pagevec_init(&pvec, 0); do { int i, num; unsigned long nr_pages; num = min_t(pgoff_t, end - index, PAGEVEC_SIZE); nr_pages = pagevec_lookup(&pvec, inode->i_mapping, index, (pgoff_t)num); if (nr_pages == 0) { if (whence == SEEK_DATA) break; BUG_ON(whence != SEEK_HOLE); /* * If this is the first time to go into the loop and * offset is not beyond the end offset, it will be a * hole at this offset */ if (lastoff == startoff || lastoff < endoff) found = 1; break; } /* * If this is the first time to go into the loop and * offset is smaller than the first page offset, it will be a * hole at this offset. */ if (lastoff == startoff && whence == SEEK_HOLE && lastoff < page_offset(pvec.pages[0])) { found = 1; break; } for (i = 0; i < nr_pages; i++) { struct page *page = pvec.pages[i]; struct buffer_head *bh, *head; /* * If the current offset is not beyond the end of given * range, it will be a hole. */ if (lastoff < endoff && whence == SEEK_HOLE && page->index > end) { found = 1; *offset = lastoff; goto out; } lock_page(page); if (unlikely(page->mapping != inode->i_mapping)) { unlock_page(page); continue; } if (!page_has_buffers(page)) { unlock_page(page); continue; } if (page_has_buffers(page)) { lastoff = page_offset(page); bh = head = page_buffers(page); do { if (buffer_uptodate(bh) || buffer_unwritten(bh)) { if (whence == SEEK_DATA) found = 1; } else { if (whence == SEEK_HOLE) found = 1; } if (found) { *offset = max_t(loff_t, startoff, lastoff); unlock_page(page); goto out; } lastoff += bh->b_size; bh = bh->b_this_page; } while (bh != head); } lastoff = page_offset(page) + PAGE_SIZE; unlock_page(page); } /* * The no. of pages is less than our desired, that would be a * hole in there. */ if (nr_pages < num && whence == SEEK_HOLE) { found = 1; *offset = lastoff; break; } index = pvec.pages[i - 1]->index + 1; pagevec_release(&pvec); } while (index <= end); out: pagevec_release(&pvec); return found; } /* * ext4_seek_data() retrieves the offset for SEEK_DATA. */ static loff_t ext4_seek_data(struct file *file, loff_t offset, loff_t maxsize) { struct inode *inode = file->f_mapping->host; struct ext4_map_blocks map; struct extent_status es; ext4_lblk_t start, last, end; loff_t dataoff, isize; int blkbits; int ret = 0; mutex_lock(&inode->i_mutex); isize = i_size_read(inode); if (offset >= isize) { mutex_unlock(&inode->i_mutex); return -ENXIO; } blkbits = inode->i_sb->s_blocksize_bits; start = offset >> blkbits; last = start; end = isize >> blkbits; dataoff = offset; do { map.m_lblk = last; map.m_len = end - last + 1; ret = ext4_map_blocks(NULL, inode, &map, 0); if (ret > 0 && !(map.m_flags & EXT4_MAP_UNWRITTEN)) { if (last != start) dataoff = (loff_t)last << blkbits; break; } /* * If there is a delay extent at this offset, * it will be as a data. */ ext4_es_find_delayed_extent_range(inode, last, last, &es); if (es.es_len != 0 && in_range(last, es.es_lblk, es.es_len)) { if (last != start) dataoff = (loff_t)last << blkbits; break; } /* * If there is a unwritten extent at this offset, * it will be as a data or a hole according to page * cache that has data or not. */ if (map.m_flags & EXT4_MAP_UNWRITTEN) { int unwritten; unwritten = ext4_find_unwritten_pgoff(inode, SEEK_DATA, &map, &dataoff); if (unwritten) break; } last++; dataoff = (loff_t)last << blkbits; } while (last <= end); mutex_unlock(&inode->i_mutex); if (dataoff > isize) return -ENXIO; return vfs_setpos(file, dataoff, maxsize); } /* * ext4_seek_hole() retrieves the offset for SEEK_HOLE. */ static loff_t ext4_seek_hole(struct file *file, loff_t offset, loff_t maxsize) { struct inode *inode = file->f_mapping->host; struct ext4_map_blocks map; struct extent_status es; ext4_lblk_t start, last, end; loff_t holeoff, isize; int blkbits; int ret = 0; mutex_lock(&inode->i_mutex); isize = i_size_read(inode); if (offset >= isize) { mutex_unlock(&inode->i_mutex); return -ENXIO; } blkbits = inode->i_sb->s_blocksize_bits; start = offset >> blkbits; last = start; end = isize >> blkbits; holeoff = offset; do { map.m_lblk = last; map.m_len = end - last + 1; ret = ext4_map_blocks(NULL, inode, &map, 0); if (ret > 0 && !(map.m_flags & EXT4_MAP_UNWRITTEN)) { last += ret; holeoff = (loff_t)last << blkbits; continue; } /* * If there is a delay extent at this offset, * we will skip this extent. */ ext4_es_find_delayed_extent_range(inode, last, last, &es); if (es.es_len != 0 && in_range(last, es.es_lblk, es.es_len)) { last = es.es_lblk + es.es_len; holeoff = (loff_t)last << blkbits; continue; } /* * If there is a unwritten extent at this offset, * it will be as a data or a hole according to page * cache that has data or not. */ if (map.m_flags & EXT4_MAP_UNWRITTEN) { int unwritten; unwritten = ext4_find_unwritten_pgoff(inode, SEEK_HOLE, &map, &holeoff); if (!unwritten) { last += ret; holeoff = (loff_t)last << blkbits; continue; } } /* find a hole */ break; } while (last <= end); mutex_unlock(&inode->i_mutex); if (holeoff > isize) holeoff = isize; return vfs_setpos(file, holeoff, maxsize); } /* * ext4_llseek() handles both block-mapped and extent-mapped maxbytes values * by calling generic_file_llseek_size() with the appropriate maxbytes * value for each. */ loff_t ext4_llseek(struct file *file, loff_t offset, int whence) { struct inode *inode = file->f_mapping->host; loff_t maxbytes; if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) maxbytes = EXT4_SB(inode->i_sb)->s_bitmap_maxbytes; else maxbytes = inode->i_sb->s_maxbytes; switch (whence) { case SEEK_SET: case SEEK_CUR: case SEEK_END: return generic_file_llseek_size(file, offset, whence, maxbytes, i_size_read(inode)); case SEEK_DATA: return ext4_seek_data(file, offset, maxbytes); case SEEK_HOLE: return ext4_seek_hole(file, offset, maxbytes); } return -EINVAL; } const struct file_operations ext4_file_operations = { .llseek = ext4_llseek, .read = new_sync_read, .write = new_sync_write, .read_iter = generic_file_read_iter, .write_iter = ext4_file_write_iter, .unlocked_ioctl = ext4_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = ext4_compat_ioctl, #endif .mmap = ext4_file_mmap, .open = ext4_file_open, .release = ext4_release_file, .fsync = ext4_sync_file, .splice_read = generic_file_splice_read, .splice_write = generic_file_splice_write, .fallocate = ext4_fallocate, }; const struct inode_operations ext4_file_inode_operations = { .setattr = ext4_setattr, .getattr = ext4_getattr, .setxattr = generic_setxattr, .getxattr = generic_getxattr, .listxattr = ext4_listxattr, .removexattr = generic_removexattr, .get_acl = ext4_get_acl, .set_acl = ext4_set_acl, .fiemap = ext4_fiemap, };
./CrossVul/dataset_final_sorted/CWE-264/c/bad_2287_4
crossvul-cpp_data_bad_2123_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-264/c/bad_2123_0
crossvul-cpp_data_bad_4821_1
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ /*** This file is part of systemd. Copyright 2010 Lennart Poettering systemd 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. systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>. ***/ #include <errno.h> #include "alloc-util.h" #include "bus-error.h" #include "bus-util.h" #include "dbus-timer.h" #include "fs-util.h" #include "parse-util.h" #include "special.h" #include "string-table.h" #include "string-util.h" #include "timer.h" #include "unit-name.h" #include "unit.h" #include "user-util.h" #include "virt.h" static const UnitActiveState state_translation_table[_TIMER_STATE_MAX] = { [TIMER_DEAD] = UNIT_INACTIVE, [TIMER_WAITING] = UNIT_ACTIVE, [TIMER_RUNNING] = UNIT_ACTIVE, [TIMER_ELAPSED] = UNIT_ACTIVE, [TIMER_FAILED] = UNIT_FAILED }; static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata); static void timer_init(Unit *u) { Timer *t = TIMER(u); assert(u); assert(u->load_state == UNIT_STUB); t->next_elapse_monotonic_or_boottime = USEC_INFINITY; t->next_elapse_realtime = USEC_INFINITY; t->accuracy_usec = u->manager->default_timer_accuracy_usec; } void timer_free_values(Timer *t) { TimerValue *v; assert(t); while ((v = t->values)) { LIST_REMOVE(value, t->values, v); calendar_spec_free(v->calendar_spec); free(v); } } static void timer_done(Unit *u) { Timer *t = TIMER(u); assert(t); timer_free_values(t); t->monotonic_event_source = sd_event_source_unref(t->monotonic_event_source); t->realtime_event_source = sd_event_source_unref(t->realtime_event_source); free(t->stamp_path); } static int timer_verify(Timer *t) { assert(t); if (UNIT(t)->load_state != UNIT_LOADED) return 0; if (!t->values) { log_unit_error(UNIT(t), "Timer unit lacks value setting. Refusing."); return -EINVAL; } return 0; } static int timer_add_default_dependencies(Timer *t) { int r; TimerValue *v; assert(t); if (!UNIT(t)->default_dependencies) return 0; r = unit_add_dependency_by_name(UNIT(t), UNIT_BEFORE, SPECIAL_TIMERS_TARGET, NULL, true); if (r < 0) return r; if (UNIT(t)->manager->running_as == MANAGER_SYSTEM) { r = unit_add_two_dependencies_by_name(UNIT(t), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true); if (r < 0) return r; LIST_FOREACH(value, v, t->values) { if (v->base == TIMER_CALENDAR) { r = unit_add_dependency_by_name(UNIT(t), UNIT_AFTER, SPECIAL_TIME_SYNC_TARGET, NULL, true); if (r < 0) return r; break; } } } return unit_add_two_dependencies_by_name(UNIT(t), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true); } static int timer_setup_persistent(Timer *t) { int r; assert(t); if (!t->persistent) return 0; if (UNIT(t)->manager->running_as == MANAGER_SYSTEM) { r = unit_require_mounts_for(UNIT(t), "/var/lib/systemd/timers"); if (r < 0) return r; t->stamp_path = strappend("/var/lib/systemd/timers/stamp-", UNIT(t)->id); } else { const char *e; e = getenv("XDG_DATA_HOME"); if (e) t->stamp_path = strjoin(e, "/systemd/timers/stamp-", UNIT(t)->id, NULL); else { _cleanup_free_ char *h = NULL; r = get_home_dir(&h); if (r < 0) return log_unit_error_errno(UNIT(t), r, "Failed to determine home directory: %m"); t->stamp_path = strjoin(h, "/.local/share/systemd/timers/stamp-", UNIT(t)->id, NULL); } } if (!t->stamp_path) return log_oom(); return 0; } static int timer_load(Unit *u) { Timer *t = TIMER(u); int r; assert(u); assert(u->load_state == UNIT_STUB); r = unit_load_fragment_and_dropin(u); if (r < 0) return r; if (u->load_state == UNIT_LOADED) { if (set_isempty(u->dependencies[UNIT_TRIGGERS])) { Unit *x; r = unit_load_related_unit(u, ".service", &x); if (r < 0) return r; r = unit_add_two_dependencies(u, UNIT_BEFORE, UNIT_TRIGGERS, x, true); if (r < 0) return r; } r = timer_setup_persistent(t); if (r < 0) return r; r = timer_add_default_dependencies(t); if (r < 0) return r; } return timer_verify(t); } static void timer_dump(Unit *u, FILE *f, const char *prefix) { char buf[FORMAT_TIMESPAN_MAX]; Timer *t = TIMER(u); Unit *trigger; TimerValue *v; trigger = UNIT_TRIGGER(u); fprintf(f, "%sTimer State: %s\n" "%sResult: %s\n" "%sUnit: %s\n" "%sPersistent: %s\n" "%sWakeSystem: %s\n" "%sAccuracy: %s\n", prefix, timer_state_to_string(t->state), prefix, timer_result_to_string(t->result), prefix, trigger ? trigger->id : "n/a", prefix, yes_no(t->persistent), prefix, yes_no(t->wake_system), prefix, format_timespan(buf, sizeof(buf), t->accuracy_usec, 1)); LIST_FOREACH(value, v, t->values) { if (v->base == TIMER_CALENDAR) { _cleanup_free_ char *p = NULL; calendar_spec_to_string(v->calendar_spec, &p); fprintf(f, "%s%s: %s\n", prefix, timer_base_to_string(v->base), strna(p)); } else { char timespan1[FORMAT_TIMESPAN_MAX]; fprintf(f, "%s%s: %s\n", prefix, timer_base_to_string(v->base), format_timespan(timespan1, sizeof(timespan1), v->value, 0)); } } } static void timer_set_state(Timer *t, TimerState state) { TimerState old_state; assert(t); old_state = t->state; t->state = state; if (state != TIMER_WAITING) { t->monotonic_event_source = sd_event_source_unref(t->monotonic_event_source); t->realtime_event_source = sd_event_source_unref(t->realtime_event_source); } if (state != old_state) log_unit_debug(UNIT(t), "Changed %s -> %s", timer_state_to_string(old_state), timer_state_to_string(state)); unit_notify(UNIT(t), state_translation_table[old_state], state_translation_table[state], true); } static void timer_enter_waiting(Timer *t, bool initial); static int timer_coldplug(Unit *u) { Timer *t = TIMER(u); assert(t); assert(t->state == TIMER_DEAD); if (t->deserialized_state != t->state) { if (t->deserialized_state == TIMER_WAITING) timer_enter_waiting(t, false); else timer_set_state(t, t->deserialized_state); } return 0; } static void timer_enter_dead(Timer *t, TimerResult f) { assert(t); if (f != TIMER_SUCCESS) t->result = f; timer_set_state(t, t->result != TIMER_SUCCESS ? TIMER_FAILED : TIMER_DEAD); } static usec_t monotonic_to_boottime(usec_t t) { usec_t a, b; if (t <= 0) return 0; a = now(CLOCK_BOOTTIME); b = now(CLOCK_MONOTONIC); if (t + a > b) return t + a - b; else return 0; } static void timer_enter_waiting(Timer *t, bool initial) { bool found_monotonic = false, found_realtime = false; usec_t ts_realtime, ts_monotonic; usec_t base = 0; TimerValue *v; int r; /* If we shall wake the system we use the boottime clock * rather than the monotonic clock. */ ts_realtime = now(CLOCK_REALTIME); ts_monotonic = now(t->wake_system ? CLOCK_BOOTTIME : CLOCK_MONOTONIC); t->next_elapse_monotonic_or_boottime = t->next_elapse_realtime = 0; LIST_FOREACH(value, v, t->values) { if (v->disabled) continue; if (v->base == TIMER_CALENDAR) { usec_t b; /* If we know the last time this was * triggered, schedule the job based relative * to that. If we don't just start from * now. */ b = t->last_trigger.realtime > 0 ? t->last_trigger.realtime : ts_realtime; r = calendar_spec_next_usec(v->calendar_spec, b, &v->next_elapse); if (r < 0) continue; if (!found_realtime) t->next_elapse_realtime = v->next_elapse; else t->next_elapse_realtime = MIN(t->next_elapse_realtime, v->next_elapse); found_realtime = true; } else { switch (v->base) { case TIMER_ACTIVE: if (state_translation_table[t->state] == UNIT_ACTIVE) base = UNIT(t)->inactive_exit_timestamp.monotonic; else base = ts_monotonic; break; case TIMER_BOOT: if (detect_container() <= 0) { /* CLOCK_MONOTONIC equals the uptime on Linux */ base = 0; break; } /* In a container we don't want to include the time the host * was already up when the container started, so count from * our own startup. Fall through. */ case TIMER_STARTUP: base = UNIT(t)->manager->userspace_timestamp.monotonic; break; case TIMER_UNIT_ACTIVE: base = UNIT_TRIGGER(UNIT(t))->inactive_exit_timestamp.monotonic; if (base <= 0) base = t->last_trigger.monotonic; if (base <= 0) continue; break; case TIMER_UNIT_INACTIVE: base = UNIT_TRIGGER(UNIT(t))->inactive_enter_timestamp.monotonic; if (base <= 0) base = t->last_trigger.monotonic; if (base <= 0) continue; break; default: assert_not_reached("Unknown timer base"); } if (t->wake_system) base = monotonic_to_boottime(base); v->next_elapse = base + v->value; if (!initial && v->next_elapse < ts_monotonic && IN_SET(v->base, TIMER_ACTIVE, TIMER_BOOT, TIMER_STARTUP)) { /* This is a one time trigger, disable it now */ v->disabled = true; continue; } if (!found_monotonic) t->next_elapse_monotonic_or_boottime = v->next_elapse; else t->next_elapse_monotonic_or_boottime = MIN(t->next_elapse_monotonic_or_boottime, v->next_elapse); found_monotonic = true; } } if (!found_monotonic && !found_realtime) { log_unit_debug(UNIT(t), "Timer is elapsed."); timer_set_state(t, TIMER_ELAPSED); return; } if (found_monotonic) { char buf[FORMAT_TIMESPAN_MAX]; log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", format_timespan(buf, sizeof(buf), t->next_elapse_monotonic_or_boottime > ts_monotonic ? t->next_elapse_monotonic_or_boottime - ts_monotonic : 0, 0)); if (t->monotonic_event_source) { r = sd_event_source_set_time(t->monotonic_event_source, t->next_elapse_monotonic_or_boottime); if (r < 0) goto fail; r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_ONESHOT); if (r < 0) goto fail; } else { r = sd_event_add_time( UNIT(t)->manager->event, &t->monotonic_event_source, t->wake_system ? CLOCK_BOOTTIME_ALARM : CLOCK_MONOTONIC, t->next_elapse_monotonic_or_boottime, t->accuracy_usec, timer_dispatch, t); if (r < 0) goto fail; (void) sd_event_source_set_description(t->monotonic_event_source, "timer-monotonic"); } } else if (t->monotonic_event_source) { r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_OFF); if (r < 0) goto fail; } if (found_realtime) { char buf[FORMAT_TIMESTAMP_MAX]; log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", format_timestamp(buf, sizeof(buf), t->next_elapse_realtime)); if (t->realtime_event_source) { r = sd_event_source_set_time(t->realtime_event_source, t->next_elapse_realtime); if (r < 0) goto fail; r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_ONESHOT); if (r < 0) goto fail; } else { r = sd_event_add_time( UNIT(t)->manager->event, &t->realtime_event_source, t->wake_system ? CLOCK_REALTIME_ALARM : CLOCK_REALTIME, t->next_elapse_realtime, t->accuracy_usec, timer_dispatch, t); if (r < 0) goto fail; (void) sd_event_source_set_description(t->realtime_event_source, "timer-realtime"); } } else if (t->realtime_event_source) { r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_OFF); if (r < 0) goto fail; } timer_set_state(t, TIMER_WAITING); return; fail: log_unit_warning_errno(UNIT(t), r, "Failed to enter waiting state: %m"); timer_enter_dead(t, TIMER_FAILURE_RESOURCES); } static void timer_enter_running(Timer *t) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; int r; assert(t); /* Don't start job if we are supposed to go down */ if (unit_stop_pending(UNIT(t))) return; r = manager_add_job(UNIT(t)->manager, JOB_START, UNIT_TRIGGER(UNIT(t)), JOB_REPLACE, true, &error, NULL); if (r < 0) goto fail; dual_timestamp_get(&t->last_trigger); if (t->stamp_path) touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, 0); timer_set_state(t, TIMER_RUNNING); return; fail: log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r)); timer_enter_dead(t, TIMER_FAILURE_RESOURCES); } static int timer_start(Unit *u) { Timer *t = TIMER(u); TimerValue *v; assert(t); assert(t->state == TIMER_DEAD || t->state == TIMER_FAILED); if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED) return -ENOENT; t->last_trigger = DUAL_TIMESTAMP_NULL; /* Reenable all timers that depend on unit activation time */ LIST_FOREACH(value, v, t->values) if (v->base == TIMER_ACTIVE) v->disabled = false; if (t->stamp_path) { struct stat st; if (stat(t->stamp_path, &st) >= 0) t->last_trigger.realtime = timespec_load(&st.st_atim); else if (errno == ENOENT) /* The timer has never run before, * make sure a stamp file exists. */ touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, 0); } t->result = TIMER_SUCCESS; timer_enter_waiting(t, true); return 1; } static int timer_stop(Unit *u) { Timer *t = TIMER(u); assert(t); assert(t->state == TIMER_WAITING || t->state == TIMER_RUNNING || t->state == TIMER_ELAPSED); timer_enter_dead(t, TIMER_SUCCESS); return 1; } static int timer_serialize(Unit *u, FILE *f, FDSet *fds) { Timer *t = TIMER(u); assert(u); assert(f); assert(fds); unit_serialize_item(u, f, "state", timer_state_to_string(t->state)); unit_serialize_item(u, f, "result", timer_result_to_string(t->result)); if (t->last_trigger.realtime > 0) unit_serialize_item_format(u, f, "last-trigger-realtime", "%" PRIu64, t->last_trigger.realtime); if (t->last_trigger.monotonic > 0) unit_serialize_item_format(u, f, "last-trigger-monotonic", "%" PRIu64, t->last_trigger.monotonic); return 0; } static int timer_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) { Timer *t = TIMER(u); int r; assert(u); assert(key); assert(value); assert(fds); if (streq(key, "state")) { TimerState state; state = timer_state_from_string(value); if (state < 0) log_unit_debug(u, "Failed to parse state value: %s", value); else t->deserialized_state = state; } else if (streq(key, "result")) { TimerResult f; f = timer_result_from_string(value); if (f < 0) log_unit_debug(u, "Failed to parse result value: %s", value); else if (f != TIMER_SUCCESS) t->result = f; } else if (streq(key, "last-trigger-realtime")) { r = safe_atou64(value, &t->last_trigger.realtime); if (r < 0) log_unit_debug(u, "Failed to parse last-trigger-realtime value: %s", value); } else if (streq(key, "last-trigger-monotonic")) { r = safe_atou64(value, &t->last_trigger.monotonic); if (r < 0) log_unit_debug(u, "Failed to parse last-trigger-monotonic value: %s", value); } else log_unit_debug(u, "Unknown serialization key: %s", key); return 0; } _pure_ static UnitActiveState timer_active_state(Unit *u) { assert(u); return state_translation_table[TIMER(u)->state]; } _pure_ static const char *timer_sub_state_to_string(Unit *u) { assert(u); return timer_state_to_string(TIMER(u)->state); } static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata) { Timer *t = TIMER(userdata); assert(t); if (t->state != TIMER_WAITING) return 0; log_unit_debug(UNIT(t), "Timer elapsed."); timer_enter_running(t); return 0; } static void timer_trigger_notify(Unit *u, Unit *other) { Timer *t = TIMER(u); TimerValue *v; assert(u); assert(other); if (other->load_state != UNIT_LOADED) return; /* Reenable all timers that depend on unit state */ LIST_FOREACH(value, v, t->values) if (v->base == TIMER_UNIT_ACTIVE || v->base == TIMER_UNIT_INACTIVE) v->disabled = false; switch (t->state) { case TIMER_WAITING: case TIMER_ELAPSED: /* Recalculate sleep time */ timer_enter_waiting(t, false); break; case TIMER_RUNNING: if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) { log_unit_debug(UNIT(t), "Got notified about unit deactivation."); timer_enter_waiting(t, false); } break; case TIMER_DEAD: case TIMER_FAILED: break; default: assert_not_reached("Unknown timer state"); } } static void timer_reset_failed(Unit *u) { Timer *t = TIMER(u); assert(t); if (t->state == TIMER_FAILED) timer_set_state(t, TIMER_DEAD); t->result = TIMER_SUCCESS; } static void timer_time_change(Unit *u) { Timer *t = TIMER(u); assert(u); if (t->state != TIMER_WAITING) return; log_unit_debug(u, "Time change, recalculating next elapse."); timer_enter_waiting(t, false); } static const char* const timer_base_table[_TIMER_BASE_MAX] = { [TIMER_ACTIVE] = "OnActiveSec", [TIMER_BOOT] = "OnBootSec", [TIMER_STARTUP] = "OnStartupSec", [TIMER_UNIT_ACTIVE] = "OnUnitActiveSec", [TIMER_UNIT_INACTIVE] = "OnUnitInactiveSec", [TIMER_CALENDAR] = "OnCalendar" }; DEFINE_STRING_TABLE_LOOKUP(timer_base, TimerBase); static const char* const timer_result_table[_TIMER_RESULT_MAX] = { [TIMER_SUCCESS] = "success", [TIMER_FAILURE_RESOURCES] = "resources" }; DEFINE_STRING_TABLE_LOOKUP(timer_result, TimerResult); const UnitVTable timer_vtable = { .object_size = sizeof(Timer), .sections = "Unit\0" "Timer\0" "Install\0", .private_section = "Timer", .init = timer_init, .done = timer_done, .load = timer_load, .coldplug = timer_coldplug, .dump = timer_dump, .start = timer_start, .stop = timer_stop, .serialize = timer_serialize, .deserialize_item = timer_deserialize_item, .active_state = timer_active_state, .sub_state_to_string = timer_sub_state_to_string, .trigger_notify = timer_trigger_notify, .reset_failed = timer_reset_failed, .time_change = timer_time_change, .bus_vtable = bus_timer_vtable, .bus_set_property = bus_timer_set_property, .can_transient = true, };
./CrossVul/dataset_final_sorted/CWE-264/c/bad_4821_1
crossvul-cpp_data_bad_1531_0
/* * NET An implementation of the SOCKET network access protocol. * * Version: @(#)socket.c 1.1.93 18/02/95 * * Authors: Orest Zborowski, <obz@Kodak.COM> * Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * * Fixes: * Anonymous : NOTSOCK/BADF cleanup. Error fix in * shutdown() * Alan Cox : verify_area() fixes * Alan Cox : Removed DDI * Jonathan Kamens : SOCK_DGRAM reconnect bug * Alan Cox : Moved a load of checks to the very * top level. * Alan Cox : Move address structures to/from user * mode above the protocol layers. * Rob Janssen : Allow 0 length sends. * Alan Cox : Asynchronous I/O support (cribbed from the * tty drivers). * Niibe Yutaka : Asynchronous I/O for writes (4.4BSD style) * Jeff Uphoff : Made max number of sockets command-line * configurable. * Matti Aarnio : Made the number of sockets dynamic, * to be allocated when needed, and mr. * Uphoff's max is used as max to be * allowed to allocate. * Linus : Argh. removed all the socket allocation * altogether: it's in the inode now. * Alan Cox : Made sock_alloc()/sock_release() public * for NetROM and future kernel nfsd type * stuff. * Alan Cox : sendmsg/recvmsg basics. * Tom Dyas : Export net symbols. * Marcin Dalecki : Fixed problems with CONFIG_NET="n". * Alan Cox : Added thread locking to sys_* calls * for sockets. May have errors at the * moment. * Kevin Buhr : Fixed the dumb errors in the above. * Andi Kleen : Some small cleanups, optimizations, * and fixed a copy_from_user() bug. * Tigran Aivazian : sys_send(args) calls sys_sendto(args, NULL, 0) * Tigran Aivazian : Made listen(2) backlog sanity checks * protocol-independent * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * * This module is effectively the top level interface to the BSD socket * paradigm. * * Based upon Swansea University Computer Society NET3.039 */ #include <linux/mm.h> #include <linux/socket.h> #include <linux/file.h> #include <linux/net.h> #include <linux/interrupt.h> #include <linux/thread_info.h> #include <linux/rcupdate.h> #include <linux/netdevice.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/mutex.h> #include <linux/if_bridge.h> #include <linux/if_frad.h> #include <linux/if_vlan.h> #include <linux/ptp_classify.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/cache.h> #include <linux/module.h> #include <linux/highmem.h> #include <linux/mount.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/compat.h> #include <linux/kmod.h> #include <linux/audit.h> #include <linux/wireless.h> #include <linux/nsproxy.h> #include <linux/magic.h> #include <linux/slab.h> #include <linux/xattr.h> #include <asm/uaccess.h> #include <asm/unistd.h> #include <net/compat.h> #include <net/wext.h> #include <net/cls_cgroup.h> #include <net/sock.h> #include <linux/netfilter.h> #include <linux/if_tun.h> #include <linux/ipv6_route.h> #include <linux/route.h> #include <linux/sockios.h> #include <linux/atalk.h> #include <net/busy_poll.h> #include <linux/errqueue.h> #ifdef CONFIG_NET_RX_BUSY_POLL unsigned int sysctl_net_busy_read __read_mostly; unsigned int sysctl_net_busy_poll __read_mostly; #endif static ssize_t sock_read_iter(struct kiocb *iocb, struct iov_iter *to); static ssize_t sock_write_iter(struct kiocb *iocb, struct iov_iter *from); static int sock_mmap(struct file *file, struct vm_area_struct *vma); static int sock_close(struct inode *inode, struct file *file); static unsigned int sock_poll(struct file *file, struct poll_table_struct *wait); static long sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg); #ifdef CONFIG_COMPAT static long compat_sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg); #endif static int sock_fasync(int fd, struct file *filp, int on); static ssize_t sock_sendpage(struct file *file, struct page *page, int offset, size_t size, loff_t *ppos, int more); static ssize_t sock_splice_read(struct file *file, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags); /* * Socket files have a set of 'special' operations as well as the generic file ones. These don't appear * in the operation structures but are done directly via the socketcall() multiplexor. */ static const struct file_operations socket_file_ops = { .owner = THIS_MODULE, .llseek = no_llseek, .read = new_sync_read, .write = new_sync_write, .read_iter = sock_read_iter, .write_iter = sock_write_iter, .poll = sock_poll, .unlocked_ioctl = sock_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = compat_sock_ioctl, #endif .mmap = sock_mmap, .release = sock_close, .fasync = sock_fasync, .sendpage = sock_sendpage, .splice_write = generic_splice_sendpage, .splice_read = sock_splice_read, }; /* * The protocol list. Each protocol is registered in here. */ static DEFINE_SPINLOCK(net_family_lock); static const struct net_proto_family __rcu *net_families[NPROTO] __read_mostly; /* * Statistics counters of the socket lists */ static DEFINE_PER_CPU(int, sockets_in_use); /* * Support routines. * Move socket addresses back and forth across the kernel/user * divide and look after the messy bits. */ /** * move_addr_to_kernel - copy a socket address into kernel space * @uaddr: Address in user space * @kaddr: Address in kernel space * @ulen: Length in user space * * The address is copied into kernel space. If the provided address is * too long an error code of -EINVAL is returned. If the copy gives * invalid addresses -EFAULT is returned. On a success 0 is returned. */ int move_addr_to_kernel(void __user *uaddr, int ulen, struct sockaddr_storage *kaddr) { if (ulen < 0 || ulen > sizeof(struct sockaddr_storage)) return -EINVAL; if (ulen == 0) return 0; if (copy_from_user(kaddr, uaddr, ulen)) return -EFAULT; return audit_sockaddr(ulen, kaddr); } /** * move_addr_to_user - copy an address to user space * @kaddr: kernel space address * @klen: length of address in kernel * @uaddr: user space address * @ulen: pointer to user length field * * The value pointed to by ulen on entry is the buffer length available. * This is overwritten with the buffer space used. -EINVAL is returned * if an overlong buffer is specified or a negative buffer size. -EFAULT * is returned if either the buffer or the length field are not * accessible. * After copying the data up to the limit the user specifies, the true * length of the data is written over the length limit the user * specified. Zero is returned for a success. */ static int move_addr_to_user(struct sockaddr_storage *kaddr, int klen, void __user *uaddr, int __user *ulen) { int err; int len; BUG_ON(klen > sizeof(struct sockaddr_storage)); err = get_user(len, ulen); if (err) return err; if (len > klen) len = klen; if (len < 0) return -EINVAL; if (len) { if (audit_sockaddr(klen, kaddr)) return -ENOMEM; if (copy_to_user(uaddr, kaddr, len)) return -EFAULT; } /* * "fromlen shall refer to the value before truncation.." * 1003.1g */ return __put_user(klen, ulen); } static struct kmem_cache *sock_inode_cachep __read_mostly; static struct inode *sock_alloc_inode(struct super_block *sb) { struct socket_alloc *ei; struct socket_wq *wq; ei = kmem_cache_alloc(sock_inode_cachep, GFP_KERNEL); if (!ei) return NULL; wq = kmalloc(sizeof(*wq), GFP_KERNEL); if (!wq) { kmem_cache_free(sock_inode_cachep, ei); return NULL; } init_waitqueue_head(&wq->wait); wq->fasync_list = NULL; RCU_INIT_POINTER(ei->socket.wq, wq); ei->socket.state = SS_UNCONNECTED; ei->socket.flags = 0; ei->socket.ops = NULL; ei->socket.sk = NULL; ei->socket.file = NULL; return &ei->vfs_inode; } static void sock_destroy_inode(struct inode *inode) { struct socket_alloc *ei; struct socket_wq *wq; ei = container_of(inode, struct socket_alloc, vfs_inode); wq = rcu_dereference_protected(ei->socket.wq, 1); kfree_rcu(wq, rcu); kmem_cache_free(sock_inode_cachep, ei); } static void init_once(void *foo) { struct socket_alloc *ei = (struct socket_alloc *)foo; inode_init_once(&ei->vfs_inode); } static int init_inodecache(void) { sock_inode_cachep = kmem_cache_create("sock_inode_cache", sizeof(struct socket_alloc), 0, (SLAB_HWCACHE_ALIGN | SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD), init_once); if (sock_inode_cachep == NULL) return -ENOMEM; return 0; } static const struct super_operations sockfs_ops = { .alloc_inode = sock_alloc_inode, .destroy_inode = sock_destroy_inode, .statfs = simple_statfs, }; /* * sockfs_dname() is called from d_path(). */ static char *sockfs_dname(struct dentry *dentry, char *buffer, int buflen) { return dynamic_dname(dentry, buffer, buflen, "socket:[%lu]", dentry->d_inode->i_ino); } static const struct dentry_operations sockfs_dentry_operations = { .d_dname = sockfs_dname, }; static struct dentry *sockfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_pseudo(fs_type, "socket:", &sockfs_ops, &sockfs_dentry_operations, SOCKFS_MAGIC); } static struct vfsmount *sock_mnt __read_mostly; static struct file_system_type sock_fs_type = { .name = "sockfs", .mount = sockfs_mount, .kill_sb = kill_anon_super, }; /* * Obtains the first available file descriptor and sets it up for use. * * These functions create file structures and maps them to fd space * of the current process. On success it returns file descriptor * and file struct implicitly stored in sock->file. * Note that another thread may close file descriptor before we return * from this function. We use the fact that now we do not refer * to socket after mapping. If one day we will need it, this * function will increment ref. count on file by 1. * * In any case returned fd MAY BE not valid! * This race condition is unavoidable * with shared fd spaces, we cannot solve it inside kernel, * but we take care of internal coherence yet. */ struct file *sock_alloc_file(struct socket *sock, int flags, const char *dname) { struct qstr name = { .name = "" }; struct path path; struct file *file; if (dname) { name.name = dname; name.len = strlen(name.name); } else if (sock->sk) { name.name = sock->sk->sk_prot_creator->name; name.len = strlen(name.name); } path.dentry = d_alloc_pseudo(sock_mnt->mnt_sb, &name); if (unlikely(!path.dentry)) return ERR_PTR(-ENOMEM); path.mnt = mntget(sock_mnt); d_instantiate(path.dentry, SOCK_INODE(sock)); file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &socket_file_ops); if (unlikely(IS_ERR(file))) { /* drop dentry, keep inode */ ihold(path.dentry->d_inode); path_put(&path); return file; } sock->file = file; file->f_flags = O_RDWR | (flags & O_NONBLOCK); file->private_data = sock; return file; } EXPORT_SYMBOL(sock_alloc_file); static int sock_map_fd(struct socket *sock, int flags) { struct file *newfile; int fd = get_unused_fd_flags(flags); if (unlikely(fd < 0)) return fd; newfile = sock_alloc_file(sock, flags, NULL); if (likely(!IS_ERR(newfile))) { fd_install(fd, newfile); return fd; } put_unused_fd(fd); return PTR_ERR(newfile); } struct socket *sock_from_file(struct file *file, int *err) { if (file->f_op == &socket_file_ops) return file->private_data; /* set in sock_map_fd */ *err = -ENOTSOCK; return NULL; } EXPORT_SYMBOL(sock_from_file); /** * sockfd_lookup - Go from a file number to its socket slot * @fd: file handle * @err: pointer to an error code return * * The file handle passed in is locked and the socket it is bound * too is returned. If an error occurs the err pointer is overwritten * with a negative errno code and NULL is returned. The function checks * for both invalid handles and passing a handle which is not a socket. * * On a success the socket object pointer is returned. */ struct socket *sockfd_lookup(int fd, int *err) { struct file *file; struct socket *sock; file = fget(fd); if (!file) { *err = -EBADF; return NULL; } sock = sock_from_file(file, err); if (!sock) fput(file); return sock; } EXPORT_SYMBOL(sockfd_lookup); static struct socket *sockfd_lookup_light(int fd, int *err, int *fput_needed) { struct fd f = fdget(fd); struct socket *sock; *err = -EBADF; if (f.file) { sock = sock_from_file(f.file, err); if (likely(sock)) { *fput_needed = f.flags; return sock; } fdput(f); } return NULL; } #define XATTR_SOCKPROTONAME_SUFFIX "sockprotoname" #define XATTR_NAME_SOCKPROTONAME (XATTR_SYSTEM_PREFIX XATTR_SOCKPROTONAME_SUFFIX) #define XATTR_NAME_SOCKPROTONAME_LEN (sizeof(XATTR_NAME_SOCKPROTONAME)-1) static ssize_t sockfs_getxattr(struct dentry *dentry, const char *name, void *value, size_t size) { const char *proto_name; size_t proto_size; int error; error = -ENODATA; if (!strncmp(name, XATTR_NAME_SOCKPROTONAME, XATTR_NAME_SOCKPROTONAME_LEN)) { proto_name = dentry->d_name.name; proto_size = strlen(proto_name); if (value) { error = -ERANGE; if (proto_size + 1 > size) goto out; strncpy(value, proto_name, proto_size + 1); } error = proto_size + 1; } out: return error; } static ssize_t sockfs_listxattr(struct dentry *dentry, char *buffer, size_t size) { ssize_t len; ssize_t used = 0; len = security_inode_listsecurity(dentry->d_inode, buffer, size); if (len < 0) return len; used += len; if (buffer) { if (size < used) return -ERANGE; buffer += len; } len = (XATTR_NAME_SOCKPROTONAME_LEN + 1); used += len; if (buffer) { if (size < used) return -ERANGE; memcpy(buffer, XATTR_NAME_SOCKPROTONAME, len); buffer += len; } return used; } static const struct inode_operations sockfs_inode_ops = { .getxattr = sockfs_getxattr, .listxattr = sockfs_listxattr, }; /** * sock_alloc - allocate a socket * * Allocate a new inode and socket object. The two are bound together * and initialised. The socket is then returned. If we are out of inodes * NULL is returned. */ static struct socket *sock_alloc(void) { struct inode *inode; struct socket *sock; inode = new_inode_pseudo(sock_mnt->mnt_sb); if (!inode) return NULL; sock = SOCKET_I(inode); kmemcheck_annotate_bitfield(sock, type); inode->i_ino = get_next_ino(); inode->i_mode = S_IFSOCK | S_IRWXUGO; inode->i_uid = current_fsuid(); inode->i_gid = current_fsgid(); inode->i_op = &sockfs_inode_ops; this_cpu_add(sockets_in_use, 1); return sock; } /** * sock_release - close a socket * @sock: socket to close * * The socket is released from the protocol stack if it has a release * callback, and the inode is then released if the socket is bound to * an inode not a file. */ void sock_release(struct socket *sock) { if (sock->ops) { struct module *owner = sock->ops->owner; sock->ops->release(sock); sock->ops = NULL; module_put(owner); } if (rcu_dereference_protected(sock->wq, 1)->fasync_list) pr_err("%s: fasync list not empty!\n", __func__); if (test_bit(SOCK_EXTERNALLY_ALLOCATED, &sock->flags)) return; this_cpu_sub(sockets_in_use, 1); if (!sock->file) { iput(SOCK_INODE(sock)); return; } sock->file = NULL; } EXPORT_SYMBOL(sock_release); void __sock_tx_timestamp(const struct sock *sk, __u8 *tx_flags) { u8 flags = *tx_flags; if (sk->sk_tsflags & SOF_TIMESTAMPING_TX_HARDWARE) flags |= SKBTX_HW_TSTAMP; if (sk->sk_tsflags & SOF_TIMESTAMPING_TX_SOFTWARE) flags |= SKBTX_SW_TSTAMP; if (sk->sk_tsflags & SOF_TIMESTAMPING_TX_SCHED) flags |= SKBTX_SCHED_TSTAMP; if (sk->sk_tsflags & SOF_TIMESTAMPING_TX_ACK) flags |= SKBTX_ACK_TSTAMP; *tx_flags = flags; } EXPORT_SYMBOL(__sock_tx_timestamp); static inline int __sock_sendmsg_nosec(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size) { return sock->ops->sendmsg(iocb, sock, msg, size); } static inline int __sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size) { int err = security_socket_sendmsg(sock, msg, size); return err ?: __sock_sendmsg_nosec(iocb, sock, msg, size); } static int do_sock_sendmsg(struct socket *sock, struct msghdr *msg, size_t size, bool nosec) { struct kiocb iocb; int ret; init_sync_kiocb(&iocb, NULL); ret = nosec ? __sock_sendmsg_nosec(&iocb, sock, msg, size) : __sock_sendmsg(&iocb, sock, msg, size); if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&iocb); return ret; } int sock_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) { return do_sock_sendmsg(sock, msg, size, false); } EXPORT_SYMBOL(sock_sendmsg); static int sock_sendmsg_nosec(struct socket *sock, struct msghdr *msg, size_t size) { return do_sock_sendmsg(sock, msg, size, true); } int kernel_sendmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t size) { mm_segment_t oldfs = get_fs(); int result; set_fs(KERNEL_DS); /* * the following is safe, since for compiler definitions of kvec and * iovec are identical, yielding the same in-core layout and alignment */ iov_iter_init(&msg->msg_iter, WRITE, (struct iovec *)vec, num, size); result = sock_sendmsg(sock, msg, size); set_fs(oldfs); return result; } EXPORT_SYMBOL(kernel_sendmsg); /* * called from sock_recv_timestamp() if sock_flag(sk, SOCK_RCVTSTAMP) */ void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp.tv64 == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); } EXPORT_SYMBOL_GPL(__sock_recv_timestamp); void __sock_recv_wifi_status(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int ack; if (!sock_flag(sk, SOCK_WIFI_STATUS)) return; if (!skb->wifi_acked_valid) return; ack = skb->wifi_acked; put_cmsg(msg, SOL_SOCKET, SCM_WIFI_STATUS, sizeof(ack), &ack); } EXPORT_SYMBOL_GPL(__sock_recv_wifi_status); static inline void sock_recv_drops(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { if (sock_flag(sk, SOCK_RXQ_OVFL) && skb && skb->dropcount) put_cmsg(msg, SOL_SOCKET, SO_RXQ_OVFL, sizeof(__u32), &skb->dropcount); } void __sock_recv_ts_and_drops(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { sock_recv_timestamp(msg, sk, skb); sock_recv_drops(msg, sk, skb); } EXPORT_SYMBOL_GPL(__sock_recv_ts_and_drops); static inline int __sock_recvmsg_nosec(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { return sock->ops->recvmsg(iocb, sock, msg, size, flags); } static inline int __sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { int err = security_socket_recvmsg(sock, msg, size, flags); return err ?: __sock_recvmsg_nosec(iocb, sock, msg, size, flags); } int sock_recvmsg(struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct kiocb iocb; int ret; init_sync_kiocb(&iocb, NULL); ret = __sock_recvmsg(&iocb, sock, msg, size, flags); if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&iocb); return ret; } EXPORT_SYMBOL(sock_recvmsg); static int sock_recvmsg_nosec(struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct kiocb iocb; int ret; init_sync_kiocb(&iocb, NULL); ret = __sock_recvmsg_nosec(&iocb, sock, msg, size, flags); if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&iocb); return ret; } /** * kernel_recvmsg - Receive a message from a socket (kernel space) * @sock: The socket to receive the message from * @msg: Received message * @vec: Input s/g array for message data * @num: Size of input s/g array * @size: Number of bytes to read * @flags: Message flags (MSG_DONTWAIT, etc...) * * On return the msg structure contains the scatter/gather array passed in the * vec argument. The array is modified so that it consists of the unfilled * portion of the original array. * * The returned value is the total number of bytes received, or an error. */ int kernel_recvmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t size, int flags) { mm_segment_t oldfs = get_fs(); int result; set_fs(KERNEL_DS); /* * the following is safe, since for compiler definitions of kvec and * iovec are identical, yielding the same in-core layout and alignment */ iov_iter_init(&msg->msg_iter, READ, (struct iovec *)vec, num, size); result = sock_recvmsg(sock, msg, size, flags); set_fs(oldfs); return result; } EXPORT_SYMBOL(kernel_recvmsg); static ssize_t sock_sendpage(struct file *file, struct page *page, int offset, size_t size, loff_t *ppos, int more) { struct socket *sock; int flags; sock = file->private_data; flags = (file->f_flags & O_NONBLOCK) ? MSG_DONTWAIT : 0; /* more is a combination of MSG_MORE and MSG_SENDPAGE_NOTLAST */ flags |= more; return kernel_sendpage(sock, page, offset, size, flags); } static ssize_t sock_splice_read(struct file *file, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { struct socket *sock = file->private_data; if (unlikely(!sock->ops->splice_read)) return -EINVAL; return sock->ops->splice_read(sock, ppos, pipe, len, flags); } static ssize_t sock_read_iter(struct kiocb *iocb, struct iov_iter *to) { struct file *file = iocb->ki_filp; struct socket *sock = file->private_data; struct msghdr msg = {.msg_iter = *to}; ssize_t res; if (file->f_flags & O_NONBLOCK) msg.msg_flags = MSG_DONTWAIT; if (iocb->ki_pos != 0) return -ESPIPE; if (iocb->ki_nbytes == 0) /* Match SYS5 behaviour */ return 0; res = __sock_recvmsg(iocb, sock, &msg, iocb->ki_nbytes, msg.msg_flags); *to = msg.msg_iter; return res; } static ssize_t sock_write_iter(struct kiocb *iocb, struct iov_iter *from) { struct file *file = iocb->ki_filp; struct socket *sock = file->private_data; struct msghdr msg = {.msg_iter = *from}; ssize_t res; if (iocb->ki_pos != 0) return -ESPIPE; if (file->f_flags & O_NONBLOCK) msg.msg_flags = MSG_DONTWAIT; if (sock->type == SOCK_SEQPACKET) msg.msg_flags |= MSG_EOR; res = __sock_sendmsg(iocb, sock, &msg, iocb->ki_nbytes); *from = msg.msg_iter; return res; } /* * Atomic setting of ioctl hooks to avoid race * with module unload. */ static DEFINE_MUTEX(br_ioctl_mutex); static int (*br_ioctl_hook) (struct net *, unsigned int cmd, void __user *arg); void brioctl_set(int (*hook) (struct net *, unsigned int, void __user *)) { mutex_lock(&br_ioctl_mutex); br_ioctl_hook = hook; mutex_unlock(&br_ioctl_mutex); } EXPORT_SYMBOL(brioctl_set); static DEFINE_MUTEX(vlan_ioctl_mutex); static int (*vlan_ioctl_hook) (struct net *, void __user *arg); void vlan_ioctl_set(int (*hook) (struct net *, void __user *)) { mutex_lock(&vlan_ioctl_mutex); vlan_ioctl_hook = hook; mutex_unlock(&vlan_ioctl_mutex); } EXPORT_SYMBOL(vlan_ioctl_set); static DEFINE_MUTEX(dlci_ioctl_mutex); static int (*dlci_ioctl_hook) (unsigned int, void __user *); void dlci_ioctl_set(int (*hook) (unsigned int, void __user *)) { mutex_lock(&dlci_ioctl_mutex); dlci_ioctl_hook = hook; mutex_unlock(&dlci_ioctl_mutex); } EXPORT_SYMBOL(dlci_ioctl_set); static long sock_do_ioctl(struct net *net, struct socket *sock, unsigned int cmd, unsigned long arg) { int err; void __user *argp = (void __user *)arg; err = sock->ops->ioctl(sock, cmd, arg); /* * If this ioctl is unknown try to hand it down * to the NIC driver. */ if (err == -ENOIOCTLCMD) err = dev_ioctl(net, cmd, argp); return err; } /* * With an ioctl, arg may well be a user mode pointer, but we don't know * what to do with it - that's up to the protocol still. */ static long sock_ioctl(struct file *file, unsigned cmd, unsigned long arg) { struct socket *sock; struct sock *sk; void __user *argp = (void __user *)arg; int pid, err; struct net *net; sock = file->private_data; sk = sock->sk; net = sock_net(sk); if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15)) { err = dev_ioctl(net, cmd, argp); } else #ifdef CONFIG_WEXT_CORE if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST) { err = dev_ioctl(net, cmd, argp); } else #endif switch (cmd) { case FIOSETOWN: case SIOCSPGRP: err = -EFAULT; if (get_user(pid, (int __user *)argp)) break; f_setown(sock->file, pid, 1); err = 0; break; case FIOGETOWN: case SIOCGPGRP: err = put_user(f_getown(sock->file), (int __user *)argp); break; case SIOCGIFBR: case SIOCSIFBR: case SIOCBRADDBR: case SIOCBRDELBR: err = -ENOPKG; if (!br_ioctl_hook) request_module("bridge"); mutex_lock(&br_ioctl_mutex); if (br_ioctl_hook) err = br_ioctl_hook(net, cmd, argp); mutex_unlock(&br_ioctl_mutex); break; case SIOCGIFVLAN: case SIOCSIFVLAN: err = -ENOPKG; if (!vlan_ioctl_hook) request_module("8021q"); mutex_lock(&vlan_ioctl_mutex); if (vlan_ioctl_hook) err = vlan_ioctl_hook(net, argp); mutex_unlock(&vlan_ioctl_mutex); break; case SIOCADDDLCI: case SIOCDELDLCI: err = -ENOPKG; if (!dlci_ioctl_hook) request_module("dlci"); mutex_lock(&dlci_ioctl_mutex); if (dlci_ioctl_hook) err = dlci_ioctl_hook(cmd, argp); mutex_unlock(&dlci_ioctl_mutex); break; default: err = sock_do_ioctl(net, sock, cmd, arg); break; } return err; } int sock_create_lite(int family, int type, int protocol, struct socket **res) { int err; struct socket *sock = NULL; err = security_socket_create(family, type, protocol, 1); if (err) goto out; sock = sock_alloc(); if (!sock) { err = -ENOMEM; goto out; } sock->type = type; err = security_socket_post_create(sock, family, type, protocol, 1); if (err) goto out_release; out: *res = sock; return err; out_release: sock_release(sock); sock = NULL; goto out; } EXPORT_SYMBOL(sock_create_lite); /* No kernel lock held - perfect */ static unsigned int sock_poll(struct file *file, poll_table *wait) { unsigned int busy_flag = 0; struct socket *sock; /* * We can't return errors to poll, so it's either yes or no. */ sock = file->private_data; if (sk_can_busy_loop(sock->sk)) { /* this socket can poll_ll so tell the system call */ busy_flag = POLL_BUSY_LOOP; /* once, only if requested by syscall */ if (wait && (wait->_key & POLL_BUSY_LOOP)) sk_busy_loop(sock->sk, 1); } return busy_flag | sock->ops->poll(file, sock, wait); } static int sock_mmap(struct file *file, struct vm_area_struct *vma) { struct socket *sock = file->private_data; return sock->ops->mmap(file, sock, vma); } static int sock_close(struct inode *inode, struct file *filp) { sock_release(SOCKET_I(inode)); return 0; } /* * Update the socket async list * * Fasync_list locking strategy. * * 1. fasync_list is modified only under process context socket lock * i.e. under semaphore. * 2. fasync_list is used under read_lock(&sk->sk_callback_lock) * or under socket lock */ static int sock_fasync(int fd, struct file *filp, int on) { struct socket *sock = filp->private_data; struct sock *sk = sock->sk; struct socket_wq *wq; if (sk == NULL) return -EINVAL; lock_sock(sk); wq = rcu_dereference_protected(sock->wq, sock_owned_by_user(sk)); fasync_helper(fd, filp, on, &wq->fasync_list); if (!wq->fasync_list) sock_reset_flag(sk, SOCK_FASYNC); else sock_set_flag(sk, SOCK_FASYNC); release_sock(sk); return 0; } /* This function may be called only under socket lock or callback_lock or rcu_lock */ int sock_wake_async(struct socket *sock, int how, int band) { struct socket_wq *wq; if (!sock) return -1; rcu_read_lock(); wq = rcu_dereference(sock->wq); if (!wq || !wq->fasync_list) { rcu_read_unlock(); return -1; } switch (how) { case SOCK_WAKE_WAITD: if (test_bit(SOCK_ASYNC_WAITDATA, &sock->flags)) break; goto call_kill; case SOCK_WAKE_SPACE: if (!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sock->flags)) break; /* fall through */ case SOCK_WAKE_IO: call_kill: kill_fasync(&wq->fasync_list, SIGIO, band); break; case SOCK_WAKE_URG: kill_fasync(&wq->fasync_list, SIGURG, band); } rcu_read_unlock(); return 0; } EXPORT_SYMBOL(sock_wake_async); int __sock_create(struct net *net, int family, int type, int protocol, struct socket **res, int kern) { int err; struct socket *sock; const struct net_proto_family *pf; /* * Check protocol is in range */ if (family < 0 || family >= NPROTO) return -EAFNOSUPPORT; if (type < 0 || type >= SOCK_MAX) return -EINVAL; /* Compatibility. This uglymoron is moved from INET layer to here to avoid deadlock in module load. */ if (family == PF_INET && type == SOCK_PACKET) { static int warned; if (!warned) { warned = 1; pr_info("%s uses obsolete (PF_INET,SOCK_PACKET)\n", current->comm); } family = PF_PACKET; } err = security_socket_create(family, type, protocol, kern); if (err) return err; /* * Allocate the socket and allow the family to set things up. if * the protocol is 0, the family is instructed to select an appropriate * default. */ sock = sock_alloc(); if (!sock) { net_warn_ratelimited("socket: no more sockets\n"); return -ENFILE; /* Not exactly a match, but its the closest posix thing */ } sock->type = type; #ifdef CONFIG_MODULES /* Attempt to load a protocol module if the find failed. * * 12/09/1996 Marcin: But! this makes REALLY only sense, if the user * requested real, full-featured networking support upon configuration. * Otherwise module support will break! */ if (rcu_access_pointer(net_families[family]) == NULL) request_module("net-pf-%d", family); #endif rcu_read_lock(); pf = rcu_dereference(net_families[family]); err = -EAFNOSUPPORT; if (!pf) goto out_release; /* * We will call the ->create function, that possibly is in a loadable * module, so we have to bump that loadable module refcnt first. */ if (!try_module_get(pf->owner)) goto out_release; /* Now protected by module ref count */ rcu_read_unlock(); err = pf->create(net, sock, protocol, kern); if (err < 0) goto out_module_put; /* * Now to bump the refcnt of the [loadable] module that owns this * socket at sock_release time we decrement its refcnt. */ if (!try_module_get(sock->ops->owner)) goto out_module_busy; /* * Now that we're done with the ->create function, the [loadable] * module can have its refcnt decremented */ module_put(pf->owner); err = security_socket_post_create(sock, family, type, protocol, kern); if (err) goto out_sock_release; *res = sock; return 0; out_module_busy: err = -EAFNOSUPPORT; out_module_put: sock->ops = NULL; module_put(pf->owner); out_sock_release: sock_release(sock); return err; out_release: rcu_read_unlock(); goto out_sock_release; } EXPORT_SYMBOL(__sock_create); int sock_create(int family, int type, int protocol, struct socket **res) { return __sock_create(current->nsproxy->net_ns, family, type, protocol, res, 0); } EXPORT_SYMBOL(sock_create); int sock_create_kern(int family, int type, int protocol, struct socket **res) { return __sock_create(&init_net, family, type, protocol, res, 1); } EXPORT_SYMBOL(sock_create_kern); SYSCALL_DEFINE3(socket, int, family, int, type, int, protocol) { int retval; struct socket *sock; int flags; /* Check the SOCK_* constants for consistency. */ BUILD_BUG_ON(SOCK_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON((SOCK_MAX | SOCK_TYPE_MASK) != SOCK_TYPE_MASK); BUILD_BUG_ON(SOCK_CLOEXEC & SOCK_TYPE_MASK); BUILD_BUG_ON(SOCK_NONBLOCK & SOCK_TYPE_MASK); flags = type & ~SOCK_TYPE_MASK; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; type &= SOCK_TYPE_MASK; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; retval = sock_create(family, type, protocol, &sock); if (retval < 0) goto out; retval = sock_map_fd(sock, flags & (O_CLOEXEC | O_NONBLOCK)); if (retval < 0) goto out_release; out: /* It may be already another descriptor 8) Not kernel problem. */ return retval; out_release: sock_release(sock); return retval; } /* * Create a pair of connected sockets. */ SYSCALL_DEFINE4(socketpair, int, family, int, type, int, protocol, int __user *, usockvec) { struct socket *sock1, *sock2; int fd1, fd2, err; struct file *newfile1, *newfile2; int flags; flags = type & ~SOCK_TYPE_MASK; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; type &= SOCK_TYPE_MASK; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; /* * Obtain the first socket and check if the underlying protocol * supports the socketpair call. */ err = sock_create(family, type, protocol, &sock1); if (err < 0) goto out; err = sock_create(family, type, protocol, &sock2); if (err < 0) goto out_release_1; err = sock1->ops->socketpair(sock1, sock2); if (err < 0) goto out_release_both; fd1 = get_unused_fd_flags(flags); if (unlikely(fd1 < 0)) { err = fd1; goto out_release_both; } fd2 = get_unused_fd_flags(flags); if (unlikely(fd2 < 0)) { err = fd2; goto out_put_unused_1; } newfile1 = sock_alloc_file(sock1, flags, NULL); if (unlikely(IS_ERR(newfile1))) { err = PTR_ERR(newfile1); goto out_put_unused_both; } newfile2 = sock_alloc_file(sock2, flags, NULL); if (IS_ERR(newfile2)) { err = PTR_ERR(newfile2); goto out_fput_1; } err = put_user(fd1, &usockvec[0]); if (err) goto out_fput_both; err = put_user(fd2, &usockvec[1]); if (err) goto out_fput_both; audit_fd_pair(fd1, fd2); fd_install(fd1, newfile1); fd_install(fd2, newfile2); /* fd1 and fd2 may be already another descriptors. * Not kernel problem. */ return 0; out_fput_both: fput(newfile2); fput(newfile1); put_unused_fd(fd2); put_unused_fd(fd1); goto out; out_fput_1: fput(newfile1); put_unused_fd(fd2); put_unused_fd(fd1); sock_release(sock2); goto out; out_put_unused_both: put_unused_fd(fd2); out_put_unused_1: put_unused_fd(fd1); out_release_both: sock_release(sock2); out_release_1: sock_release(sock1); out: return err; } /* * Bind a name to a socket. Nothing much to do here since it's * the protocol's responsibility to handle the local address. * * We move the socket address to kernel space before we call * the protocol layer (having also checked the address is ok). */ SYSCALL_DEFINE3(bind, int, fd, struct sockaddr __user *, umyaddr, int, addrlen) { struct socket *sock; struct sockaddr_storage address; int err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock) { err = move_addr_to_kernel(umyaddr, addrlen, &address); if (err >= 0) { err = security_socket_bind(sock, (struct sockaddr *)&address, addrlen); if (!err) err = sock->ops->bind(sock, (struct sockaddr *) &address, addrlen); } fput_light(sock->file, fput_needed); } return err; } /* * Perform a listen. Basically, we allow the protocol to do anything * necessary for a listen, and if that works, we mark the socket as * ready for listening. */ SYSCALL_DEFINE2(listen, int, fd, int, backlog) { struct socket *sock; int err, fput_needed; int somaxconn; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock) { somaxconn = sock_net(sock->sk)->core.sysctl_somaxconn; if ((unsigned int)backlog > somaxconn) backlog = somaxconn; err = security_socket_listen(sock, backlog); if (!err) err = sock->ops->listen(sock, backlog); fput_light(sock->file, fput_needed); } return err; } /* * For accept, we attempt to create a new socket, set up the link * with the client, wake up the client, then return the new * connected fd. We collect the address of the connector in kernel * space and move it to user at the very end. This is unclean because * we open the socket then return an error. * * 1003.1g adds the ability to recvmsg() to query connection pending * status to recvmsg. We need to add that support in a way thats * clean when we restucture accept also. */ SYSCALL_DEFINE4(accept4, int, fd, struct sockaddr __user *, upeer_sockaddr, int __user *, upeer_addrlen, int, flags) { struct socket *sock, *newsock; struct file *newfile; int err, len, newfd, fput_needed; struct sockaddr_storage address; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = -ENFILE; newsock = sock_alloc(); if (!newsock) goto out_put; newsock->type = sock->type; newsock->ops = sock->ops; /* * We don't need try_module_get here, as the listening socket (sock) * has the protocol module (sock->ops->owner) held. */ __module_get(newsock->ops->owner); newfd = get_unused_fd_flags(flags); if (unlikely(newfd < 0)) { err = newfd; sock_release(newsock); goto out_put; } newfile = sock_alloc_file(newsock, flags, sock->sk->sk_prot_creator->name); if (unlikely(IS_ERR(newfile))) { err = PTR_ERR(newfile); put_unused_fd(newfd); sock_release(newsock); goto out_put; } err = security_socket_accept(sock, newsock); if (err) goto out_fd; err = sock->ops->accept(sock, newsock, sock->file->f_flags); if (err < 0) goto out_fd; if (upeer_sockaddr) { if (newsock->ops->getname(newsock, (struct sockaddr *)&address, &len, 2) < 0) { err = -ECONNABORTED; goto out_fd; } err = move_addr_to_user(&address, len, upeer_sockaddr, upeer_addrlen); if (err < 0) goto out_fd; } /* File flags are not inherited via accept() unlike another OSes. */ fd_install(newfd, newfile); err = newfd; out_put: fput_light(sock->file, fput_needed); out: return err; out_fd: fput(newfile); put_unused_fd(newfd); goto out_put; } SYSCALL_DEFINE3(accept, int, fd, struct sockaddr __user *, upeer_sockaddr, int __user *, upeer_addrlen) { return sys_accept4(fd, upeer_sockaddr, upeer_addrlen, 0); } /* * Attempt to connect to a socket with the server address. The address * is in user space so we verify it is OK and move it to kernel space. * * For 1003.1g we need to add clean support for a bind to AF_UNSPEC to * break bindings * * NOTE: 1003.1g draft 6.3 is broken with respect to AX.25/NetROM and * other SEQPACKET protocols that take time to connect() as it doesn't * include the -EINPROGRESS status for such sockets. */ SYSCALL_DEFINE3(connect, int, fd, struct sockaddr __user *, uservaddr, int, addrlen) { struct socket *sock; struct sockaddr_storage address; int err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = move_addr_to_kernel(uservaddr, addrlen, &address); if (err < 0) goto out_put; err = security_socket_connect(sock, (struct sockaddr *)&address, addrlen); if (err) goto out_put; err = sock->ops->connect(sock, (struct sockaddr *)&address, addrlen, sock->file->f_flags); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Get the local address ('name') of a socket object. Move the obtained * name to user space. */ SYSCALL_DEFINE3(getsockname, int, fd, struct sockaddr __user *, usockaddr, int __user *, usockaddr_len) { struct socket *sock; struct sockaddr_storage address; int len, err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = security_socket_getsockname(sock); if (err) goto out_put; err = sock->ops->getname(sock, (struct sockaddr *)&address, &len, 0); if (err) goto out_put; err = move_addr_to_user(&address, len, usockaddr, usockaddr_len); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Get the remote address ('name') of a socket object. Move the obtained * name to user space. */ SYSCALL_DEFINE3(getpeername, int, fd, struct sockaddr __user *, usockaddr, int __user *, usockaddr_len) { struct socket *sock; struct sockaddr_storage address; int len, err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_getpeername(sock); if (err) { fput_light(sock->file, fput_needed); return err; } err = sock->ops->getname(sock, (struct sockaddr *)&address, &len, 1); if (!err) err = move_addr_to_user(&address, len, usockaddr, usockaddr_len); fput_light(sock->file, fput_needed); } return err; } /* * Send a datagram to a given address. We move the address into kernel * space and check the user space data area is readable before invoking * the protocol. */ SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len, unsigned int, flags, struct sockaddr __user *, addr, int, addr_len) { struct socket *sock; struct sockaddr_storage address; int err; struct msghdr msg; struct iovec iov; int fput_needed; if (len > INT_MAX) len = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; iov.iov_base = buff; iov.iov_len = len; msg.msg_name = NULL; iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, len); msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_namelen = 0; if (addr) { err = move_addr_to_kernel(addr, addr_len, &address); if (err < 0) goto out_put; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = addr_len; } if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; msg.msg_flags = flags; err = sock_sendmsg(sock, &msg, len); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Send a datagram down a socket. */ SYSCALL_DEFINE4(send, int, fd, void __user *, buff, size_t, len, unsigned int, flags) { return sys_sendto(fd, buff, len, flags, NULL, 0); } /* * Receive a frame from the socket and optionally record the address of the * sender. We verify the buffers are writable and if needed move the * sender address from kernel to user space. */ SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags, struct sockaddr __user *, addr, int __user *, addr_len) { struct socket *sock; struct iovec iov; struct msghdr msg; struct sockaddr_storage address; int err, err2; int fput_needed; if (size > INT_MAX) size = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_control = NULL; msg.msg_controllen = 0; iov.iov_len = size; iov.iov_base = ubuf; iov_iter_init(&msg.msg_iter, READ, &iov, 1, size); /* Save some cycles and don't copy the address if not needed */ msg.msg_name = addr ? (struct sockaddr *)&address : NULL; /* We assume all kernel code knows the size of sockaddr_storage */ msg.msg_namelen = 0; if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = sock_recvmsg(sock, &msg, size, flags); if (err >= 0 && addr != NULL) { err2 = move_addr_to_user(&address, msg.msg_namelen, addr, addr_len); if (err2 < 0) err = err2; } fput_light(sock->file, fput_needed); out: return err; } /* * Receive a datagram from a socket. */ SYSCALL_DEFINE4(recv, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags) { return sys_recvfrom(fd, ubuf, size, flags, NULL, NULL); } /* * Set a socket option. Because we don't know the option lengths we have * to pass the user mode parameter for the protocols to sort out. */ SYSCALL_DEFINE5(setsockopt, int, fd, int, level, int, optname, char __user *, optval, int, optlen) { int err, fput_needed; struct socket *sock; if (optlen < 0) return -EINVAL; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_setsockopt(sock, level, optname); if (err) goto out_put; if (level == SOL_SOCKET) err = sock_setsockopt(sock, level, optname, optval, optlen); else err = sock->ops->setsockopt(sock, level, optname, optval, optlen); out_put: fput_light(sock->file, fput_needed); } return err; } /* * Get a socket option. Because we don't know the option lengths we have * to pass a user mode parameter for the protocols to sort out. */ SYSCALL_DEFINE5(getsockopt, int, fd, int, level, int, optname, char __user *, optval, int __user *, optlen) { int err, fput_needed; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_getsockopt(sock, level, optname); if (err) goto out_put; if (level == SOL_SOCKET) err = sock_getsockopt(sock, level, optname, optval, optlen); else err = sock->ops->getsockopt(sock, level, optname, optval, optlen); out_put: fput_light(sock->file, fput_needed); } return err; } /* * Shutdown a socket. */ SYSCALL_DEFINE2(shutdown, int, fd, int, how) { int err, fput_needed; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_shutdown(sock, how); if (!err) err = sock->ops->shutdown(sock, how); fput_light(sock->file, fput_needed); } return err; } /* A couple of helpful macros for getting the address of the 32/64 bit * fields which are the same type (int / unsigned) on our platforms. */ #define COMPAT_MSG(msg, member) ((MSG_CMSG_COMPAT & flags) ? &msg##_compat->member : &msg->member) #define COMPAT_NAMELEN(msg) COMPAT_MSG(msg, msg_namelen) #define COMPAT_FLAGS(msg) COMPAT_MSG(msg, msg_flags) struct used_address { struct sockaddr_storage name; unsigned int name_len; }; static ssize_t copy_msghdr_from_user(struct msghdr *kmsg, struct user_msghdr __user *umsg, struct sockaddr __user **save_addr, struct iovec **iov) { struct sockaddr __user *uaddr; struct iovec __user *uiov; size_t nr_segs; ssize_t err; if (!access_ok(VERIFY_READ, umsg, sizeof(*umsg)) || __get_user(uaddr, &umsg->msg_name) || __get_user(kmsg->msg_namelen, &umsg->msg_namelen) || __get_user(uiov, &umsg->msg_iov) || __get_user(nr_segs, &umsg->msg_iovlen) || __get_user(kmsg->msg_control, &umsg->msg_control) || __get_user(kmsg->msg_controllen, &umsg->msg_controllen) || __get_user(kmsg->msg_flags, &umsg->msg_flags)) return -EFAULT; if (!uaddr) kmsg->msg_namelen = 0; if (kmsg->msg_namelen < 0) return -EINVAL; if (kmsg->msg_namelen > sizeof(struct sockaddr_storage)) kmsg->msg_namelen = sizeof(struct sockaddr_storage); if (save_addr) *save_addr = uaddr; if (uaddr && kmsg->msg_namelen) { if (!save_addr) { err = move_addr_to_kernel(uaddr, kmsg->msg_namelen, kmsg->msg_name); if (err < 0) return err; } } else { kmsg->msg_name = NULL; kmsg->msg_namelen = 0; } if (nr_segs > UIO_MAXIOV) return -EMSGSIZE; err = rw_copy_check_uvector(save_addr ? READ : WRITE, uiov, nr_segs, UIO_FASTIOV, *iov, iov); if (err >= 0) iov_iter_init(&kmsg->msg_iter, save_addr ? READ : WRITE, *iov, nr_segs, err); return err; } static int ___sys_sendmsg(struct socket *sock, struct user_msghdr __user *msg, struct msghdr *msg_sys, unsigned int flags, struct used_address *used_address) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct sockaddr_storage address; struct iovec iovstack[UIO_FASTIOV], *iov = iovstack; unsigned char ctl[sizeof(struct cmsghdr) + 20] __attribute__ ((aligned(sizeof(__kernel_size_t)))); /* 20 is size of ipv6_pktinfo */ unsigned char *ctl_buf = ctl; int ctl_len, total_len; ssize_t err; msg_sys->msg_name = &address; if (MSG_CMSG_COMPAT & flags) err = get_compat_msghdr(msg_sys, msg_compat, NULL, &iov); else err = copy_msghdr_from_user(msg_sys, msg, NULL, &iov); if (err < 0) goto out_freeiov; total_len = err; err = -ENOBUFS; if (msg_sys->msg_controllen > INT_MAX) goto out_freeiov; ctl_len = msg_sys->msg_controllen; if ((MSG_CMSG_COMPAT & flags) && ctl_len) { err = cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl, sizeof(ctl)); if (err) goto out_freeiov; ctl_buf = msg_sys->msg_control; ctl_len = msg_sys->msg_controllen; } else if (ctl_len) { if (ctl_len > sizeof(ctl)) { ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL); if (ctl_buf == NULL) goto out_freeiov; } err = -EFAULT; /* * Careful! Before this, msg_sys->msg_control contains a user pointer. * Afterwards, it will be a kernel pointer. Thus the compiler-assisted * checking falls down on this. */ if (copy_from_user(ctl_buf, (void __user __force *)msg_sys->msg_control, ctl_len)) goto out_freectl; msg_sys->msg_control = ctl_buf; } msg_sys->msg_flags = flags; if (sock->file->f_flags & O_NONBLOCK) msg_sys->msg_flags |= MSG_DONTWAIT; /* * If this is sendmmsg() and current destination address is same as * previously succeeded address, omit asking LSM's decision. * used_address->name_len is initialized to UINT_MAX so that the first * destination address never matches. */ if (used_address && msg_sys->msg_name && used_address->name_len == msg_sys->msg_namelen && !memcmp(&used_address->name, msg_sys->msg_name, used_address->name_len)) { err = sock_sendmsg_nosec(sock, msg_sys, total_len); goto out_freectl; } err = sock_sendmsg(sock, msg_sys, total_len); /* * If this is sendmmsg() and sending to current destination address was * successful, remember it. */ if (used_address && err >= 0) { used_address->name_len = msg_sys->msg_namelen; if (msg_sys->msg_name) memcpy(&used_address->name, msg_sys->msg_name, used_address->name_len); } out_freectl: if (ctl_buf != ctl) sock_kfree_s(sock->sk, ctl_buf, ctl_len); out_freeiov: if (iov != iovstack) kfree(iov); return err; } /* * BSD sendmsg interface */ long __sys_sendmsg(int fd, struct user_msghdr __user *msg, unsigned flags) { int fput_needed, err; struct msghdr msg_sys; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = ___sys_sendmsg(sock, msg, &msg_sys, flags, NULL); fput_light(sock->file, fput_needed); out: return err; } SYSCALL_DEFINE3(sendmsg, int, fd, struct user_msghdr __user *, msg, unsigned int, flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_sendmsg(fd, msg, flags); } /* * Linux sendmmsg interface */ int __sys_sendmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags) { int fput_needed, err, datagrams; struct socket *sock; struct mmsghdr __user *entry; struct compat_mmsghdr __user *compat_entry; struct msghdr msg_sys; struct used_address used_address; if (vlen > UIO_MAXIOV) vlen = UIO_MAXIOV; datagrams = 0; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) return err; used_address.name_len = UINT_MAX; entry = mmsg; compat_entry = (struct compat_mmsghdr __user *)mmsg; err = 0; while (datagrams < vlen) { if (MSG_CMSG_COMPAT & flags) { err = ___sys_sendmsg(sock, (struct user_msghdr __user *)compat_entry, &msg_sys, flags, &used_address); if (err < 0) break; err = __put_user(err, &compat_entry->msg_len); ++compat_entry; } else { err = ___sys_sendmsg(sock, (struct user_msghdr __user *)entry, &msg_sys, flags, &used_address); if (err < 0) break; err = put_user(err, &entry->msg_len); ++entry; } if (err) break; ++datagrams; } fput_light(sock->file, fput_needed); /* We only return an error if no datagrams were able to be sent */ if (datagrams != 0) return datagrams; return err; } SYSCALL_DEFINE4(sendmmsg, int, fd, struct mmsghdr __user *, mmsg, unsigned int, vlen, unsigned int, flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_sendmmsg(fd, mmsg, vlen, flags); } static int ___sys_recvmsg(struct socket *sock, struct user_msghdr __user *msg, struct msghdr *msg_sys, unsigned int flags, int nosec) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct iovec iovstack[UIO_FASTIOV]; struct iovec *iov = iovstack; unsigned long cmsg_ptr; int total_len, len; ssize_t err; /* kernel mode address */ struct sockaddr_storage addr; /* user mode address pointers */ struct sockaddr __user *uaddr; int __user *uaddr_len = COMPAT_NAMELEN(msg); msg_sys->msg_name = &addr; if (MSG_CMSG_COMPAT & flags) err = get_compat_msghdr(msg_sys, msg_compat, &uaddr, &iov); else err = copy_msghdr_from_user(msg_sys, msg, &uaddr, &iov); if (err < 0) goto out_freeiov; total_len = err; cmsg_ptr = (unsigned long)msg_sys->msg_control; msg_sys->msg_flags = flags & (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT); /* We assume all kernel code knows the size of sockaddr_storage */ msg_sys->msg_namelen = 0; if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = (nosec ? sock_recvmsg_nosec : sock_recvmsg)(sock, msg_sys, total_len, flags); if (err < 0) goto out_freeiov; len = err; if (uaddr != NULL) { err = move_addr_to_user(&addr, msg_sys->msg_namelen, uaddr, uaddr_len); if (err < 0) goto out_freeiov; } err = __put_user((msg_sys->msg_flags & ~MSG_CMSG_COMPAT), COMPAT_FLAGS(msg)); if (err) goto out_freeiov; if (MSG_CMSG_COMPAT & flags) err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr, &msg_compat->msg_controllen); else err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr, &msg->msg_controllen); if (err) goto out_freeiov; err = len; out_freeiov: if (iov != iovstack) kfree(iov); return err; } /* * BSD recvmsg interface */ long __sys_recvmsg(int fd, struct user_msghdr __user *msg, unsigned flags) { int fput_needed, err; struct msghdr msg_sys; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = ___sys_recvmsg(sock, msg, &msg_sys, flags, 0); fput_light(sock->file, fput_needed); out: return err; } SYSCALL_DEFINE3(recvmsg, int, fd, struct user_msghdr __user *, msg, unsigned int, flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_recvmsg(fd, msg, flags); } /* * Linux recvmmsg interface */ int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout) { int fput_needed, err, datagrams; struct socket *sock; struct mmsghdr __user *entry; struct compat_mmsghdr __user *compat_entry; struct msghdr msg_sys; struct timespec end_time; if (timeout && poll_select_set_timeout(&end_time, timeout->tv_sec, timeout->tv_nsec)) return -EINVAL; datagrams = 0; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) return err; err = sock_error(sock->sk); if (err) goto out_put; entry = mmsg; compat_entry = (struct compat_mmsghdr __user *)mmsg; while (datagrams < vlen) { /* * No need to ask LSM for more than the first datagram. */ if (MSG_CMSG_COMPAT & flags) { err = ___sys_recvmsg(sock, (struct user_msghdr __user *)compat_entry, &msg_sys, flags & ~MSG_WAITFORONE, datagrams); if (err < 0) break; err = __put_user(err, &compat_entry->msg_len); ++compat_entry; } else { err = ___sys_recvmsg(sock, (struct user_msghdr __user *)entry, &msg_sys, flags & ~MSG_WAITFORONE, datagrams); if (err < 0) break; err = put_user(err, &entry->msg_len); ++entry; } if (err) break; ++datagrams; /* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */ if (flags & MSG_WAITFORONE) flags |= MSG_DONTWAIT; if (timeout) { ktime_get_ts(timeout); *timeout = timespec_sub(end_time, *timeout); if (timeout->tv_sec < 0) { timeout->tv_sec = timeout->tv_nsec = 0; break; } /* Timeout, return less than vlen datagrams */ if (timeout->tv_nsec == 0 && timeout->tv_sec == 0) break; } /* Out of band data, return right away */ if (msg_sys.msg_flags & MSG_OOB) break; } out_put: fput_light(sock->file, fput_needed); if (err == 0) return datagrams; if (datagrams != 0) { /* * We may return less entries than requested (vlen) if the * sock is non block and there aren't enough datagrams... */ if (err != -EAGAIN) { /* * ... or if recvmsg returns an error after we * received some datagrams, where we record the * error to return on the next call or if the * app asks about it using getsockopt(SO_ERROR). */ sock->sk->sk_err = -err; } return datagrams; } return err; } SYSCALL_DEFINE5(recvmmsg, int, fd, struct mmsghdr __user *, mmsg, unsigned int, vlen, unsigned int, flags, struct timespec __user *, timeout) { int datagrams; struct timespec timeout_sys; if (flags & MSG_CMSG_COMPAT) return -EINVAL; if (!timeout) return __sys_recvmmsg(fd, mmsg, vlen, flags, NULL); if (copy_from_user(&timeout_sys, timeout, sizeof(timeout_sys))) return -EFAULT; datagrams = __sys_recvmmsg(fd, mmsg, vlen, flags, &timeout_sys); if (datagrams > 0 && copy_to_user(timeout, &timeout_sys, sizeof(timeout_sys))) datagrams = -EFAULT; return datagrams; } #ifdef __ARCH_WANT_SYS_SOCKETCALL /* Argument list sizes for sys_socketcall */ #define AL(x) ((x) * sizeof(unsigned long)) static const unsigned char nargs[21] = { AL(0), AL(3), AL(3), AL(3), AL(2), AL(3), AL(3), AL(3), AL(4), AL(4), AL(4), AL(6), AL(6), AL(2), AL(5), AL(5), AL(3), AL(3), AL(4), AL(5), AL(4) }; #undef AL /* * System call vectors. * * Argument checking cleaned up. Saved 20% in size. * This function doesn't need to set the kernel lock because * it is set by the callees. */ SYSCALL_DEFINE2(socketcall, int, call, unsigned long __user *, args) { unsigned long a[AUDITSC_ARGS]; unsigned long a0, a1; int err; unsigned int len; if (call < 1 || call > SYS_SENDMMSG) return -EINVAL; len = nargs[call]; if (len > sizeof(a)) return -EINVAL; /* copy_from_user should be SMP safe. */ if (copy_from_user(a, args, len)) return -EFAULT; err = audit_socketcall(nargs[call] / sizeof(unsigned long), a); if (err) return err; a0 = a[0]; a1 = a[1]; switch (call) { case SYS_SOCKET: err = sys_socket(a0, a1, a[2]); break; case SYS_BIND: err = sys_bind(a0, (struct sockaddr __user *)a1, a[2]); break; case SYS_CONNECT: err = sys_connect(a0, (struct sockaddr __user *)a1, a[2]); break; case SYS_LISTEN: err = sys_listen(a0, a1); break; case SYS_ACCEPT: err = sys_accept4(a0, (struct sockaddr __user *)a1, (int __user *)a[2], 0); break; case SYS_GETSOCKNAME: err = sys_getsockname(a0, (struct sockaddr __user *)a1, (int __user *)a[2]); break; case SYS_GETPEERNAME: err = sys_getpeername(a0, (struct sockaddr __user *)a1, (int __user *)a[2]); break; case SYS_SOCKETPAIR: err = sys_socketpair(a0, a1, a[2], (int __user *)a[3]); break; case SYS_SEND: err = sys_send(a0, (void __user *)a1, a[2], a[3]); break; case SYS_SENDTO: err = sys_sendto(a0, (void __user *)a1, a[2], a[3], (struct sockaddr __user *)a[4], a[5]); break; case SYS_RECV: err = sys_recv(a0, (void __user *)a1, a[2], a[3]); break; case SYS_RECVFROM: err = sys_recvfrom(a0, (void __user *)a1, a[2], a[3], (struct sockaddr __user *)a[4], (int __user *)a[5]); break; case SYS_SHUTDOWN: err = sys_shutdown(a0, a1); break; case SYS_SETSOCKOPT: err = sys_setsockopt(a0, a1, a[2], (char __user *)a[3], a[4]); break; case SYS_GETSOCKOPT: err = sys_getsockopt(a0, a1, a[2], (char __user *)a[3], (int __user *)a[4]); break; case SYS_SENDMSG: err = sys_sendmsg(a0, (struct user_msghdr __user *)a1, a[2]); break; case SYS_SENDMMSG: err = sys_sendmmsg(a0, (struct mmsghdr __user *)a1, a[2], a[3]); break; case SYS_RECVMSG: err = sys_recvmsg(a0, (struct user_msghdr __user *)a1, a[2]); break; case SYS_RECVMMSG: err = sys_recvmmsg(a0, (struct mmsghdr __user *)a1, a[2], a[3], (struct timespec __user *)a[4]); break; case SYS_ACCEPT4: err = sys_accept4(a0, (struct sockaddr __user *)a1, (int __user *)a[2], a[3]); break; default: err = -EINVAL; break; } return err; } #endif /* __ARCH_WANT_SYS_SOCKETCALL */ /** * sock_register - add a socket protocol handler * @ops: description of protocol * * This function is called by a protocol handler that wants to * advertise its address family, and have it linked into the * socket interface. The value ops->family corresponds to the * socket system call protocol family. */ int sock_register(const struct net_proto_family *ops) { int err; if (ops->family >= NPROTO) { pr_crit("protocol %d >= NPROTO(%d)\n", ops->family, NPROTO); return -ENOBUFS; } spin_lock(&net_family_lock); if (rcu_dereference_protected(net_families[ops->family], lockdep_is_held(&net_family_lock))) err = -EEXIST; else { rcu_assign_pointer(net_families[ops->family], ops); err = 0; } spin_unlock(&net_family_lock); pr_info("NET: Registered protocol family %d\n", ops->family); return err; } EXPORT_SYMBOL(sock_register); /** * sock_unregister - remove a protocol handler * @family: protocol family to remove * * This function is called by a protocol handler that wants to * remove its address family, and have it unlinked from the * new socket creation. * * If protocol handler is a module, then it can use module reference * counts to protect against new references. If protocol handler is not * a module then it needs to provide its own protection in * the ops->create routine. */ void sock_unregister(int family) { BUG_ON(family < 0 || family >= NPROTO); spin_lock(&net_family_lock); RCU_INIT_POINTER(net_families[family], NULL); spin_unlock(&net_family_lock); synchronize_rcu(); pr_info("NET: Unregistered protocol family %d\n", family); } EXPORT_SYMBOL(sock_unregister); static int __init sock_init(void) { int err; /* * Initialize the network sysctl infrastructure. */ err = net_sysctl_init(); if (err) goto out; /* * Initialize skbuff SLAB cache */ skb_init(); /* * Initialize the protocols module. */ init_inodecache(); err = register_filesystem(&sock_fs_type); if (err) goto out_fs; sock_mnt = kern_mount(&sock_fs_type); if (IS_ERR(sock_mnt)) { err = PTR_ERR(sock_mnt); goto out_mount; } /* The real protocol initialization is performed in later initcalls. */ #ifdef CONFIG_NETFILTER err = netfilter_init(); if (err) goto out; #endif ptp_classifier_init(); out: return err; out_mount: unregister_filesystem(&sock_fs_type); out_fs: goto out; } core_initcall(sock_init); /* early initcall */ #ifdef CONFIG_PROC_FS void socket_seq_show(struct seq_file *seq) { int cpu; int counter = 0; for_each_possible_cpu(cpu) counter += per_cpu(sockets_in_use, cpu); /* It can be negative, by the way. 8) */ if (counter < 0) counter = 0; seq_printf(seq, "sockets: used %d\n", counter); } #endif /* CONFIG_PROC_FS */ #ifdef CONFIG_COMPAT static int do_siocgstamp(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timeval ktv; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&ktv); set_fs(old_fs); if (!err) err = compat_put_timeval(&ktv, up); return err; } static int do_siocgstampns(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timespec kts; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts); set_fs(old_fs); if (!err) err = compat_put_timespec(&kts, up); return err; } static int dev_ifname32(struct net *net, struct compat_ifreq __user *uifr32) { struct ifreq __user *uifr; int err; uifr = compat_alloc_user_space(sizeof(struct ifreq)); if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq))) return -EFAULT; err = dev_ioctl(net, SIOCGIFNAME, uifr); if (err) return err; if (copy_in_user(uifr32, uifr, sizeof(struct compat_ifreq))) return -EFAULT; return 0; } static int dev_ifconf(struct net *net, struct compat_ifconf __user *uifc32) { struct compat_ifconf ifc32; struct ifconf ifc; struct ifconf __user *uifc; struct compat_ifreq __user *ifr32; struct ifreq __user *ifr; unsigned int i, j; int err; if (copy_from_user(&ifc32, uifc32, sizeof(struct compat_ifconf))) return -EFAULT; memset(&ifc, 0, sizeof(ifc)); if (ifc32.ifcbuf == 0) { ifc32.ifc_len = 0; ifc.ifc_len = 0; ifc.ifc_req = NULL; uifc = compat_alloc_user_space(sizeof(struct ifconf)); } else { size_t len = ((ifc32.ifc_len / sizeof(struct compat_ifreq)) + 1) * sizeof(struct ifreq); uifc = compat_alloc_user_space(sizeof(struct ifconf) + len); ifc.ifc_len = len; ifr = ifc.ifc_req = (void __user *)(uifc + 1); ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0; i < ifc32.ifc_len; i += sizeof(struct compat_ifreq)) { if (copy_in_user(ifr, ifr32, sizeof(struct compat_ifreq))) return -EFAULT; ifr++; ifr32++; } } if (copy_to_user(uifc, &ifc, sizeof(struct ifconf))) return -EFAULT; err = dev_ioctl(net, SIOCGIFCONF, uifc); if (err) return err; if (copy_from_user(&ifc, uifc, sizeof(struct ifconf))) return -EFAULT; ifr = ifc.ifc_req; ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0, j = 0; i + sizeof(struct compat_ifreq) <= ifc32.ifc_len && j < ifc.ifc_len; i += sizeof(struct compat_ifreq), j += sizeof(struct ifreq)) { if (copy_in_user(ifr32, ifr, sizeof(struct compat_ifreq))) return -EFAULT; ifr32++; ifr++; } if (ifc32.ifcbuf == 0) { /* Translate from 64-bit structure multiple to * a 32-bit one. */ i = ifc.ifc_len; i = ((i / sizeof(struct ifreq)) * sizeof(struct compat_ifreq)); ifc32.ifc_len = i; } else { ifc32.ifc_len = i; } if (copy_to_user(uifc32, &ifc32, sizeof(struct compat_ifconf))) return -EFAULT; return 0; } static int ethtool_ioctl(struct net *net, struct compat_ifreq __user *ifr32) { struct compat_ethtool_rxnfc __user *compat_rxnfc; bool convert_in = false, convert_out = false; size_t buf_size = ALIGN(sizeof(struct ifreq), 8); struct ethtool_rxnfc __user *rxnfc; struct ifreq __user *ifr; u32 rule_cnt = 0, actual_rule_cnt; u32 ethcmd; u32 data; int ret; if (get_user(data, &ifr32->ifr_ifru.ifru_data)) return -EFAULT; compat_rxnfc = compat_ptr(data); if (get_user(ethcmd, &compat_rxnfc->cmd)) return -EFAULT; /* Most ethtool structures are defined without padding. * Unfortunately struct ethtool_rxnfc is an exception. */ switch (ethcmd) { default: break; case ETHTOOL_GRXCLSRLALL: /* Buffer size is variable */ if (get_user(rule_cnt, &compat_rxnfc->rule_cnt)) return -EFAULT; if (rule_cnt > KMALLOC_MAX_SIZE / sizeof(u32)) return -ENOMEM; buf_size += rule_cnt * sizeof(u32); /* fall through */ case ETHTOOL_GRXRINGS: case ETHTOOL_GRXCLSRLCNT: case ETHTOOL_GRXCLSRULE: case ETHTOOL_SRXCLSRLINS: convert_out = true; /* fall through */ case ETHTOOL_SRXCLSRLDEL: buf_size += sizeof(struct ethtool_rxnfc); convert_in = true; break; } ifr = compat_alloc_user_space(buf_size); rxnfc = (void __user *)ifr + ALIGN(sizeof(struct ifreq), 8); if (copy_in_user(&ifr->ifr_name, &ifr32->ifr_name, IFNAMSIZ)) return -EFAULT; if (put_user(convert_in ? rxnfc : compat_ptr(data), &ifr->ifr_ifru.ifru_data)) return -EFAULT; if (convert_in) { /* We expect there to be holes between fs.m_ext and * fs.ring_cookie and at the end of fs, but nowhere else. */ BUILD_BUG_ON(offsetof(struct compat_ethtool_rxnfc, fs.m_ext) + sizeof(compat_rxnfc->fs.m_ext) != offsetof(struct ethtool_rxnfc, fs.m_ext) + sizeof(rxnfc->fs.m_ext)); BUILD_BUG_ON( offsetof(struct compat_ethtool_rxnfc, fs.location) - offsetof(struct compat_ethtool_rxnfc, fs.ring_cookie) != offsetof(struct ethtool_rxnfc, fs.location) - offsetof(struct ethtool_rxnfc, fs.ring_cookie)); if (copy_in_user(rxnfc, compat_rxnfc, (void __user *)(&rxnfc->fs.m_ext + 1) - (void __user *)rxnfc) || copy_in_user(&rxnfc->fs.ring_cookie, &compat_rxnfc->fs.ring_cookie, (void __user *)(&rxnfc->fs.location + 1) - (void __user *)&rxnfc->fs.ring_cookie) || copy_in_user(&rxnfc->rule_cnt, &compat_rxnfc->rule_cnt, sizeof(rxnfc->rule_cnt))) return -EFAULT; } ret = dev_ioctl(net, SIOCETHTOOL, ifr); if (ret) return ret; if (convert_out) { if (copy_in_user(compat_rxnfc, rxnfc, (const void __user *)(&rxnfc->fs.m_ext + 1) - (const void __user *)rxnfc) || copy_in_user(&compat_rxnfc->fs.ring_cookie, &rxnfc->fs.ring_cookie, (const void __user *)(&rxnfc->fs.location + 1) - (const void __user *)&rxnfc->fs.ring_cookie) || copy_in_user(&compat_rxnfc->rule_cnt, &rxnfc->rule_cnt, sizeof(rxnfc->rule_cnt))) return -EFAULT; if (ethcmd == ETHTOOL_GRXCLSRLALL) { /* As an optimisation, we only copy the actual * number of rules that the underlying * function returned. Since Mallory might * change the rule count in user memory, we * check that it is less than the rule count * originally given (as the user buffer size), * which has been range-checked. */ if (get_user(actual_rule_cnt, &rxnfc->rule_cnt)) return -EFAULT; if (actual_rule_cnt < rule_cnt) rule_cnt = actual_rule_cnt; if (copy_in_user(&compat_rxnfc->rule_locs[0], &rxnfc->rule_locs[0], rule_cnt * sizeof(u32))) return -EFAULT; } } return 0; } static int compat_siocwandev(struct net *net, struct compat_ifreq __user *uifr32) { void __user *uptr; compat_uptr_t uptr32; struct ifreq __user *uifr; uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq))) return -EFAULT; if (get_user(uptr32, &uifr32->ifr_settings.ifs_ifsu)) return -EFAULT; uptr = compat_ptr(uptr32); if (put_user(uptr, &uifr->ifr_settings.ifs_ifsu.raw_hdlc)) return -EFAULT; return dev_ioctl(net, SIOCWANDEV, uifr); } static int bond_ioctl(struct net *net, unsigned int cmd, struct compat_ifreq __user *ifr32) { struct ifreq kifr; mm_segment_t old_fs; int err; switch (cmd) { case SIOCBONDENSLAVE: case SIOCBONDRELEASE: case SIOCBONDSETHWADDR: case SIOCBONDCHANGEACTIVE: if (copy_from_user(&kifr, ifr32, sizeof(struct compat_ifreq))) return -EFAULT; old_fs = get_fs(); set_fs(KERNEL_DS); err = dev_ioctl(net, cmd, (struct ifreq __user __force *) &kifr); set_fs(old_fs); return err; default: return -ENOIOCTLCMD; } } /* Handle ioctls that use ifreq::ifr_data and just need struct ifreq converted */ static int compat_ifr_data_ioctl(struct net *net, unsigned int cmd, struct compat_ifreq __user *u_ifreq32) { struct ifreq __user *u_ifreq64; char tmp_buf[IFNAMSIZ]; void __user *data64; u32 data32; if (copy_from_user(&tmp_buf[0], &(u_ifreq32->ifr_ifrn.ifrn_name[0]), IFNAMSIZ)) return -EFAULT; if (get_user(data32, &u_ifreq32->ifr_ifru.ifru_data)) return -EFAULT; data64 = compat_ptr(data32); u_ifreq64 = compat_alloc_user_space(sizeof(*u_ifreq64)); if (copy_to_user(&u_ifreq64->ifr_ifrn.ifrn_name[0], &tmp_buf[0], IFNAMSIZ)) return -EFAULT; if (put_user(data64, &u_ifreq64->ifr_ifru.ifru_data)) return -EFAULT; return dev_ioctl(net, cmd, u_ifreq64); } static int dev_ifsioc(struct net *net, struct socket *sock, unsigned int cmd, struct compat_ifreq __user *uifr32) { struct ifreq __user *uifr; int err; uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(uifr, uifr32, sizeof(*uifr32))) return -EFAULT; err = sock_do_ioctl(net, sock, cmd, (unsigned long)uifr); if (!err) { switch (cmd) { case SIOCGIFFLAGS: case SIOCGIFMETRIC: case SIOCGIFMTU: case SIOCGIFMEM: case SIOCGIFHWADDR: case SIOCGIFINDEX: case SIOCGIFADDR: case SIOCGIFBRDADDR: case SIOCGIFDSTADDR: case SIOCGIFNETMASK: case SIOCGIFPFLAGS: case SIOCGIFTXQLEN: case SIOCGMIIPHY: case SIOCGMIIREG: if (copy_in_user(uifr32, uifr, sizeof(*uifr32))) err = -EFAULT; break; } } return err; } static int compat_sioc_ifmap(struct net *net, unsigned int cmd, struct compat_ifreq __user *uifr32) { struct ifreq ifr; struct compat_ifmap __user *uifmap32; mm_segment_t old_fs; int err; uifmap32 = &uifr32->ifr_ifru.ifru_map; err = copy_from_user(&ifr, uifr32, sizeof(ifr.ifr_name)); err |= get_user(ifr.ifr_map.mem_start, &uifmap32->mem_start); err |= get_user(ifr.ifr_map.mem_end, &uifmap32->mem_end); err |= get_user(ifr.ifr_map.base_addr, &uifmap32->base_addr); err |= get_user(ifr.ifr_map.irq, &uifmap32->irq); err |= get_user(ifr.ifr_map.dma, &uifmap32->dma); err |= get_user(ifr.ifr_map.port, &uifmap32->port); if (err) return -EFAULT; old_fs = get_fs(); set_fs(KERNEL_DS); err = dev_ioctl(net, cmd, (void __user __force *)&ifr); set_fs(old_fs); if (cmd == SIOCGIFMAP && !err) { err = copy_to_user(uifr32, &ifr, sizeof(ifr.ifr_name)); err |= put_user(ifr.ifr_map.mem_start, &uifmap32->mem_start); err |= put_user(ifr.ifr_map.mem_end, &uifmap32->mem_end); err |= put_user(ifr.ifr_map.base_addr, &uifmap32->base_addr); err |= put_user(ifr.ifr_map.irq, &uifmap32->irq); err |= put_user(ifr.ifr_map.dma, &uifmap32->dma); err |= put_user(ifr.ifr_map.port, &uifmap32->port); if (err) err = -EFAULT; } return err; } struct rtentry32 { u32 rt_pad1; struct sockaddr rt_dst; /* target address */ struct sockaddr rt_gateway; /* gateway addr (RTF_GATEWAY) */ struct sockaddr rt_genmask; /* target network mask (IP) */ unsigned short rt_flags; short rt_pad2; u32 rt_pad3; unsigned char rt_tos; unsigned char rt_class; short rt_pad4; short rt_metric; /* +1 for binary compatibility! */ /* char * */ u32 rt_dev; /* forcing the device at add */ u32 rt_mtu; /* per route MTU/Window */ u32 rt_window; /* Window clamping */ unsigned short rt_irtt; /* Initial RTT */ }; struct in6_rtmsg32 { struct in6_addr rtmsg_dst; struct in6_addr rtmsg_src; struct in6_addr rtmsg_gateway; u32 rtmsg_type; u16 rtmsg_dst_len; u16 rtmsg_src_len; u32 rtmsg_metric; u32 rtmsg_info; u32 rtmsg_flags; s32 rtmsg_ifindex; }; static int routing_ioctl(struct net *net, struct socket *sock, unsigned int cmd, void __user *argp) { int ret; void *r = NULL; struct in6_rtmsg r6; struct rtentry r4; char devname[16]; u32 rtdev; mm_segment_t old_fs = get_fs(); if (sock && sock->sk && sock->sk->sk_family == AF_INET6) { /* ipv6 */ struct in6_rtmsg32 __user *ur6 = argp; ret = copy_from_user(&r6.rtmsg_dst, &(ur6->rtmsg_dst), 3 * sizeof(struct in6_addr)); ret |= get_user(r6.rtmsg_type, &(ur6->rtmsg_type)); ret |= get_user(r6.rtmsg_dst_len, &(ur6->rtmsg_dst_len)); ret |= get_user(r6.rtmsg_src_len, &(ur6->rtmsg_src_len)); ret |= get_user(r6.rtmsg_metric, &(ur6->rtmsg_metric)); ret |= get_user(r6.rtmsg_info, &(ur6->rtmsg_info)); ret |= get_user(r6.rtmsg_flags, &(ur6->rtmsg_flags)); ret |= get_user(r6.rtmsg_ifindex, &(ur6->rtmsg_ifindex)); r = (void *) &r6; } else { /* ipv4 */ struct rtentry32 __user *ur4 = argp; ret = copy_from_user(&r4.rt_dst, &(ur4->rt_dst), 3 * sizeof(struct sockaddr)); ret |= get_user(r4.rt_flags, &(ur4->rt_flags)); ret |= get_user(r4.rt_metric, &(ur4->rt_metric)); ret |= get_user(r4.rt_mtu, &(ur4->rt_mtu)); ret |= get_user(r4.rt_window, &(ur4->rt_window)); ret |= get_user(r4.rt_irtt, &(ur4->rt_irtt)); ret |= get_user(rtdev, &(ur4->rt_dev)); if (rtdev) { ret |= copy_from_user(devname, compat_ptr(rtdev), 15); r4.rt_dev = (char __user __force *)devname; devname[15] = 0; } else r4.rt_dev = NULL; r = (void *) &r4; } if (ret) { ret = -EFAULT; goto out; } set_fs(KERNEL_DS); ret = sock_do_ioctl(net, sock, cmd, (unsigned long) r); set_fs(old_fs); out: return ret; } /* Since old style bridge ioctl's endup using SIOCDEVPRIVATE * for some operations; this forces use of the newer bridge-utils that * use compatible ioctls */ static int old_bridge_ioctl(compat_ulong_t __user *argp) { compat_ulong_t tmp; if (get_user(tmp, argp)) return -EFAULT; if (tmp == BRCTL_GET_VERSION) return BRCTL_VERSION + 1; return -EINVAL; } static int compat_sock_ioctl_trans(struct file *file, struct socket *sock, unsigned int cmd, unsigned long arg) { void __user *argp = compat_ptr(arg); struct sock *sk = sock->sk; struct net *net = sock_net(sk); if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15)) return compat_ifr_data_ioctl(net, cmd, argp); switch (cmd) { case SIOCSIFBR: case SIOCGIFBR: return old_bridge_ioctl(argp); case SIOCGIFNAME: return dev_ifname32(net, argp); case SIOCGIFCONF: return dev_ifconf(net, argp); case SIOCETHTOOL: return ethtool_ioctl(net, argp); case SIOCWANDEV: return compat_siocwandev(net, argp); case SIOCGIFMAP: case SIOCSIFMAP: return compat_sioc_ifmap(net, cmd, argp); case SIOCBONDENSLAVE: case SIOCBONDRELEASE: case SIOCBONDSETHWADDR: case SIOCBONDCHANGEACTIVE: return bond_ioctl(net, cmd, argp); case SIOCADDRT: case SIOCDELRT: return routing_ioctl(net, sock, cmd, argp); case SIOCGSTAMP: return do_siocgstamp(net, sock, cmd, argp); case SIOCGSTAMPNS: return do_siocgstampns(net, sock, cmd, argp); case SIOCBONDSLAVEINFOQUERY: case SIOCBONDINFOQUERY: case SIOCSHWTSTAMP: case SIOCGHWTSTAMP: return compat_ifr_data_ioctl(net, cmd, argp); case FIOSETOWN: case SIOCSPGRP: case FIOGETOWN: case SIOCGPGRP: case SIOCBRADDBR: case SIOCBRDELBR: case SIOCGIFVLAN: case SIOCSIFVLAN: case SIOCADDDLCI: case SIOCDELDLCI: return sock_ioctl(file, cmd, arg); case SIOCGIFFLAGS: case SIOCSIFFLAGS: case SIOCGIFMETRIC: case SIOCSIFMETRIC: case SIOCGIFMTU: case SIOCSIFMTU: case SIOCGIFMEM: case SIOCSIFMEM: case SIOCGIFHWADDR: case SIOCSIFHWADDR: case SIOCADDMULTI: case SIOCDELMULTI: case SIOCGIFINDEX: case SIOCGIFADDR: case SIOCSIFADDR: case SIOCSIFHWBROADCAST: case SIOCDIFADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCSIFPFLAGS: case SIOCGIFPFLAGS: case SIOCGIFTXQLEN: case SIOCSIFTXQLEN: case SIOCBRADDIF: case SIOCBRDELIF: case SIOCSIFNAME: case SIOCGMIIPHY: case SIOCGMIIREG: case SIOCSMIIREG: return dev_ifsioc(net, sock, cmd, argp); case SIOCSARP: case SIOCGARP: case SIOCDARP: case SIOCATMARK: return sock_do_ioctl(net, sock, cmd, arg); } return -ENOIOCTLCMD; } static long compat_sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct socket *sock = file->private_data; int ret = -ENOIOCTLCMD; struct sock *sk; struct net *net; sk = sock->sk; net = sock_net(sk); if (sock->ops->compat_ioctl) ret = sock->ops->compat_ioctl(sock, cmd, arg); if (ret == -ENOIOCTLCMD && (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST)) ret = compat_wext_handle_ioctl(net, cmd, arg); if (ret == -ENOIOCTLCMD) ret = compat_sock_ioctl_trans(file, sock, cmd, arg); return ret; } #endif int kernel_bind(struct socket *sock, struct sockaddr *addr, int addrlen) { return sock->ops->bind(sock, addr, addrlen); } EXPORT_SYMBOL(kernel_bind); int kernel_listen(struct socket *sock, int backlog) { return sock->ops->listen(sock, backlog); } EXPORT_SYMBOL(kernel_listen); int kernel_accept(struct socket *sock, struct socket **newsock, int flags) { struct sock *sk = sock->sk; int err; err = sock_create_lite(sk->sk_family, sk->sk_type, sk->sk_protocol, newsock); if (err < 0) goto done; err = sock->ops->accept(sock, *newsock, flags); if (err < 0) { sock_release(*newsock); *newsock = NULL; goto done; } (*newsock)->ops = sock->ops; __module_get((*newsock)->ops->owner); done: return err; } EXPORT_SYMBOL(kernel_accept); int kernel_connect(struct socket *sock, struct sockaddr *addr, int addrlen, int flags) { return sock->ops->connect(sock, addr, addrlen, flags); } EXPORT_SYMBOL(kernel_connect); int kernel_getsockname(struct socket *sock, struct sockaddr *addr, int *addrlen) { return sock->ops->getname(sock, addr, addrlen, 0); } EXPORT_SYMBOL(kernel_getsockname); int kernel_getpeername(struct socket *sock, struct sockaddr *addr, int *addrlen) { return sock->ops->getname(sock, addr, addrlen, 1); } EXPORT_SYMBOL(kernel_getpeername); int kernel_getsockopt(struct socket *sock, int level, int optname, char *optval, int *optlen) { mm_segment_t oldfs = get_fs(); char __user *uoptval; int __user *uoptlen; int err; uoptval = (char __user __force *) optval; uoptlen = (int __user __force *) optlen; set_fs(KERNEL_DS); if (level == SOL_SOCKET) err = sock_getsockopt(sock, level, optname, uoptval, uoptlen); else err = sock->ops->getsockopt(sock, level, optname, uoptval, uoptlen); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_getsockopt); int kernel_setsockopt(struct socket *sock, int level, int optname, char *optval, unsigned int optlen) { mm_segment_t oldfs = get_fs(); char __user *uoptval; int err; uoptval = (char __user __force *) optval; set_fs(KERNEL_DS); if (level == SOL_SOCKET) err = sock_setsockopt(sock, level, optname, uoptval, optlen); else err = sock->ops->setsockopt(sock, level, optname, uoptval, optlen); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_setsockopt); int kernel_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { if (sock->ops->sendpage) return sock->ops->sendpage(sock, page, offset, size, flags); return sock_no_sendpage(sock, page, offset, size, flags); } EXPORT_SYMBOL(kernel_sendpage); int kernel_sock_ioctl(struct socket *sock, int cmd, unsigned long arg) { mm_segment_t oldfs = get_fs(); int err; set_fs(KERNEL_DS); err = sock->ops->ioctl(sock, cmd, arg); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_sock_ioctl); int kernel_sock_shutdown(struct socket *sock, enum sock_shutdown_cmd how) { return sock->ops->shutdown(sock, how); } EXPORT_SYMBOL(kernel_sock_shutdown);
./CrossVul/dataset_final_sorted/CWE-264/c/bad_1531_0
crossvul-cpp_data_good_3849_0
/* * 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. * * Generic socket support routines. Memory allocators, socket lock/release * handler for protocols to use and generic option handler. * * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Florian La Roche, <flla@stud.uni-sb.de> * Alan Cox, <A.Cox@swansea.ac.uk> * * Fixes: * Alan Cox : Numerous verify_area() problems * Alan Cox : Connecting on a connecting socket * now returns an error for tcp. * Alan Cox : sock->protocol is set correctly. * and is not sometimes left as 0. * Alan Cox : connect handles icmp errors on a * connect properly. Unfortunately there * is a restart syscall nasty there. I * can't match BSD without hacking the C * library. Ideas urgently sought! * Alan Cox : Disallow bind() to addresses that are * not ours - especially broadcast ones!! * Alan Cox : Socket 1024 _IS_ ok for users. (fencepost) * Alan Cox : sock_wfree/sock_rfree don't destroy sockets, * instead they leave that for the DESTROY timer. * Alan Cox : Clean up error flag in accept * Alan Cox : TCP ack handling is buggy, the DESTROY timer * was buggy. Put a remove_sock() in the handler * for memory when we hit 0. Also altered the timer * code. The ACK stuff can wait and needs major * TCP layer surgery. * Alan Cox : Fixed TCP ack bug, removed remove sock * and fixed timer/inet_bh race. * Alan Cox : Added zapped flag for TCP * Alan Cox : Move kfree_skb into skbuff.c and tidied up surplus code * Alan Cox : for new sk_buff allocations wmalloc/rmalloc now call alloc_skb * Alan Cox : kfree_s calls now are kfree_skbmem so we can track skb resources * Alan Cox : Supports socket option broadcast now as does udp. Packet and raw need fixing. * Alan Cox : Added RCVBUF,SNDBUF size setting. It suddenly occurred to me how easy it was so... * Rick Sladkey : Relaxed UDP rules for matching packets. * C.E.Hawkins : IFF_PROMISC/SIOCGHWADDR support * Pauline Middelink : identd support * Alan Cox : Fixed connect() taking signals I think. * Alan Cox : SO_LINGER supported * Alan Cox : Error reporting fixes * Anonymous : inet_create tidied up (sk->reuse setting) * Alan Cox : inet sockets don't set sk->type! * Alan Cox : Split socket option code * Alan Cox : Callbacks * Alan Cox : Nagle flag for Charles & Johannes stuff * Alex : Removed restriction on inet fioctl * Alan Cox : Splitting INET from NET core * Alan Cox : Fixed bogus SO_TYPE handling in getsockopt() * Adam Caldwell : Missing return in SO_DONTROUTE/SO_DEBUG code * Alan Cox : Split IP from generic code * Alan Cox : New kfree_skbmem() * Alan Cox : Make SO_DEBUG superuser only. * Alan Cox : Allow anyone to clear SO_DEBUG * (compatibility fix) * Alan Cox : Added optimistic memory grabbing for AF_UNIX throughput. * Alan Cox : Allocator for a socket is settable. * Alan Cox : SO_ERROR includes soft errors. * Alan Cox : Allow NULL arguments on some SO_ opts * Alan Cox : Generic socket allocation to make hooks * easier (suggested by Craig Metz). * Michael Pall : SO_ERROR returns positive errno again * Steve Whitehouse: Added default destructor to free * protocol private data. * Steve Whitehouse: Added various other default routines * common to several socket families. * Chris Evans : Call suser() check last on F_SETOWN * Jay Schulist : Added SO_ATTACH_FILTER and SO_DETACH_FILTER. * Andi Kleen : Add sock_kmalloc()/sock_kfree_s() * Andi Kleen : Fix write_space callback * Chris Evans : Security fixes - signedness again * Arnaldo C. Melo : cleanups, use skb_queue_purge * * To Fix: * * * 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/capability.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/poll.h> #include <linux/tcp.h> #include <linux/init.h> #include <linux/highmem.h> #include <linux/user_namespace.h> #include <linux/static_key.h> #include <linux/memcontrol.h> #include <linux/prefetch.h> #include <asm/uaccess.h> #include <linux/netdevice.h> #include <net/protocol.h> #include <linux/skbuff.h> #include <net/net_namespace.h> #include <net/request_sock.h> #include <net/sock.h> #include <linux/net_tstamp.h> #include <net/xfrm.h> #include <linux/ipsec.h> #include <net/cls_cgroup.h> #include <net/netprio_cgroup.h> #include <linux/filter.h> #include <trace/events/sock.h> #ifdef CONFIG_INET #include <net/tcp.h> #endif static DEFINE_MUTEX(proto_list_mutex); static LIST_HEAD(proto_list); #ifdef CONFIG_MEMCG_KMEM int mem_cgroup_sockets_init(struct mem_cgroup *memcg, struct cgroup_subsys *ss) { struct proto *proto; int ret = 0; mutex_lock(&proto_list_mutex); list_for_each_entry(proto, &proto_list, node) { if (proto->init_cgroup) { ret = proto->init_cgroup(memcg, ss); if (ret) goto out; } } mutex_unlock(&proto_list_mutex); return ret; out: list_for_each_entry_continue_reverse(proto, &proto_list, node) if (proto->destroy_cgroup) proto->destroy_cgroup(memcg); mutex_unlock(&proto_list_mutex); return ret; } void mem_cgroup_sockets_destroy(struct mem_cgroup *memcg) { struct proto *proto; mutex_lock(&proto_list_mutex); list_for_each_entry_reverse(proto, &proto_list, node) if (proto->destroy_cgroup) proto->destroy_cgroup(memcg); mutex_unlock(&proto_list_mutex); } #endif /* * Each address family might have different locking rules, so we have * one slock key per address family: */ static struct lock_class_key af_family_keys[AF_MAX]; static struct lock_class_key af_family_slock_keys[AF_MAX]; struct static_key memcg_socket_limit_enabled; EXPORT_SYMBOL(memcg_socket_limit_enabled); /* * Make lock validator output more readable. (we pre-construct these * strings build-time, so that runtime initialization of socket * locks is fast): */ static const char *const af_family_key_strings[AF_MAX+1] = { "sk_lock-AF_UNSPEC", "sk_lock-AF_UNIX" , "sk_lock-AF_INET" , "sk_lock-AF_AX25" , "sk_lock-AF_IPX" , "sk_lock-AF_APPLETALK", "sk_lock-AF_NETROM", "sk_lock-AF_BRIDGE" , "sk_lock-AF_ATMPVC" , "sk_lock-AF_X25" , "sk_lock-AF_INET6" , "sk_lock-AF_ROSE" , "sk_lock-AF_DECnet", "sk_lock-AF_NETBEUI" , "sk_lock-AF_SECURITY" , "sk_lock-AF_KEY" , "sk_lock-AF_NETLINK" , "sk_lock-AF_PACKET" , "sk_lock-AF_ASH" , "sk_lock-AF_ECONET" , "sk_lock-AF_ATMSVC" , "sk_lock-AF_RDS" , "sk_lock-AF_SNA" , "sk_lock-AF_IRDA" , "sk_lock-AF_PPPOX" , "sk_lock-AF_WANPIPE" , "sk_lock-AF_LLC" , "sk_lock-27" , "sk_lock-28" , "sk_lock-AF_CAN" , "sk_lock-AF_TIPC" , "sk_lock-AF_BLUETOOTH", "sk_lock-IUCV" , "sk_lock-AF_RXRPC" , "sk_lock-AF_ISDN" , "sk_lock-AF_PHONET" , "sk_lock-AF_IEEE802154", "sk_lock-AF_CAIF" , "sk_lock-AF_ALG" , "sk_lock-AF_NFC" , "sk_lock-AF_MAX" }; static const char *const af_family_slock_key_strings[AF_MAX+1] = { "slock-AF_UNSPEC", "slock-AF_UNIX" , "slock-AF_INET" , "slock-AF_AX25" , "slock-AF_IPX" , "slock-AF_APPLETALK", "slock-AF_NETROM", "slock-AF_BRIDGE" , "slock-AF_ATMPVC" , "slock-AF_X25" , "slock-AF_INET6" , "slock-AF_ROSE" , "slock-AF_DECnet", "slock-AF_NETBEUI" , "slock-AF_SECURITY" , "slock-AF_KEY" , "slock-AF_NETLINK" , "slock-AF_PACKET" , "slock-AF_ASH" , "slock-AF_ECONET" , "slock-AF_ATMSVC" , "slock-AF_RDS" , "slock-AF_SNA" , "slock-AF_IRDA" , "slock-AF_PPPOX" , "slock-AF_WANPIPE" , "slock-AF_LLC" , "slock-27" , "slock-28" , "slock-AF_CAN" , "slock-AF_TIPC" , "slock-AF_BLUETOOTH", "slock-AF_IUCV" , "slock-AF_RXRPC" , "slock-AF_ISDN" , "slock-AF_PHONET" , "slock-AF_IEEE802154", "slock-AF_CAIF" , "slock-AF_ALG" , "slock-AF_NFC" , "slock-AF_MAX" }; static const char *const af_family_clock_key_strings[AF_MAX+1] = { "clock-AF_UNSPEC", "clock-AF_UNIX" , "clock-AF_INET" , "clock-AF_AX25" , "clock-AF_IPX" , "clock-AF_APPLETALK", "clock-AF_NETROM", "clock-AF_BRIDGE" , "clock-AF_ATMPVC" , "clock-AF_X25" , "clock-AF_INET6" , "clock-AF_ROSE" , "clock-AF_DECnet", "clock-AF_NETBEUI" , "clock-AF_SECURITY" , "clock-AF_KEY" , "clock-AF_NETLINK" , "clock-AF_PACKET" , "clock-AF_ASH" , "clock-AF_ECONET" , "clock-AF_ATMSVC" , "clock-AF_RDS" , "clock-AF_SNA" , "clock-AF_IRDA" , "clock-AF_PPPOX" , "clock-AF_WANPIPE" , "clock-AF_LLC" , "clock-27" , "clock-28" , "clock-AF_CAN" , "clock-AF_TIPC" , "clock-AF_BLUETOOTH", "clock-AF_IUCV" , "clock-AF_RXRPC" , "clock-AF_ISDN" , "clock-AF_PHONET" , "clock-AF_IEEE802154", "clock-AF_CAIF" , "clock-AF_ALG" , "clock-AF_NFC" , "clock-AF_MAX" }; /* * sk_callback_lock locking rules are per-address-family, * so split the lock classes by using a per-AF key: */ static struct lock_class_key af_callback_keys[AF_MAX]; /* Take into consideration the size of the struct sk_buff overhead in the * determination of these values, since that is non-constant across * platforms. This makes socket queueing behavior and performance * not depend upon such differences. */ #define _SK_MEM_PACKETS 256 #define _SK_MEM_OVERHEAD SKB_TRUESIZE(256) #define SK_WMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS) #define SK_RMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS) /* Run time adjustable parameters. */ __u32 sysctl_wmem_max __read_mostly = SK_WMEM_MAX; EXPORT_SYMBOL(sysctl_wmem_max); __u32 sysctl_rmem_max __read_mostly = SK_RMEM_MAX; EXPORT_SYMBOL(sysctl_rmem_max); __u32 sysctl_wmem_default __read_mostly = SK_WMEM_MAX; __u32 sysctl_rmem_default __read_mostly = SK_RMEM_MAX; /* Maximal space eaten by iovec or ancillary data plus some space */ int sysctl_optmem_max __read_mostly = sizeof(unsigned long)*(2*UIO_MAXIOV+512); EXPORT_SYMBOL(sysctl_optmem_max); struct static_key memalloc_socks = STATIC_KEY_INIT_FALSE; EXPORT_SYMBOL_GPL(memalloc_socks); /** * sk_set_memalloc - sets %SOCK_MEMALLOC * @sk: socket to set it on * * Set %SOCK_MEMALLOC on a socket for access to emergency reserves. * It's the responsibility of the admin to adjust min_free_kbytes * to meet the requirements */ void sk_set_memalloc(struct sock *sk) { sock_set_flag(sk, SOCK_MEMALLOC); sk->sk_allocation |= __GFP_MEMALLOC; static_key_slow_inc(&memalloc_socks); } EXPORT_SYMBOL_GPL(sk_set_memalloc); void sk_clear_memalloc(struct sock *sk) { sock_reset_flag(sk, SOCK_MEMALLOC); sk->sk_allocation &= ~__GFP_MEMALLOC; static_key_slow_dec(&memalloc_socks); /* * SOCK_MEMALLOC is allowed to ignore rmem limits to ensure forward * progress of swapping. However, if SOCK_MEMALLOC is cleared while * it has rmem allocations there is a risk that the user of the * socket cannot make forward progress due to exceeding the rmem * limits. By rights, sk_clear_memalloc() should only be called * on sockets being torn down but warn and reset the accounting if * that assumption breaks. */ if (WARN_ON(sk->sk_forward_alloc)) sk_mem_reclaim(sk); } EXPORT_SYMBOL_GPL(sk_clear_memalloc); int __sk_backlog_rcv(struct sock *sk, struct sk_buff *skb) { int ret; unsigned long pflags = current->flags; /* these should have been dropped before queueing */ BUG_ON(!sock_flag(sk, SOCK_MEMALLOC)); current->flags |= PF_MEMALLOC; ret = sk->sk_backlog_rcv(sk, skb); tsk_restore_flags(current, pflags, PF_MEMALLOC); return ret; } EXPORT_SYMBOL(__sk_backlog_rcv); #if defined(CONFIG_CGROUPS) #if !defined(CONFIG_NET_CLS_CGROUP) int net_cls_subsys_id = -1; EXPORT_SYMBOL_GPL(net_cls_subsys_id); #endif #if !defined(CONFIG_NETPRIO_CGROUP) int net_prio_subsys_id = -1; EXPORT_SYMBOL_GPL(net_prio_subsys_id); #endif #endif static int sock_set_timeout(long *timeo_p, char __user *optval, int optlen) { struct timeval tv; if (optlen < sizeof(tv)) return -EINVAL; if (copy_from_user(&tv, optval, sizeof(tv))) return -EFAULT; if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC) return -EDOM; if (tv.tv_sec < 0) { static int warned __read_mostly; *timeo_p = 0; if (warned < 10 && net_ratelimit()) { warned++; pr_info("%s: `%s' (pid %d) tries to set negative timeout\n", __func__, current->comm, task_pid_nr(current)); } return 0; } *timeo_p = MAX_SCHEDULE_TIMEOUT; if (tv.tv_sec == 0 && tv.tv_usec == 0) return 0; if (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT/HZ - 1)) *timeo_p = tv.tv_sec*HZ + (tv.tv_usec+(1000000/HZ-1))/(1000000/HZ); return 0; } static void sock_warn_obsolete_bsdism(const char *name) { static int warned; static char warncomm[TASK_COMM_LEN]; if (strcmp(warncomm, current->comm) && warned < 5) { strcpy(warncomm, current->comm); pr_warn("process `%s' is using obsolete %s SO_BSDCOMPAT\n", warncomm, name); warned++; } } #define SK_FLAGS_TIMESTAMP ((1UL << SOCK_TIMESTAMP) | (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)) static void sock_disable_timestamp(struct sock *sk, unsigned long flags) { if (sk->sk_flags & flags) { sk->sk_flags &= ~flags; if (!(sk->sk_flags & SK_FLAGS_TIMESTAMP)) net_disable_timestamp(); } } int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { int err; int skb_len; unsigned long flags; struct sk_buff_head *list = &sk->sk_receive_queue; if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) { atomic_inc(&sk->sk_drops); trace_sock_rcvqueue_full(sk, skb); return -ENOMEM; } err = sk_filter(sk, skb); if (err) return err; if (!sk_rmem_schedule(sk, skb, skb->truesize)) { atomic_inc(&sk->sk_drops); return -ENOBUFS; } skb->dev = NULL; skb_set_owner_r(skb, sk); /* Cache the SKB length before we tack it onto the receive * queue. Once it is added it no longer belongs to us and * may be freed by other threads of control pulling packets * from the queue. */ skb_len = skb->len; /* we escape from rcu protected region, make sure we dont leak * a norefcounted dst */ skb_dst_force(skb); spin_lock_irqsave(&list->lock, flags); skb->dropcount = atomic_read(&sk->sk_drops); __skb_queue_tail(list, skb); spin_unlock_irqrestore(&list->lock, flags); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb_len); return 0; } EXPORT_SYMBOL(sock_queue_rcv_skb); int sk_receive_skb(struct sock *sk, struct sk_buff *skb, const int nested) { int rc = NET_RX_SUCCESS; if (sk_filter(sk, skb)) goto discard_and_relse; skb->dev = NULL; if (sk_rcvqueues_full(sk, skb, sk->sk_rcvbuf)) { atomic_inc(&sk->sk_drops); goto discard_and_relse; } if (nested) bh_lock_sock_nested(sk); else bh_lock_sock(sk); if (!sock_owned_by_user(sk)) { /* * trylock + unlock semantics: */ mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_); rc = sk_backlog_rcv(sk, skb); mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_); } else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) { bh_unlock_sock(sk); atomic_inc(&sk->sk_drops); goto discard_and_relse; } bh_unlock_sock(sk); out: sock_put(sk); return rc; discard_and_relse: kfree_skb(skb); goto out; } EXPORT_SYMBOL(sk_receive_skb); void sk_reset_txq(struct sock *sk) { sk_tx_queue_clear(sk); } EXPORT_SYMBOL(sk_reset_txq); struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = __sk_dst_get(sk); if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk_tx_queue_clear(sk); RCU_INIT_POINTER(sk->sk_dst_cache, NULL); dst_release(dst); return NULL; } return dst; } EXPORT_SYMBOL(__sk_dst_check); struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = sk_dst_get(sk); if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk_dst_reset(sk); dst_release(dst); return NULL; } return dst; } EXPORT_SYMBOL(sk_dst_check); static int sock_bindtodevice(struct sock *sk, char __user *optval, int optlen) { int ret = -ENOPROTOOPT; #ifdef CONFIG_NETDEVICES struct net *net = sock_net(sk); char devname[IFNAMSIZ]; int index; /* Sorry... */ ret = -EPERM; if (!capable(CAP_NET_RAW)) goto out; ret = -EINVAL; if (optlen < 0) goto out; /* Bind this socket to a particular device like "eth0", * as specified in the passed interface name. If the * name is "" or the option length is zero the socket * is not bound. */ if (optlen > IFNAMSIZ - 1) optlen = IFNAMSIZ - 1; memset(devname, 0, sizeof(devname)); ret = -EFAULT; if (copy_from_user(devname, optval, optlen)) goto out; index = 0; if (devname[0] != '\0') { struct net_device *dev; rcu_read_lock(); dev = dev_get_by_name_rcu(net, devname); if (dev) index = dev->ifindex; rcu_read_unlock(); ret = -ENODEV; if (!dev) goto out; } lock_sock(sk); sk->sk_bound_dev_if = index; sk_dst_reset(sk); release_sock(sk); ret = 0; out: #endif return ret; } static inline void sock_valbool_flag(struct sock *sk, int bit, int valbool) { if (valbool) sock_set_flag(sk, bit); else sock_reset_flag(sk, bit); } /* * This is meant for all protocols to use and covers goings on * at the socket level. Everything here is generic. */ int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_bindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * "struct sk_buff" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that "struct sk_buff" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || capable(CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("setsockopt"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE, val & SOF_TIMESTAMPING_TX_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE, val & SOF_TIMESTAMPING_TX_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE, val & SOF_TIMESTAMPING_RX_HARDWARE); if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SOFTWARE, val & SOF_TIMESTAMPING_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE, val & SOF_TIMESTAMPING_SYS_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE, val & SOF_TIMESTAMPING_RAW_HARDWARE); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!capable(CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; /* We implement the SO_SNDLOWAT etc to not be settable (1003.1g 5.3) */ case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; } EXPORT_SYMBOL(sock_setsockopt); void cred_to_ucred(struct pid *pid, const struct cred *cred, struct ucred *ucred) { ucred->pid = pid_vnr(pid); ucred->uid = ucred->gid = -1; if (cred) { struct user_namespace *current_ns = current_user_ns(); ucred->uid = from_kuid(current_ns, cred->euid); ucred->gid = from_kgid(current_ns, cred->egid); } } EXPORT_SYMBOL_GPL(cred_to_ucred); int sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; union { int val; struct linger ling; struct timeval tm; } v; int lv = sizeof(int); int len; if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; memset(&v, 0, sizeof(v)); switch (optname) { case SO_DEBUG: v.val = sock_flag(sk, SOCK_DBG); break; case SO_DONTROUTE: v.val = sock_flag(sk, SOCK_LOCALROUTE); break; case SO_BROADCAST: v.val = sock_flag(sk, SOCK_BROADCAST); break; case SO_SNDBUF: v.val = sk->sk_sndbuf; break; case SO_RCVBUF: v.val = sk->sk_rcvbuf; break; case SO_REUSEADDR: v.val = sk->sk_reuse; break; case SO_KEEPALIVE: v.val = sock_flag(sk, SOCK_KEEPOPEN); break; case SO_TYPE: v.val = sk->sk_type; break; case SO_PROTOCOL: v.val = sk->sk_protocol; break; case SO_DOMAIN: v.val = sk->sk_family; break; case SO_ERROR: v.val = -sock_error(sk); if (v.val == 0) v.val = xchg(&sk->sk_err_soft, 0); break; case SO_OOBINLINE: v.val = sock_flag(sk, SOCK_URGINLINE); break; case SO_NO_CHECK: v.val = sk->sk_no_check; break; case SO_PRIORITY: v.val = sk->sk_priority; break; case SO_LINGER: lv = sizeof(v.ling); v.ling.l_onoff = sock_flag(sk, SOCK_LINGER); v.ling.l_linger = sk->sk_lingertime / HZ; break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("getsockopt"); break; case SO_TIMESTAMP: v.val = sock_flag(sk, SOCK_RCVTSTAMP) && !sock_flag(sk, SOCK_RCVTSTAMPNS); break; case SO_TIMESTAMPNS: v.val = sock_flag(sk, SOCK_RCVTSTAMPNS); break; case SO_TIMESTAMPING: v.val = 0; if (sock_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE)) v.val |= SOF_TIMESTAMPING_TX_HARDWARE; if (sock_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE)) v.val |= SOF_TIMESTAMPING_TX_SOFTWARE; if (sock_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE)) v.val |= SOF_TIMESTAMPING_RX_HARDWARE; if (sock_flag(sk, SOCK_TIMESTAMPING_RX_SOFTWARE)) v.val |= SOF_TIMESTAMPING_RX_SOFTWARE; if (sock_flag(sk, SOCK_TIMESTAMPING_SOFTWARE)) v.val |= SOF_TIMESTAMPING_SOFTWARE; if (sock_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE)) v.val |= SOF_TIMESTAMPING_SYS_HARDWARE; if (sock_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE)) v.val |= SOF_TIMESTAMPING_RAW_HARDWARE; break; case SO_RCVTIMEO: lv = sizeof(struct timeval); if (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) { v.tm.tv_sec = 0; v.tm.tv_usec = 0; } else { v.tm.tv_sec = sk->sk_rcvtimeo / HZ; v.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * 1000000) / HZ; } break; case SO_SNDTIMEO: lv = sizeof(struct timeval); if (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) { v.tm.tv_sec = 0; v.tm.tv_usec = 0; } else { v.tm.tv_sec = sk->sk_sndtimeo / HZ; v.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * 1000000) / HZ; } break; case SO_RCVLOWAT: v.val = sk->sk_rcvlowat; break; case SO_SNDLOWAT: v.val = 1; break; case SO_PASSCRED: v.val = !!test_bit(SOCK_PASSCRED, &sock->flags); break; case SO_PEERCRED: { struct ucred peercred; if (len > sizeof(peercred)) len = sizeof(peercred); cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred); if (copy_to_user(optval, &peercred, len)) return -EFAULT; goto lenout; } case SO_PEERNAME: { char address[128]; if (sock->ops->getname(sock, (struct sockaddr *)address, &lv, 2)) return -ENOTCONN; if (lv < len) return -EINVAL; if (copy_to_user(optval, address, len)) return -EFAULT; goto lenout; } /* Dubious BSD thing... Probably nobody even uses it, but * the UNIX standard wants it for whatever reason... -DaveM */ case SO_ACCEPTCONN: v.val = sk->sk_state == TCP_LISTEN; break; case SO_PASSSEC: v.val = !!test_bit(SOCK_PASSSEC, &sock->flags); break; case SO_PEERSEC: return security_socket_getpeersec_stream(sock, optval, optlen, len); case SO_MARK: v.val = sk->sk_mark; break; case SO_RXQ_OVFL: v.val = sock_flag(sk, SOCK_RXQ_OVFL); break; case SO_WIFI_STATUS: v.val = sock_flag(sk, SOCK_WIFI_STATUS); break; case SO_PEEK_OFF: if (!sock->ops->set_peek_off) return -EOPNOTSUPP; v.val = sk->sk_peek_off; break; case SO_NOFCS: v.val = sock_flag(sk, SOCK_NOFCS); break; default: return -ENOPROTOOPT; } if (len > lv) len = lv; if (copy_to_user(optval, &v, len)) return -EFAULT; lenout: if (put_user(len, optlen)) return -EFAULT; return 0; } /* * Initialize an sk_lock. * * (We also register the sk_lock with the lock validator.) */ static inline void sock_lock_init(struct sock *sk) { sock_lock_init_class_and_name(sk, af_family_slock_key_strings[sk->sk_family], af_family_slock_keys + sk->sk_family, af_family_key_strings[sk->sk_family], af_family_keys + sk->sk_family); } /* * Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet, * even temporarly, because of RCU lookups. sk_node should also be left as is. * We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end */ static void sock_copy(struct sock *nsk, const struct sock *osk) { #ifdef CONFIG_SECURITY_NETWORK void *sptr = nsk->sk_security; #endif memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin)); memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end, osk->sk_prot->obj_size - offsetof(struct sock, sk_dontcopy_end)); #ifdef CONFIG_SECURITY_NETWORK nsk->sk_security = sptr; security_sk_clone(osk, nsk); #endif } /* * caches using SLAB_DESTROY_BY_RCU should let .next pointer from nulls nodes * un-modified. Special care is taken when initializing object to zero. */ static inline void sk_prot_clear_nulls(struct sock *sk, int size) { if (offsetof(struct sock, sk_node.next) != 0) memset(sk, 0, offsetof(struct sock, sk_node.next)); memset(&sk->sk_node.pprev, 0, size - offsetof(struct sock, sk_node.pprev)); } void sk_prot_clear_portaddr_nulls(struct sock *sk, int size) { unsigned long nulls1, nulls2; nulls1 = offsetof(struct sock, __sk_common.skc_node.next); nulls2 = offsetof(struct sock, __sk_common.skc_portaddr_node.next); if (nulls1 > nulls2) swap(nulls1, nulls2); if (nulls1 != 0) memset((char *)sk, 0, nulls1); memset((char *)sk + nulls1 + sizeof(void *), 0, nulls2 - nulls1 - sizeof(void *)); memset((char *)sk + nulls2 + sizeof(void *), 0, size - nulls2 - sizeof(void *)); } EXPORT_SYMBOL(sk_prot_clear_portaddr_nulls); static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority, int family) { struct sock *sk; struct kmem_cache *slab; slab = prot->slab; if (slab != NULL) { sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO); if (!sk) return sk; if (priority & __GFP_ZERO) { if (prot->clear_sk) prot->clear_sk(sk, prot->obj_size); else sk_prot_clear_nulls(sk, prot->obj_size); } } else sk = kmalloc(prot->obj_size, priority); if (sk != NULL) { kmemcheck_annotate_bitfield(sk, flags); if (security_sk_alloc(sk, family, priority)) goto out_free; if (!try_module_get(prot->owner)) goto out_free_sec; sk_tx_queue_clear(sk); } return sk; out_free_sec: security_sk_free(sk); out_free: if (slab != NULL) kmem_cache_free(slab, sk); else kfree(sk); return NULL; } static void sk_prot_free(struct proto *prot, struct sock *sk) { struct kmem_cache *slab; struct module *owner; owner = prot->owner; slab = prot->slab; security_sk_free(sk); if (slab != NULL) kmem_cache_free(slab, sk); else kfree(sk); module_put(owner); } #ifdef CONFIG_CGROUPS void sock_update_classid(struct sock *sk) { u32 classid; rcu_read_lock(); /* doing current task, which cannot vanish. */ classid = task_cls_classid(current); rcu_read_unlock(); if (classid && classid != sk->sk_classid) sk->sk_classid = classid; } EXPORT_SYMBOL(sock_update_classid); void sock_update_netprioidx(struct sock *sk, struct task_struct *task) { if (in_interrupt()) return; sk->sk_cgrp_prioidx = task_netprioidx(task); } EXPORT_SYMBOL_GPL(sock_update_netprioidx); #endif /** * sk_alloc - All socket objects are allocated here * @net: the applicable net namespace * @family: protocol family * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) * @prot: struct proto associated with this new sock instance */ struct sock *sk_alloc(struct net *net, int family, gfp_t priority, struct proto *prot) { struct sock *sk; sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family); if (sk) { sk->sk_family = family; /* * See comment in struct sock definition to understand * why we need sk_prot_creator -acme */ sk->sk_prot = sk->sk_prot_creator = prot; sock_lock_init(sk); sock_net_set(sk, get_net(net)); atomic_set(&sk->sk_wmem_alloc, 1); sock_update_classid(sk); sock_update_netprioidx(sk, current); } return sk; } EXPORT_SYMBOL(sk_alloc); static void __sk_free(struct sock *sk) { struct sk_filter *filter; if (sk->sk_destruct) sk->sk_destruct(sk); filter = rcu_dereference_check(sk->sk_filter, atomic_read(&sk->sk_wmem_alloc) == 0); if (filter) { sk_filter_uncharge(sk, filter); RCU_INIT_POINTER(sk->sk_filter, NULL); } sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP); if (atomic_read(&sk->sk_omem_alloc)) pr_debug("%s: optmem leakage (%d bytes) detected\n", __func__, atomic_read(&sk->sk_omem_alloc)); if (sk->sk_peer_cred) put_cred(sk->sk_peer_cred); put_pid(sk->sk_peer_pid); put_net(sock_net(sk)); sk_prot_free(sk->sk_prot_creator, sk); } void sk_free(struct sock *sk) { /* * We subtract one from sk_wmem_alloc and can know if * some packets are still in some tx queue. * If not null, sock_wfree() will call __sk_free(sk) later */ if (atomic_dec_and_test(&sk->sk_wmem_alloc)) __sk_free(sk); } EXPORT_SYMBOL(sk_free); /* * Last sock_put should drop reference to sk->sk_net. It has already * been dropped in sk_change_net. Taking reference to stopping namespace * is not an option. * Take reference to a socket to remove it from hash _alive_ and after that * destroy it in the context of init_net. */ void sk_release_kernel(struct sock *sk) { if (sk == NULL || sk->sk_socket == NULL) return; sock_hold(sk); sock_release(sk->sk_socket); release_net(sock_net(sk)); sock_net_set(sk, get_net(&init_net)); sock_put(sk); } EXPORT_SYMBOL(sk_release_kernel); static void sk_update_clone(const struct sock *sk, struct sock *newsk) { if (mem_cgroup_sockets_enabled && sk->sk_cgrp) sock_update_memcg(newsk); } /** * sk_clone_lock - clone a socket, and lock its clone * @sk: the socket to clone * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) * * Caller must unlock socket even in error path (bh_unlock_sock(newsk)) */ struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority) { struct sock *newsk; newsk = sk_prot_alloc(sk->sk_prot, priority, sk->sk_family); if (newsk != NULL) { struct sk_filter *filter; sock_copy(newsk, sk); /* SANITY */ get_net(sock_net(newsk)); sk_node_init(&newsk->sk_node); sock_lock_init(newsk); bh_lock_sock(newsk); newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL; newsk->sk_backlog.len = 0; atomic_set(&newsk->sk_rmem_alloc, 0); /* * sk_wmem_alloc set to one (see sk_free() and sock_wfree()) */ atomic_set(&newsk->sk_wmem_alloc, 1); atomic_set(&newsk->sk_omem_alloc, 0); skb_queue_head_init(&newsk->sk_receive_queue); skb_queue_head_init(&newsk->sk_write_queue); #ifdef CONFIG_NET_DMA skb_queue_head_init(&newsk->sk_async_wait_queue); #endif spin_lock_init(&newsk->sk_dst_lock); rwlock_init(&newsk->sk_callback_lock); lockdep_set_class_and_name(&newsk->sk_callback_lock, af_callback_keys + newsk->sk_family, af_family_clock_key_strings[newsk->sk_family]); newsk->sk_dst_cache = NULL; newsk->sk_wmem_queued = 0; newsk->sk_forward_alloc = 0; newsk->sk_send_head = NULL; newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK; sock_reset_flag(newsk, SOCK_DONE); skb_queue_head_init(&newsk->sk_error_queue); filter = rcu_dereference_protected(newsk->sk_filter, 1); if (filter != NULL) sk_filter_charge(newsk, filter); if (unlikely(xfrm_sk_clone_policy(newsk))) { /* It is still raw copy of parent, so invalidate * destructor and make plain sk_free() */ newsk->sk_destruct = NULL; bh_unlock_sock(newsk); sk_free(newsk); newsk = NULL; goto out; } newsk->sk_err = 0; newsk->sk_priority = 0; /* * Before updating sk_refcnt, we must commit prior changes to memory * (Documentation/RCU/rculist_nulls.txt for details) */ smp_wmb(); atomic_set(&newsk->sk_refcnt, 2); /* * Increment the counter in the same struct proto as the master * sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that * is the same as sk->sk_prot->socks, as this field was copied * with memcpy). * * This _changes_ the previous behaviour, where * tcp_create_openreq_child always was incrementing the * equivalent to tcp_prot->socks (inet_sock_nr), so this have * to be taken into account in all callers. -acme */ sk_refcnt_debug_inc(newsk); sk_set_socket(newsk, NULL); newsk->sk_wq = NULL; sk_update_clone(sk, newsk); if (newsk->sk_prot->sockets_allocated) sk_sockets_allocated_inc(newsk); if (newsk->sk_flags & SK_FLAGS_TIMESTAMP) net_enable_timestamp(); } out: return newsk; } EXPORT_SYMBOL_GPL(sk_clone_lock); void sk_setup_caps(struct sock *sk, struct dst_entry *dst) { __sk_dst_set(sk, dst); sk->sk_route_caps = dst->dev->features; if (sk->sk_route_caps & NETIF_F_GSO) sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE; sk->sk_route_caps &= ~sk->sk_route_nocaps; if (sk_can_gso(sk)) { if (dst->header_len) { sk->sk_route_caps &= ~NETIF_F_GSO_MASK; } else { sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM; sk->sk_gso_max_size = dst->dev->gso_max_size; sk->sk_gso_max_segs = dst->dev->gso_max_segs; } } } EXPORT_SYMBOL_GPL(sk_setup_caps); void __init sk_init(void) { if (totalram_pages <= 4096) { sysctl_wmem_max = 32767; sysctl_rmem_max = 32767; sysctl_wmem_default = 32767; sysctl_rmem_default = 32767; } else if (totalram_pages >= 131072) { sysctl_wmem_max = 131071; sysctl_rmem_max = 131071; } } /* * Simple resource managers for sockets. */ /* * Write buffer destructor automatically called from kfree_skb. */ void sock_wfree(struct sk_buff *skb) { struct sock *sk = skb->sk; unsigned int len = skb->truesize; if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) { /* * Keep a reference on sk_wmem_alloc, this will be released * after sk_write_space() call */ atomic_sub(len - 1, &sk->sk_wmem_alloc); sk->sk_write_space(sk); len = 1; } /* * if sk_wmem_alloc reaches 0, we must finish what sk_free() * could not do because of in-flight packets */ if (atomic_sub_and_test(len, &sk->sk_wmem_alloc)) __sk_free(sk); } EXPORT_SYMBOL(sock_wfree); /* * Read buffer destructor automatically called from kfree_skb. */ void sock_rfree(struct sk_buff *skb) { struct sock *sk = skb->sk; unsigned int len = skb->truesize; atomic_sub(len, &sk->sk_rmem_alloc); sk_mem_uncharge(sk, len); } EXPORT_SYMBOL(sock_rfree); void sock_edemux(struct sk_buff *skb) { struct sock *sk = skb->sk; #ifdef CONFIG_INET if (sk->sk_state == TCP_TIME_WAIT) inet_twsk_put(inet_twsk(sk)); else #endif sock_put(sk); } EXPORT_SYMBOL(sock_edemux); int sock_i_uid(struct sock *sk) { int uid; read_lock_bh(&sk->sk_callback_lock); uid = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : 0; read_unlock_bh(&sk->sk_callback_lock); return uid; } EXPORT_SYMBOL(sock_i_uid); unsigned long sock_i_ino(struct sock *sk) { unsigned long ino; read_lock_bh(&sk->sk_callback_lock); ino = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_ino : 0; read_unlock_bh(&sk->sk_callback_lock); return ino; } EXPORT_SYMBOL(sock_i_ino); /* * Allocate a skb from the socket's send buffer. */ struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force, gfp_t priority) { if (force || atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) { struct sk_buff *skb = alloc_skb(size, priority); if (skb) { skb_set_owner_w(skb, sk); return skb; } } return NULL; } EXPORT_SYMBOL(sock_wmalloc); /* * Allocate a skb from the socket's receive buffer. */ struct sk_buff *sock_rmalloc(struct sock *sk, unsigned long size, int force, gfp_t priority) { if (force || atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) { struct sk_buff *skb = alloc_skb(size, priority); if (skb) { skb_set_owner_r(skb, sk); return skb; } } return NULL; } /* * Allocate a memory block from the socket's option memory buffer. */ void *sock_kmalloc(struct sock *sk, int size, gfp_t priority) { if ((unsigned int)size <= sysctl_optmem_max && atomic_read(&sk->sk_omem_alloc) + size < sysctl_optmem_max) { void *mem; /* First do the add, to avoid the race if kmalloc * might sleep. */ atomic_add(size, &sk->sk_omem_alloc); mem = kmalloc(size, priority); if (mem) return mem; atomic_sub(size, &sk->sk_omem_alloc); } return NULL; } EXPORT_SYMBOL(sock_kmalloc); /* * Free an option memory block. */ void sock_kfree_s(struct sock *sk, void *mem, int size) { kfree(mem); atomic_sub(size, &sk->sk_omem_alloc); } EXPORT_SYMBOL(sock_kfree_s); /* It is almost wait_for_tcp_memory minus release_sock/lock_sock. I think, these locks should be removed for datagram sockets. */ static long sock_wait_for_wmem(struct sock *sk, long timeo) { DEFINE_WAIT(wait); clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); for (;;) { if (!timeo) break; if (signal_pending(current)) break; set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) break; if (sk->sk_shutdown & SEND_SHUTDOWN) break; if (sk->sk_err) break; timeo = schedule_timeout(timeo); } finish_wait(sk_sleep(sk), &wait); return timeo; } /* * Generic send/receive buffer handlers */ struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len, unsigned long data_len, int noblock, int *errcode) { struct sk_buff *skb; gfp_t gfp_mask; long timeo; int err; int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT; err = -EMSGSIZE; if (npages > MAX_SKB_FRAGS) goto failure; gfp_mask = sk->sk_allocation; if (gfp_mask & __GFP_WAIT) gfp_mask |= __GFP_REPEAT; timeo = sock_sndtimeo(sk, noblock); while (1) { err = sock_error(sk); if (err != 0) goto failure; err = -EPIPE; if (sk->sk_shutdown & SEND_SHUTDOWN) goto failure; if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) { skb = alloc_skb(header_len, gfp_mask); if (skb) { int i; /* No pages, we're done... */ if (!data_len) break; skb->truesize += data_len; skb_shinfo(skb)->nr_frags = npages; for (i = 0; i < npages; i++) { struct page *page; page = alloc_pages(sk->sk_allocation, 0); if (!page) { err = -ENOBUFS; skb_shinfo(skb)->nr_frags = i; kfree_skb(skb); goto failure; } __skb_fill_page_desc(skb, i, page, 0, (data_len >= PAGE_SIZE ? PAGE_SIZE : data_len)); data_len -= PAGE_SIZE; } /* Full success... */ break; } err = -ENOBUFS; goto failure; } set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); err = -EAGAIN; if (!timeo) goto failure; if (signal_pending(current)) goto interrupted; timeo = sock_wait_for_wmem(sk, timeo); } skb_set_owner_w(skb, sk); return skb; interrupted: err = sock_intr_errno(timeo); failure: *errcode = err; return NULL; } EXPORT_SYMBOL(sock_alloc_send_pskb); struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size, int noblock, int *errcode) { return sock_alloc_send_pskb(sk, size, 0, noblock, errcode); } EXPORT_SYMBOL(sock_alloc_send_skb); static void __lock_sock(struct sock *sk) __releases(&sk->sk_lock.slock) __acquires(&sk->sk_lock.slock) { DEFINE_WAIT(wait); for (;;) { prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait, TASK_UNINTERRUPTIBLE); spin_unlock_bh(&sk->sk_lock.slock); schedule(); spin_lock_bh(&sk->sk_lock.slock); if (!sock_owned_by_user(sk)) break; } finish_wait(&sk->sk_lock.wq, &wait); } static void __release_sock(struct sock *sk) __releases(&sk->sk_lock.slock) __acquires(&sk->sk_lock.slock) { struct sk_buff *skb = sk->sk_backlog.head; do { sk->sk_backlog.head = sk->sk_backlog.tail = NULL; bh_unlock_sock(sk); do { struct sk_buff *next = skb->next; prefetch(next); WARN_ON_ONCE(skb_dst_is_noref(skb)); skb->next = NULL; sk_backlog_rcv(sk, skb); /* * We are in process context here with softirqs * disabled, use cond_resched_softirq() to preempt. * This is safe to do because we've taken the backlog * queue private: */ cond_resched_softirq(); skb = next; } while (skb != NULL); bh_lock_sock(sk); } while ((skb = sk->sk_backlog.head) != NULL); /* * Doing the zeroing here guarantee we can not loop forever * while a wild producer attempts to flood us. */ sk->sk_backlog.len = 0; } /** * sk_wait_data - wait for data to arrive at sk_receive_queue * @sk: sock to wait on * @timeo: for how long * * Now socket state including sk->sk_err is changed only under lock, * hence we may omit checks after joining wait queue. * We check receive queue before schedule() only as optimization; * it is very likely that release_sock() added new data. */ int sk_wait_data(struct sock *sk, long *timeo) { int rc; DEFINE_WAIT(wait); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); rc = sk_wait_event(sk, timeo, !skb_queue_empty(&sk->sk_receive_queue)); clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); finish_wait(sk_sleep(sk), &wait); return rc; } EXPORT_SYMBOL(sk_wait_data); /** * __sk_mem_schedule - increase sk_forward_alloc and memory_allocated * @sk: socket * @size: memory size to allocate * @kind: allocation type * * If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means * rmem allocation. This function assumes that protocols which have * memory_pressure use sk_wmem_queued as write buffer accounting. */ int __sk_mem_schedule(struct sock *sk, int size, int kind) { struct proto *prot = sk->sk_prot; int amt = sk_mem_pages(size); long allocated; int parent_status = UNDER_LIMIT; sk->sk_forward_alloc += amt * SK_MEM_QUANTUM; allocated = sk_memory_allocated_add(sk, amt, &parent_status); /* Under limit. */ if (parent_status == UNDER_LIMIT && allocated <= sk_prot_mem_limits(sk, 0)) { sk_leave_memory_pressure(sk); return 1; } /* Under pressure. (we or our parents) */ if ((parent_status > SOFT_LIMIT) || allocated > sk_prot_mem_limits(sk, 1)) sk_enter_memory_pressure(sk); /* Over hard limit (we or our parents) */ if ((parent_status == OVER_LIMIT) || (allocated > sk_prot_mem_limits(sk, 2))) goto suppress_allocation; /* guarantee minimum buffer size under pressure */ if (kind == SK_MEM_RECV) { if (atomic_read(&sk->sk_rmem_alloc) < prot->sysctl_rmem[0]) return 1; } else { /* SK_MEM_SEND */ if (sk->sk_type == SOCK_STREAM) { if (sk->sk_wmem_queued < prot->sysctl_wmem[0]) return 1; } else if (atomic_read(&sk->sk_wmem_alloc) < prot->sysctl_wmem[0]) return 1; } if (sk_has_memory_pressure(sk)) { int alloc; if (!sk_under_memory_pressure(sk)) return 1; alloc = sk_sockets_allocated_read_positive(sk); if (sk_prot_mem_limits(sk, 2) > alloc * sk_mem_pages(sk->sk_wmem_queued + atomic_read(&sk->sk_rmem_alloc) + sk->sk_forward_alloc)) return 1; } suppress_allocation: if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) { sk_stream_moderate_sndbuf(sk); /* Fail only if socket is _under_ its sndbuf. * In this case we cannot block, so that we have to fail. */ if (sk->sk_wmem_queued + size >= sk->sk_sndbuf) return 1; } trace_sock_exceed_buf_limit(sk, prot, allocated); /* Alas. Undo changes. */ sk->sk_forward_alloc -= amt * SK_MEM_QUANTUM; sk_memory_allocated_sub(sk, amt); return 0; } EXPORT_SYMBOL(__sk_mem_schedule); /** * __sk_reclaim - reclaim memory_allocated * @sk: socket */ void __sk_mem_reclaim(struct sock *sk) { sk_memory_allocated_sub(sk, sk->sk_forward_alloc >> SK_MEM_QUANTUM_SHIFT); sk->sk_forward_alloc &= SK_MEM_QUANTUM - 1; if (sk_under_memory_pressure(sk) && (sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0))) sk_leave_memory_pressure(sk); } EXPORT_SYMBOL(__sk_mem_reclaim); /* * Set of default routines for initialising struct proto_ops when * the protocol does not support a particular function. In certain * cases where it makes no sense for a protocol to have a "do nothing" * function, some default processing is provided. */ int sock_no_bind(struct socket *sock, struct sockaddr *saddr, int len) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_bind); int sock_no_connect(struct socket *sock, struct sockaddr *saddr, int len, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_connect); int sock_no_socketpair(struct socket *sock1, struct socket *sock2) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_socketpair); int sock_no_accept(struct socket *sock, struct socket *newsock, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_accept); int sock_no_getname(struct socket *sock, struct sockaddr *saddr, int *len, int peer) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_getname); unsigned int sock_no_poll(struct file *file, struct socket *sock, poll_table *pt) { return 0; } EXPORT_SYMBOL(sock_no_poll); int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_ioctl); int sock_no_listen(struct socket *sock, int backlog) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_listen); int sock_no_shutdown(struct socket *sock, int how) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_shutdown); int sock_no_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_setsockopt); int sock_no_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_getsockopt); int sock_no_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t len) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_sendmsg); int sock_no_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t len, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_recvmsg); int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma) { /* Mirror missing mmap method error code */ return -ENODEV; } EXPORT_SYMBOL(sock_no_mmap); ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { ssize_t res; struct msghdr msg = {.msg_flags = flags}; struct kvec iov; char *kaddr = kmap(page); iov.iov_base = kaddr + offset; iov.iov_len = size; res = kernel_sendmsg(sock, &msg, &iov, 1, size); kunmap(page); return res; } EXPORT_SYMBOL(sock_no_sendpage); /* * Default Socket Callbacks */ static void sock_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_interruptible_all(&wq->wait); rcu_read_unlock(); } static void sock_def_error_report(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up_interruptible_poll(&wq->wait, POLLERR); sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR); rcu_read_unlock(); } static void sock_def_readable(struct sock *sk, int len) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND); sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN); rcu_read_unlock(); } static void sock_def_write_space(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); /* Do not wake up a writer until he can make "significant" * progress. --DaveM */ if ((atomic_read(&sk->sk_wmem_alloc) << 1) <= sk->sk_sndbuf) { wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLOUT | POLLWRNORM | POLLWRBAND); /* Should agree with poll, otherwise some programs break */ if (sock_writeable(sk)) sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT); } rcu_read_unlock(); } static void sock_def_destruct(struct sock *sk) { kfree(sk->sk_protinfo); } void sk_send_sigurg(struct sock *sk) { if (sk->sk_socket && sk->sk_socket->file) if (send_sigurg(&sk->sk_socket->file->f_owner)) sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI); } EXPORT_SYMBOL(sk_send_sigurg); void sk_reset_timer(struct sock *sk, struct timer_list* timer, unsigned long expires) { if (!mod_timer(timer, expires)) sock_hold(sk); } EXPORT_SYMBOL(sk_reset_timer); void sk_stop_timer(struct sock *sk, struct timer_list* timer) { if (timer_pending(timer) && del_timer(timer)) __sock_put(sk); } EXPORT_SYMBOL(sk_stop_timer); void sock_init_data(struct socket *sock, struct sock *sk) { skb_queue_head_init(&sk->sk_receive_queue); skb_queue_head_init(&sk->sk_write_queue); skb_queue_head_init(&sk->sk_error_queue); #ifdef CONFIG_NET_DMA skb_queue_head_init(&sk->sk_async_wait_queue); #endif sk->sk_send_head = NULL; init_timer(&sk->sk_timer); sk->sk_allocation = GFP_KERNEL; sk->sk_rcvbuf = sysctl_rmem_default; sk->sk_sndbuf = sysctl_wmem_default; sk->sk_state = TCP_CLOSE; sk_set_socket(sk, sock); sock_set_flag(sk, SOCK_ZAPPED); if (sock) { sk->sk_type = sock->type; sk->sk_wq = sock->wq; sock->sk = sk; } else sk->sk_wq = NULL; spin_lock_init(&sk->sk_dst_lock); rwlock_init(&sk->sk_callback_lock); lockdep_set_class_and_name(&sk->sk_callback_lock, af_callback_keys + sk->sk_family, af_family_clock_key_strings[sk->sk_family]); sk->sk_state_change = sock_def_wakeup; sk->sk_data_ready = sock_def_readable; sk->sk_write_space = sock_def_write_space; sk->sk_error_report = sock_def_error_report; sk->sk_destruct = sock_def_destruct; sk->sk_sndmsg_page = NULL; sk->sk_sndmsg_off = 0; sk->sk_peek_off = -1; sk->sk_peer_pid = NULL; sk->sk_peer_cred = NULL; sk->sk_write_pending = 0; sk->sk_rcvlowat = 1; sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT; sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT; sk->sk_stamp = ktime_set(-1L, 0); /* * Before updating sk_refcnt, we must commit prior changes to memory * (Documentation/RCU/rculist_nulls.txt for details) */ smp_wmb(); atomic_set(&sk->sk_refcnt, 1); atomic_set(&sk->sk_drops, 0); } EXPORT_SYMBOL(sock_init_data); void lock_sock_nested(struct sock *sk, int subclass) { might_sleep(); spin_lock_bh(&sk->sk_lock.slock); if (sk->sk_lock.owned) __lock_sock(sk); sk->sk_lock.owned = 1; spin_unlock(&sk->sk_lock.slock); /* * The sk_lock has mutex_lock() semantics here: */ mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_); local_bh_enable(); } EXPORT_SYMBOL(lock_sock_nested); void release_sock(struct sock *sk) { /* * The sk_lock has mutex_unlock() semantics: */ mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_); spin_lock_bh(&sk->sk_lock.slock); if (sk->sk_backlog.tail) __release_sock(sk); if (sk->sk_prot->release_cb) sk->sk_prot->release_cb(sk); sk->sk_lock.owned = 0; if (waitqueue_active(&sk->sk_lock.wq)) wake_up(&sk->sk_lock.wq); spin_unlock_bh(&sk->sk_lock.slock); } EXPORT_SYMBOL(release_sock); /** * lock_sock_fast - fast version of lock_sock * @sk: socket * * This version should be used for very small section, where process wont block * return false if fast path is taken * sk_lock.slock locked, owned = 0, BH disabled * return true if slow path is taken * sk_lock.slock unlocked, owned = 1, BH enabled */ bool lock_sock_fast(struct sock *sk) { might_sleep(); spin_lock_bh(&sk->sk_lock.slock); if (!sk->sk_lock.owned) /* * Note : We must disable BH */ return false; __lock_sock(sk); sk->sk_lock.owned = 1; spin_unlock(&sk->sk_lock.slock); /* * The sk_lock has mutex_lock() semantics here: */ mutex_acquire(&sk->sk_lock.dep_map, 0, 0, _RET_IP_); local_bh_enable(); return true; } EXPORT_SYMBOL(lock_sock_fast); int sock_get_timestamp(struct sock *sk, struct timeval __user *userstamp) { struct timeval tv; 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 -ENOENT; if (tv.tv_sec == 0) { sk->sk_stamp = ktime_get_real(); tv = ktime_to_timeval(sk->sk_stamp); } return copy_to_user(userstamp, &tv, sizeof(tv)) ? -EFAULT : 0; } EXPORT_SYMBOL(sock_get_timestamp); int sock_get_timestampns(struct sock *sk, struct timespec __user *userstamp) { struct timespec ts; 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 -ENOENT; if (ts.tv_sec == 0) { sk->sk_stamp = ktime_get_real(); ts = ktime_to_timespec(sk->sk_stamp); } return copy_to_user(userstamp, &ts, sizeof(ts)) ? -EFAULT : 0; } EXPORT_SYMBOL(sock_get_timestampns); void sock_enable_timestamp(struct sock *sk, int flag) { if (!sock_flag(sk, flag)) { unsigned long previous_flags = sk->sk_flags; sock_set_flag(sk, flag); /* * we just set one of the two flags which require net * time stamping, but time stamping might have been on * already because of the other one */ if (!(previous_flags & SK_FLAGS_TIMESTAMP)) net_enable_timestamp(); } } /* * Get a socket option on an socket. * * FIX: POSIX 1003.1g is very ambiguous here. It states that * asynchronous errors should be reported by getsockopt. We assume * this means if you specify SO_ERROR (otherwise whats the point of it). */ int sock_common_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(sock_common_getsockopt); #ifdef CONFIG_COMPAT int compat_sock_common_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; if (sk->sk_prot->compat_getsockopt != NULL) return sk->sk_prot->compat_getsockopt(sk, level, optname, optval, optlen); return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_sock_common_getsockopt); #endif int sock_common_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; int addr_len = 0; int err; err = sk->sk_prot->recvmsg(iocb, sk, msg, size, flags & MSG_DONTWAIT, flags & ~MSG_DONTWAIT, &addr_len); if (err >= 0) msg->msg_namelen = addr_len; return err; } EXPORT_SYMBOL(sock_common_recvmsg); /* * Set socket options on an inet socket. */ int sock_common_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(sock_common_setsockopt); #ifdef CONFIG_COMPAT int compat_sock_common_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; if (sk->sk_prot->compat_setsockopt != NULL) return sk->sk_prot->compat_setsockopt(sk, level, optname, optval, optlen); return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_sock_common_setsockopt); #endif void sk_common_release(struct sock *sk) { if (sk->sk_prot->destroy) sk->sk_prot->destroy(sk); /* * Observation: when sock_common_release is called, processes have * no access to socket. But net still has. * Step one, detach it from networking: * * A. Remove from hash tables. */ sk->sk_prot->unhash(sk); /* * In this point socket cannot receive new packets, but it is possible * that some packets are in flight because some CPU runs receiver and * did hash table lookup before we unhashed socket. They will achieve * receive queue and will be purged by socket destructor. * * Also we still have packets pending on receive queue and probably, * our own packets waiting in device queues. sock_destroy will drain * receive queue, but transmitted packets will delay socket destruction * until the last reference will be released. */ sock_orphan(sk); xfrm_sk_free_policy(sk); sk_refcnt_debug_release(sk); sock_put(sk); } EXPORT_SYMBOL(sk_common_release); #ifdef CONFIG_PROC_FS #define PROTO_INUSE_NR 64 /* should be enough for the first time */ struct prot_inuse { int val[PROTO_INUSE_NR]; }; static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR); #ifdef CONFIG_NET_NS void sock_prot_inuse_add(struct net *net, struct proto *prot, int val) { __this_cpu_add(net->core.inuse->val[prot->inuse_idx], val); } EXPORT_SYMBOL_GPL(sock_prot_inuse_add); int sock_prot_inuse_get(struct net *net, struct proto *prot) { int cpu, idx = prot->inuse_idx; int res = 0; for_each_possible_cpu(cpu) res += per_cpu_ptr(net->core.inuse, cpu)->val[idx]; return res >= 0 ? res : 0; } EXPORT_SYMBOL_GPL(sock_prot_inuse_get); static int __net_init sock_inuse_init_net(struct net *net) { net->core.inuse = alloc_percpu(struct prot_inuse); return net->core.inuse ? 0 : -ENOMEM; } static void __net_exit sock_inuse_exit_net(struct net *net) { free_percpu(net->core.inuse); } static struct pernet_operations net_inuse_ops = { .init = sock_inuse_init_net, .exit = sock_inuse_exit_net, }; static __init int net_inuse_init(void) { if (register_pernet_subsys(&net_inuse_ops)) panic("Cannot initialize net inuse counters"); return 0; } core_initcall(net_inuse_init); #else static DEFINE_PER_CPU(struct prot_inuse, prot_inuse); void sock_prot_inuse_add(struct net *net, struct proto *prot, int val) { __this_cpu_add(prot_inuse.val[prot->inuse_idx], val); } EXPORT_SYMBOL_GPL(sock_prot_inuse_add); int sock_prot_inuse_get(struct net *net, struct proto *prot) { int cpu, idx = prot->inuse_idx; int res = 0; for_each_possible_cpu(cpu) res += per_cpu(prot_inuse, cpu).val[idx]; return res >= 0 ? res : 0; } EXPORT_SYMBOL_GPL(sock_prot_inuse_get); #endif static void assign_proto_idx(struct proto *prot) { prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR); if (unlikely(prot->inuse_idx == PROTO_INUSE_NR - 1)) { pr_err("PROTO_INUSE_NR exhausted\n"); return; } set_bit(prot->inuse_idx, proto_inuse_idx); } static void release_proto_idx(struct proto *prot) { if (prot->inuse_idx != PROTO_INUSE_NR - 1) clear_bit(prot->inuse_idx, proto_inuse_idx); } #else static inline void assign_proto_idx(struct proto *prot) { } static inline void release_proto_idx(struct proto *prot) { } #endif int proto_register(struct proto *prot, int alloc_slab) { if (alloc_slab) { prot->slab = kmem_cache_create(prot->name, prot->obj_size, 0, SLAB_HWCACHE_ALIGN | prot->slab_flags, NULL); if (prot->slab == NULL) { pr_crit("%s: Can't create sock SLAB cache!\n", prot->name); goto out; } if (prot->rsk_prot != NULL) { prot->rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s", prot->name); if (prot->rsk_prot->slab_name == NULL) goto out_free_sock_slab; prot->rsk_prot->slab = kmem_cache_create(prot->rsk_prot->slab_name, prot->rsk_prot->obj_size, 0, SLAB_HWCACHE_ALIGN, NULL); if (prot->rsk_prot->slab == NULL) { pr_crit("%s: Can't create request sock SLAB cache!\n", prot->name); goto out_free_request_sock_slab_name; } } if (prot->twsk_prot != NULL) { prot->twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s", prot->name); if (prot->twsk_prot->twsk_slab_name == NULL) goto out_free_request_sock_slab; prot->twsk_prot->twsk_slab = kmem_cache_create(prot->twsk_prot->twsk_slab_name, prot->twsk_prot->twsk_obj_size, 0, SLAB_HWCACHE_ALIGN | prot->slab_flags, NULL); if (prot->twsk_prot->twsk_slab == NULL) goto out_free_timewait_sock_slab_name; } } mutex_lock(&proto_list_mutex); list_add(&prot->node, &proto_list); assign_proto_idx(prot); mutex_unlock(&proto_list_mutex); return 0; out_free_timewait_sock_slab_name: kfree(prot->twsk_prot->twsk_slab_name); out_free_request_sock_slab: if (prot->rsk_prot && prot->rsk_prot->slab) { kmem_cache_destroy(prot->rsk_prot->slab); prot->rsk_prot->slab = NULL; } out_free_request_sock_slab_name: if (prot->rsk_prot) kfree(prot->rsk_prot->slab_name); out_free_sock_slab: kmem_cache_destroy(prot->slab); prot->slab = NULL; out: return -ENOBUFS; } EXPORT_SYMBOL(proto_register); void proto_unregister(struct proto *prot) { mutex_lock(&proto_list_mutex); release_proto_idx(prot); list_del(&prot->node); mutex_unlock(&proto_list_mutex); if (prot->slab != NULL) { kmem_cache_destroy(prot->slab); prot->slab = NULL; } if (prot->rsk_prot != NULL && prot->rsk_prot->slab != NULL) { kmem_cache_destroy(prot->rsk_prot->slab); kfree(prot->rsk_prot->slab_name); prot->rsk_prot->slab = NULL; } if (prot->twsk_prot != NULL && prot->twsk_prot->twsk_slab != NULL) { kmem_cache_destroy(prot->twsk_prot->twsk_slab); kfree(prot->twsk_prot->twsk_slab_name); prot->twsk_prot->twsk_slab = NULL; } } EXPORT_SYMBOL(proto_unregister); #ifdef CONFIG_PROC_FS static void *proto_seq_start(struct seq_file *seq, loff_t *pos) __acquires(proto_list_mutex) { mutex_lock(&proto_list_mutex); return seq_list_start_head(&proto_list, *pos); } static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_list_next(v, &proto_list, pos); } static void proto_seq_stop(struct seq_file *seq, void *v) __releases(proto_list_mutex) { mutex_unlock(&proto_list_mutex); } static char proto_method_implemented(const void *method) { return method == NULL ? 'n' : 'y'; } static long sock_prot_memory_allocated(struct proto *proto) { return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L; } static char *sock_prot_memory_pressure(struct proto *proto) { return proto->memory_pressure != NULL ? proto_memory_pressure(proto) ? "yes" : "no" : "NI"; } static void proto_seq_printf(struct seq_file *seq, struct proto *proto) { seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s " "%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n", proto->name, proto->obj_size, sock_prot_inuse_get(seq_file_net(seq), proto), sock_prot_memory_allocated(proto), sock_prot_memory_pressure(proto), proto->max_header, proto->slab == NULL ? "no" : "yes", module_name(proto->owner), proto_method_implemented(proto->close), proto_method_implemented(proto->connect), proto_method_implemented(proto->disconnect), proto_method_implemented(proto->accept), proto_method_implemented(proto->ioctl), proto_method_implemented(proto->init), proto_method_implemented(proto->destroy), proto_method_implemented(proto->shutdown), proto_method_implemented(proto->setsockopt), proto_method_implemented(proto->getsockopt), proto_method_implemented(proto->sendmsg), proto_method_implemented(proto->recvmsg), proto_method_implemented(proto->sendpage), proto_method_implemented(proto->bind), proto_method_implemented(proto->backlog_rcv), proto_method_implemented(proto->hash), proto_method_implemented(proto->unhash), proto_method_implemented(proto->get_port), proto_method_implemented(proto->enter_memory_pressure)); } static int proto_seq_show(struct seq_file *seq, void *v) { if (v == &proto_list) seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s", "protocol", "size", "sockets", "memory", "press", "maxhdr", "slab", "module", "cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\n"); else proto_seq_printf(seq, list_entry(v, struct proto, node)); return 0; } static const struct seq_operations proto_seq_ops = { .start = proto_seq_start, .next = proto_seq_next, .stop = proto_seq_stop, .show = proto_seq_show, }; static int proto_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &proto_seq_ops, sizeof(struct seq_net_private)); } static const struct file_operations proto_seq_fops = { .owner = THIS_MODULE, .open = proto_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static __net_init int proto_init_net(struct net *net) { if (!proc_net_fops_create(net, "protocols", S_IRUGO, &proto_seq_fops)) return -ENOMEM; return 0; } static __net_exit void proto_exit_net(struct net *net) { proc_net_remove(net, "protocols"); } static __net_initdata struct pernet_operations proto_net_ops = { .init = proto_init_net, .exit = proto_exit_net, }; static int __init proto_init(void) { return register_pernet_subsys(&proto_net_ops); } subsys_initcall(proto_init); #endif /* PROC_FS */
./CrossVul/dataset_final_sorted/CWE-264/c/good_3849_0
crossvul-cpp_data_bad_2423_5
/* * linux/arch/arm/kernel/traps.c * * Copyright (C) 1995-2009 Russell King * Fragments that appear the same as linux/arch/i386/kernel/traps.c (C) Linus Torvalds * * 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. * * 'traps.c' handles hardware exceptions after we have saved some state in * 'linux/arch/arm/lib/traps.S'. Mostly a debugging aid, but will probably * kill the offending process. */ #include <linux/signal.h> #include <linux/personality.h> #include <linux/kallsyms.h> #include <linux/spinlock.h> #include <linux/uaccess.h> #include <linux/hardirq.h> #include <linux/kdebug.h> #include <linux/module.h> #include <linux/kexec.h> #include <linux/bug.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/atomic.h> #include <asm/cacheflush.h> #include <asm/exception.h> #include <asm/unistd.h> #include <asm/traps.h> #include <asm/unwind.h> #include <asm/tls.h> #include <asm/system_misc.h> #include "signal.h" static const char *handler[]= { "prefetch abort", "data abort", "address exception", "interrupt" }; void *vectors_page; #ifdef CONFIG_DEBUG_USER unsigned int user_debug; static int __init user_debug_setup(char *str) { get_option(&str, &user_debug); return 1; } __setup("user_debug=", user_debug_setup); #endif static void dump_mem(const char *, const char *, unsigned long, unsigned long); void dump_backtrace_entry(unsigned long where, unsigned long from, unsigned long frame) { #ifdef CONFIG_KALLSYMS printk("[<%08lx>] (%pS) from [<%08lx>] (%pS)\n", where, (void *)where, from, (void *)from); #else printk("Function entered at [<%08lx>] from [<%08lx>]\n", where, from); #endif if (in_exception_text(where)) dump_mem("", "Exception stack", frame + 4, frame + 4 + sizeof(struct pt_regs)); } #ifndef CONFIG_ARM_UNWIND /* * Stack pointers should always be within the kernels view of * physical memory. If it is not there, then we can't dump * out any information relating to the stack. */ static int verify_stack(unsigned long sp) { if (sp < PAGE_OFFSET || (sp > (unsigned long)high_memory && high_memory != NULL)) return -EFAULT; return 0; } #endif /* * Dump out the contents of some memory nicely... */ static void dump_mem(const char *lvl, const char *str, unsigned long bottom, unsigned long top) { unsigned long first; mm_segment_t fs; int i; /* * We need to switch to kernel mode so that we can use __get_user * to safely read from kernel space. Note that we now dump the * code first, just in case the backtrace kills us. */ fs = get_fs(); set_fs(KERNEL_DS); printk("%s%s(0x%08lx to 0x%08lx)\n", lvl, str, bottom, top); for (first = bottom & ~31; first < top; first += 32) { unsigned long p; char str[sizeof(" 12345678") * 8 + 1]; memset(str, ' ', sizeof(str)); str[sizeof(str) - 1] = '\0'; for (p = first, i = 0; i < 8 && p < top; i++, p += 4) { if (p >= bottom && p < top) { unsigned long val; if (__get_user(val, (unsigned long *)p) == 0) sprintf(str + i * 9, " %08lx", val); else sprintf(str + i * 9, " ????????"); } } printk("%s%04lx:%s\n", lvl, first & 0xffff, str); } set_fs(fs); } static void dump_instr(const char *lvl, struct pt_regs *regs) { unsigned long addr = instruction_pointer(regs); const int thumb = thumb_mode(regs); const int width = thumb ? 4 : 8; mm_segment_t fs; char str[sizeof("00000000 ") * 5 + 2 + 1], *p = str; int i; /* * We need to switch to kernel mode so that we can use __get_user * to safely read from kernel space. Note that we now dump the * code first, just in case the backtrace kills us. */ fs = get_fs(); set_fs(KERNEL_DS); for (i = -4; i < 1 + !!thumb; i++) { unsigned int val, bad; if (thumb) bad = __get_user(val, &((u16 *)addr)[i]); else bad = __get_user(val, &((u32 *)addr)[i]); if (!bad) p += sprintf(p, i == 0 ? "(%0*x) " : "%0*x ", width, val); else { p += sprintf(p, "bad PC value"); break; } } printk("%sCode: %s\n", lvl, str); set_fs(fs); } #ifdef CONFIG_ARM_UNWIND static inline void dump_backtrace(struct pt_regs *regs, struct task_struct *tsk) { unwind_backtrace(regs, tsk); } #else static void dump_backtrace(struct pt_regs *regs, struct task_struct *tsk) { unsigned int fp, mode; int ok = 1; printk("Backtrace: "); if (!tsk) tsk = current; if (regs) { fp = regs->ARM_fp; mode = processor_mode(regs); } else if (tsk != current) { fp = thread_saved_fp(tsk); mode = 0x10; } else { asm("mov %0, fp" : "=r" (fp) : : "cc"); mode = 0x10; } if (!fp) { printk("no frame pointer"); ok = 0; } else if (verify_stack(fp)) { printk("invalid frame pointer 0x%08x", fp); ok = 0; } else if (fp < (unsigned long)end_of_stack(tsk)) printk("frame pointer underflow"); printk("\n"); if (ok) c_backtrace(fp, mode); } #endif void show_stack(struct task_struct *tsk, unsigned long *sp) { dump_backtrace(NULL, tsk); barrier(); } #ifdef CONFIG_PREEMPT #define S_PREEMPT " PREEMPT" #else #define S_PREEMPT "" #endif #ifdef CONFIG_SMP #define S_SMP " SMP" #else #define S_SMP "" #endif #ifdef CONFIG_THUMB2_KERNEL #define S_ISA " THUMB2" #else #define S_ISA " ARM" #endif static int __die(const char *str, int err, struct pt_regs *regs) { struct task_struct *tsk = current; static int die_counter; int ret; printk(KERN_EMERG "Internal error: %s: %x [#%d]" S_PREEMPT S_SMP S_ISA "\n", str, err, ++die_counter); /* trap and error numbers are mostly meaningless on ARM */ ret = notify_die(DIE_OOPS, str, regs, err, tsk->thread.trap_no, SIGSEGV); if (ret == NOTIFY_STOP) return 1; print_modules(); __show_regs(regs); printk(KERN_EMERG "Process %.*s (pid: %d, stack limit = 0x%p)\n", TASK_COMM_LEN, tsk->comm, task_pid_nr(tsk), end_of_stack(tsk)); if (!user_mode(regs) || in_interrupt()) { dump_mem(KERN_EMERG, "Stack: ", regs->ARM_sp, THREAD_SIZE + (unsigned long)task_stack_page(tsk)); dump_backtrace(regs, tsk); dump_instr(KERN_EMERG, regs); } return 0; } static arch_spinlock_t die_lock = __ARCH_SPIN_LOCK_UNLOCKED; static int die_owner = -1; static unsigned int die_nest_count; static unsigned long oops_begin(void) { int cpu; unsigned long flags; oops_enter(); /* racy, but better than risking deadlock. */ raw_local_irq_save(flags); cpu = smp_processor_id(); if (!arch_spin_trylock(&die_lock)) { if (cpu == die_owner) /* nested oops. should stop eventually */; else arch_spin_lock(&die_lock); } die_nest_count++; die_owner = cpu; console_verbose(); bust_spinlocks(1); return flags; } static void oops_end(unsigned long flags, struct pt_regs *regs, int signr) { if (regs && kexec_should_crash(current)) crash_kexec(regs); bust_spinlocks(0); die_owner = -1; add_taint(TAINT_DIE, LOCKDEP_NOW_UNRELIABLE); die_nest_count--; if (!die_nest_count) /* Nest count reaches zero, release the lock. */ arch_spin_unlock(&die_lock); raw_local_irq_restore(flags); oops_exit(); if (in_interrupt()) panic("Fatal exception in interrupt"); if (panic_on_oops) panic("Fatal exception"); if (signr) do_exit(signr); } /* * This function is protected against re-entrancy. */ void die(const char *str, struct pt_regs *regs, int err) { enum bug_trap_type bug_type = BUG_TRAP_TYPE_NONE; unsigned long flags = oops_begin(); int sig = SIGSEGV; if (!user_mode(regs)) bug_type = report_bug(regs->ARM_pc, regs); if (bug_type != BUG_TRAP_TYPE_NONE) str = "Oops - BUG"; if (__die(str, err, regs)) sig = 0; oops_end(flags, regs, sig); } void arm_notify_die(const char *str, struct pt_regs *regs, struct siginfo *info, unsigned long err, unsigned long trap) { if (user_mode(regs)) { current->thread.error_code = err; current->thread.trap_no = trap; force_sig_info(info->si_signo, info, current); } else { die(str, regs, err); } } #ifdef CONFIG_GENERIC_BUG int is_valid_bugaddr(unsigned long pc) { #ifdef CONFIG_THUMB2_KERNEL unsigned short bkpt; #else unsigned long bkpt; #endif if (probe_kernel_address((unsigned *)pc, bkpt)) return 0; return bkpt == BUG_INSTR_VALUE; } #endif static LIST_HEAD(undef_hook); static DEFINE_RAW_SPINLOCK(undef_lock); void register_undef_hook(struct undef_hook *hook) { unsigned long flags; raw_spin_lock_irqsave(&undef_lock, flags); list_add(&hook->node, &undef_hook); raw_spin_unlock_irqrestore(&undef_lock, flags); } void unregister_undef_hook(struct undef_hook *hook) { unsigned long flags; raw_spin_lock_irqsave(&undef_lock, flags); list_del(&hook->node); raw_spin_unlock_irqrestore(&undef_lock, flags); } static int call_undef_hook(struct pt_regs *regs, unsigned int instr) { struct undef_hook *hook; unsigned long flags; int (*fn)(struct pt_regs *regs, unsigned int instr) = NULL; raw_spin_lock_irqsave(&undef_lock, flags); list_for_each_entry(hook, &undef_hook, node) if ((instr & hook->instr_mask) == hook->instr_val && (regs->ARM_cpsr & hook->cpsr_mask) == hook->cpsr_val) fn = hook->fn; raw_spin_unlock_irqrestore(&undef_lock, flags); return fn ? fn(regs, instr) : 1; } asmlinkage void __exception do_undefinstr(struct pt_regs *regs) { unsigned int instr; siginfo_t info; void __user *pc; pc = (void __user *)instruction_pointer(regs); if (processor_mode(regs) == SVC_MODE) { #ifdef CONFIG_THUMB2_KERNEL if (thumb_mode(regs)) { instr = ((u16 *)pc)[0]; if (is_wide_instruction(instr)) { instr <<= 16; instr |= ((u16 *)pc)[1]; } } else #endif instr = *(u32 *) pc; } else if (thumb_mode(regs)) { if (get_user(instr, (u16 __user *)pc)) goto die_sig; if (is_wide_instruction(instr)) { unsigned int instr2; if (get_user(instr2, (u16 __user *)pc+1)) goto die_sig; instr <<= 16; instr |= instr2; } } else if (get_user(instr, (u32 __user *)pc)) { goto die_sig; } if (call_undef_hook(regs, instr) == 0) return; die_sig: #ifdef CONFIG_DEBUG_USER if (user_debug & UDBG_UNDEFINED) { printk(KERN_INFO "%s (%d): undefined instruction: pc=%p\n", current->comm, task_pid_nr(current), pc); dump_instr(KERN_INFO, regs); } #endif info.si_signo = SIGILL; info.si_errno = 0; info.si_code = ILL_ILLOPC; info.si_addr = pc; arm_notify_die("Oops - undefined instruction", regs, &info, 0, 6); } asmlinkage void do_unexp_fiq (struct pt_regs *regs) { printk("Hmm. Unexpected FIQ received, but trying to continue\n"); printk("You may have a hardware problem...\n"); } /* * bad_mode handles the impossible case in the vectors. If you see one of * these, then it's extremely serious, and could mean you have buggy hardware. * It never returns, and never tries to sync. We hope that we can at least * dump out some state information... */ asmlinkage void bad_mode(struct pt_regs *regs, int reason) { console_verbose(); printk(KERN_CRIT "Bad mode in %s handler detected\n", handler[reason]); die("Oops - bad mode", regs, 0); local_irq_disable(); panic("bad mode"); } static int bad_syscall(int n, struct pt_regs *regs) { struct thread_info *thread = current_thread_info(); siginfo_t info; if ((current->personality & PER_MASK) != PER_LINUX && thread->exec_domain->handler) { thread->exec_domain->handler(n, regs); return regs->ARM_r0; } #ifdef CONFIG_DEBUG_USER if (user_debug & UDBG_SYSCALL) { printk(KERN_ERR "[%d] %s: obsolete system call %08x.\n", task_pid_nr(current), current->comm, n); dump_instr(KERN_ERR, regs); } #endif info.si_signo = SIGILL; info.si_errno = 0; info.si_code = ILL_ILLTRP; info.si_addr = (void __user *)instruction_pointer(regs) - (thumb_mode(regs) ? 2 : 4); arm_notify_die("Oops - bad syscall", regs, &info, n, 0); return regs->ARM_r0; } static inline int do_cache_op(unsigned long start, unsigned long end, int flags) { struct mm_struct *mm = current->active_mm; struct vm_area_struct *vma; if (end < start || flags) return -EINVAL; down_read(&mm->mmap_sem); vma = find_vma(mm, start); if (vma && vma->vm_start < end) { if (start < vma->vm_start) start = vma->vm_start; if (end > vma->vm_end) end = vma->vm_end; up_read(&mm->mmap_sem); return flush_cache_user_range(start, end); } up_read(&mm->mmap_sem); return -EINVAL; } /* * Handle all unrecognised system calls. * 0x9f0000 - 0x9fffff are some more esoteric system calls */ #define NR(x) ((__ARM_NR_##x) - __ARM_NR_BASE) asmlinkage int arm_syscall(int no, struct pt_regs *regs) { struct thread_info *thread = current_thread_info(); siginfo_t info; if ((no >> 16) != (__ARM_NR_BASE>> 16)) return bad_syscall(no, regs); switch (no & 0xffff) { case 0: /* branch through 0 */ info.si_signo = SIGSEGV; info.si_errno = 0; info.si_code = SEGV_MAPERR; info.si_addr = NULL; arm_notify_die("branch through zero", regs, &info, 0, 0); return 0; case NR(breakpoint): /* SWI BREAK_POINT */ regs->ARM_pc -= thumb_mode(regs) ? 2 : 4; ptrace_break(current, regs); return regs->ARM_r0; /* * Flush a region from virtual address 'r0' to virtual address 'r1' * _exclusive_. There is no alignment requirement on either address; * user space does not need to know the hardware cache layout. * * r2 contains flags. It should ALWAYS be passed as ZERO until it * is defined to be something else. For now we ignore it, but may * the fires of hell burn in your belly if you break this rule. ;) * * (at a later date, we may want to allow this call to not flush * various aspects of the cache. Passing '0' will guarantee that * everything necessary gets flushed to maintain consistency in * the specified region). */ case NR(cacheflush): return do_cache_op(regs->ARM_r0, regs->ARM_r1, regs->ARM_r2); case NR(usr26): if (!(elf_hwcap & HWCAP_26BIT)) break; regs->ARM_cpsr &= ~MODE32_BIT; return regs->ARM_r0; case NR(usr32): if (!(elf_hwcap & HWCAP_26BIT)) break; regs->ARM_cpsr |= MODE32_BIT; return regs->ARM_r0; case NR(set_tls): thread->tp_value = regs->ARM_r0; if (tls_emu) return 0; if (has_tls_reg) { asm ("mcr p15, 0, %0, c13, c0, 3" : : "r" (regs->ARM_r0)); } else { /* * User space must never try to access this directly. * Expect your app to break eventually if you do so. * The user helper at 0xffff0fe0 must be used instead. * (see entry-armv.S for details) */ *((unsigned int *)0xffff0ff0) = regs->ARM_r0; } return 0; #ifdef CONFIG_NEEDS_SYSCALL_FOR_CMPXCHG /* * Atomically store r1 in *r2 if *r2 is equal to r0 for user space. * Return zero in r0 if *MEM was changed or non-zero if no exchange * happened. Also set the user C flag accordingly. * If access permissions have to be fixed up then non-zero is * returned and the operation has to be re-attempted. * * *NOTE*: This is a ghost syscall private to the kernel. Only the * __kuser_cmpxchg code in entry-armv.S should be aware of its * existence. Don't ever use this from user code. */ case NR(cmpxchg): for (;;) { extern void do_DataAbort(unsigned long addr, unsigned int fsr, struct pt_regs *regs); unsigned long val; unsigned long addr = regs->ARM_r2; struct mm_struct *mm = current->mm; pgd_t *pgd; pmd_t *pmd; pte_t *pte; spinlock_t *ptl; regs->ARM_cpsr &= ~PSR_C_BIT; down_read(&mm->mmap_sem); pgd = pgd_offset(mm, addr); if (!pgd_present(*pgd)) goto bad_access; pmd = pmd_offset(pgd, addr); if (!pmd_present(*pmd)) goto bad_access; pte = pte_offset_map_lock(mm, pmd, addr, &ptl); if (!pte_present(*pte) || !pte_write(*pte) || !pte_dirty(*pte)) { pte_unmap_unlock(pte, ptl); goto bad_access; } val = *(unsigned long *)addr; val -= regs->ARM_r0; if (val == 0) { *(unsigned long *)addr = regs->ARM_r1; regs->ARM_cpsr |= PSR_C_BIT; } pte_unmap_unlock(pte, ptl); up_read(&mm->mmap_sem); return val; bad_access: up_read(&mm->mmap_sem); /* simulate a write access fault */ do_DataAbort(addr, 15 + (1 << 11), regs); } #endif default: /* Calls 9f00xx..9f07ff are defined to return -ENOSYS if not implemented, rather than raising SIGILL. This way the calling program can gracefully determine whether a feature is supported. */ if ((no & 0xffff) <= 0x7ff) return -ENOSYS; break; } #ifdef CONFIG_DEBUG_USER /* * experience shows that these seem to indicate that * something catastrophic has happened */ if (user_debug & UDBG_SYSCALL) { printk("[%d] %s: arm syscall %d\n", task_pid_nr(current), current->comm, no); dump_instr("", regs); if (user_mode(regs)) { __show_regs(regs); c_backtrace(regs->ARM_fp, processor_mode(regs)); } } #endif info.si_signo = SIGILL; info.si_errno = 0; info.si_code = ILL_ILLTRP; info.si_addr = (void __user *)instruction_pointer(regs) - (thumb_mode(regs) ? 2 : 4); arm_notify_die("Oops - bad syscall(2)", regs, &info, no, 0); return 0; } #ifdef CONFIG_TLS_REG_EMUL /* * We might be running on an ARMv6+ processor which should have the TLS * register but for some reason we can't use it, or maybe an SMP system * using a pre-ARMv6 processor (there are apparently a few prototypes like * that in existence) and therefore access to that register must be * emulated. */ static int get_tp_trap(struct pt_regs *regs, unsigned int instr) { int reg = (instr >> 12) & 15; if (reg == 15) return 1; regs->uregs[reg] = current_thread_info()->tp_value; regs->ARM_pc += 4; return 0; } static struct undef_hook arm_mrc_hook = { .instr_mask = 0x0fff0fff, .instr_val = 0x0e1d0f70, .cpsr_mask = PSR_T_BIT, .cpsr_val = 0, .fn = get_tp_trap, }; static int __init arm_mrc_hook_init(void) { register_undef_hook(&arm_mrc_hook); return 0; } late_initcall(arm_mrc_hook_init); #endif void __bad_xchg(volatile void *ptr, int size) { printk("xchg: bad data size: pc 0x%p, ptr 0x%p, size %d\n", __builtin_return_address(0), ptr, size); BUG(); } EXPORT_SYMBOL(__bad_xchg); /* * A data abort trap was taken, but we did not handle the instruction. * Try to abort the user program, or panic if it was the kernel. */ asmlinkage void baddataabort(int code, unsigned long instr, struct pt_regs *regs) { unsigned long addr = instruction_pointer(regs); siginfo_t info; #ifdef CONFIG_DEBUG_USER if (user_debug & UDBG_BADABORT) { printk(KERN_ERR "[%d] %s: bad data abort: code %d instr 0x%08lx\n", task_pid_nr(current), current->comm, code, instr); dump_instr(KERN_ERR, regs); show_pte(current->mm, addr); } #endif info.si_signo = SIGILL; info.si_errno = 0; info.si_code = ILL_ILLOPC; info.si_addr = (void __user *)addr; arm_notify_die("unknown data abort code", regs, &info, instr, 0); } void __readwrite_bug(const char *fn) { printk("%s called, but not implemented\n", fn); BUG(); } EXPORT_SYMBOL(__readwrite_bug); void __pte_error(const char *file, int line, pte_t pte) { printk("%s:%d: bad pte %08llx.\n", file, line, (long long)pte_val(pte)); } void __pmd_error(const char *file, int line, pmd_t pmd) { printk("%s:%d: bad pmd %08llx.\n", file, line, (long long)pmd_val(pmd)); } void __pgd_error(const char *file, int line, pgd_t pgd) { printk("%s:%d: bad pgd %08llx.\n", file, line, (long long)pgd_val(pgd)); } asmlinkage void __div0(void) { printk("Division by zero in kernel.\n"); dump_stack(); } EXPORT_SYMBOL(__div0); void abort(void) { BUG(); /* if that doesn't kill us, halt */ panic("Oops failed to kill thread"); } EXPORT_SYMBOL(abort); void __init trap_init(void) { return; } static void __init kuser_get_tls_init(unsigned long vectors) { /* * vectors + 0xfe0 = __kuser_get_tls * vectors + 0xfe8 = hardware TLS instruction at 0xffff0fe8 */ if (tls_emu || has_tls_reg) memcpy((void *)vectors + 0xfe0, (void *)vectors + 0xfe8, 4); } void __init early_trap_init(void *vectors_base) { unsigned long vectors = (unsigned long)vectors_base; extern char __stubs_start[], __stubs_end[]; extern char __vectors_start[], __vectors_end[]; extern char __kuser_helper_start[], __kuser_helper_end[]; int kuser_sz = __kuser_helper_end - __kuser_helper_start; vectors_page = vectors_base; /* * Copy the vectors, stubs and kuser helpers (in entry-armv.S) * into the vector page, mapped at 0xffff0000, and ensure these * are visible to the instruction stream. */ memcpy((void *)vectors, __vectors_start, __vectors_end - __vectors_start); memcpy((void *)vectors + 0x200, __stubs_start, __stubs_end - __stubs_start); memcpy((void *)vectors + 0x1000 - kuser_sz, __kuser_helper_start, kuser_sz); /* * Do processor specific fixups for the kuser helpers */ kuser_get_tls_init(vectors); /* * Copy signal return handlers into the vector page, and * set sigreturn to be a pointer to these. */ memcpy((void *)(vectors + KERN_SIGRETURN_CODE - CONFIG_VECTORS_BASE), sigreturn_codes, sizeof(sigreturn_codes)); flush_icache_range(vectors, vectors + PAGE_SIZE); modify_domain(DOMAIN_USER, DOMAIN_CLIENT); }
./CrossVul/dataset_final_sorted/CWE-264/c/bad_2423_5
crossvul-cpp_data_bad_5861_26
/* * Glue Code for assembler optimized version of Camellia * * Copyright (c) 2012 Jussi Kivilinna <jussi.kivilinna@mbnet.fi> * * Camellia parts based on code by: * Copyright (C) 2006 NTT (Nippon Telegraph and Telephone Corporation) * * 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 <asm/processor.h> #include <asm/unaligned.h> #include <linux/crypto.h> #include <linux/init.h> #include <linux/module.h> #include <linux/types.h> #include <crypto/algapi.h> #include <crypto/lrw.h> #include <crypto/xts.h> #include <asm/crypto/camellia.h> #include <asm/crypto/glue_helper.h> /* regular block cipher functions */ asmlinkage void __camellia_enc_blk(struct camellia_ctx *ctx, u8 *dst, const u8 *src, bool xor); EXPORT_SYMBOL_GPL(__camellia_enc_blk); asmlinkage void camellia_dec_blk(struct camellia_ctx *ctx, u8 *dst, const u8 *src); EXPORT_SYMBOL_GPL(camellia_dec_blk); /* 2-way parallel cipher functions */ asmlinkage void __camellia_enc_blk_2way(struct camellia_ctx *ctx, u8 *dst, const u8 *src, bool xor); EXPORT_SYMBOL_GPL(__camellia_enc_blk_2way); asmlinkage void camellia_dec_blk_2way(struct camellia_ctx *ctx, u8 *dst, const u8 *src); EXPORT_SYMBOL_GPL(camellia_dec_blk_2way); static void camellia_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src) { camellia_enc_blk(crypto_tfm_ctx(tfm), dst, src); } static void camellia_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src) { camellia_dec_blk(crypto_tfm_ctx(tfm), dst, src); } /* camellia sboxes */ __visible const u64 camellia_sp10011110[256] = { 0x7000007070707000ULL, 0x8200008282828200ULL, 0x2c00002c2c2c2c00ULL, 0xec0000ecececec00ULL, 0xb30000b3b3b3b300ULL, 0x2700002727272700ULL, 0xc00000c0c0c0c000ULL, 0xe50000e5e5e5e500ULL, 0xe40000e4e4e4e400ULL, 0x8500008585858500ULL, 0x5700005757575700ULL, 0x3500003535353500ULL, 0xea0000eaeaeaea00ULL, 0x0c00000c0c0c0c00ULL, 0xae0000aeaeaeae00ULL, 0x4100004141414100ULL, 0x2300002323232300ULL, 0xef0000efefefef00ULL, 0x6b00006b6b6b6b00ULL, 0x9300009393939300ULL, 0x4500004545454500ULL, 0x1900001919191900ULL, 0xa50000a5a5a5a500ULL, 0x2100002121212100ULL, 0xed0000edededed00ULL, 0x0e00000e0e0e0e00ULL, 0x4f00004f4f4f4f00ULL, 0x4e00004e4e4e4e00ULL, 0x1d00001d1d1d1d00ULL, 0x6500006565656500ULL, 0x9200009292929200ULL, 0xbd0000bdbdbdbd00ULL, 0x8600008686868600ULL, 0xb80000b8b8b8b800ULL, 0xaf0000afafafaf00ULL, 0x8f00008f8f8f8f00ULL, 0x7c00007c7c7c7c00ULL, 0xeb0000ebebebeb00ULL, 0x1f00001f1f1f1f00ULL, 0xce0000cececece00ULL, 0x3e00003e3e3e3e00ULL, 0x3000003030303000ULL, 0xdc0000dcdcdcdc00ULL, 0x5f00005f5f5f5f00ULL, 0x5e00005e5e5e5e00ULL, 0xc50000c5c5c5c500ULL, 0x0b00000b0b0b0b00ULL, 0x1a00001a1a1a1a00ULL, 0xa60000a6a6a6a600ULL, 0xe10000e1e1e1e100ULL, 0x3900003939393900ULL, 0xca0000cacacaca00ULL, 0xd50000d5d5d5d500ULL, 0x4700004747474700ULL, 0x5d00005d5d5d5d00ULL, 0x3d00003d3d3d3d00ULL, 0xd90000d9d9d9d900ULL, 0x0100000101010100ULL, 0x5a00005a5a5a5a00ULL, 0xd60000d6d6d6d600ULL, 0x5100005151515100ULL, 0x5600005656565600ULL, 0x6c00006c6c6c6c00ULL, 0x4d00004d4d4d4d00ULL, 0x8b00008b8b8b8b00ULL, 0x0d00000d0d0d0d00ULL, 0x9a00009a9a9a9a00ULL, 0x6600006666666600ULL, 0xfb0000fbfbfbfb00ULL, 0xcc0000cccccccc00ULL, 0xb00000b0b0b0b000ULL, 0x2d00002d2d2d2d00ULL, 0x7400007474747400ULL, 0x1200001212121200ULL, 0x2b00002b2b2b2b00ULL, 0x2000002020202000ULL, 0xf00000f0f0f0f000ULL, 0xb10000b1b1b1b100ULL, 0x8400008484848400ULL, 0x9900009999999900ULL, 0xdf0000dfdfdfdf00ULL, 0x4c00004c4c4c4c00ULL, 0xcb0000cbcbcbcb00ULL, 0xc20000c2c2c2c200ULL, 0x3400003434343400ULL, 0x7e00007e7e7e7e00ULL, 0x7600007676767600ULL, 0x0500000505050500ULL, 0x6d00006d6d6d6d00ULL, 0xb70000b7b7b7b700ULL, 0xa90000a9a9a9a900ULL, 0x3100003131313100ULL, 0xd10000d1d1d1d100ULL, 0x1700001717171700ULL, 0x0400000404040400ULL, 0xd70000d7d7d7d700ULL, 0x1400001414141400ULL, 0x5800005858585800ULL, 0x3a00003a3a3a3a00ULL, 0x6100006161616100ULL, 0xde0000dededede00ULL, 0x1b00001b1b1b1b00ULL, 0x1100001111111100ULL, 0x1c00001c1c1c1c00ULL, 0x3200003232323200ULL, 0x0f00000f0f0f0f00ULL, 0x9c00009c9c9c9c00ULL, 0x1600001616161600ULL, 0x5300005353535300ULL, 0x1800001818181800ULL, 0xf20000f2f2f2f200ULL, 0x2200002222222200ULL, 0xfe0000fefefefe00ULL, 0x4400004444444400ULL, 0xcf0000cfcfcfcf00ULL, 0xb20000b2b2b2b200ULL, 0xc30000c3c3c3c300ULL, 0xb50000b5b5b5b500ULL, 0x7a00007a7a7a7a00ULL, 0x9100009191919100ULL, 0x2400002424242400ULL, 0x0800000808080800ULL, 0xe80000e8e8e8e800ULL, 0xa80000a8a8a8a800ULL, 0x6000006060606000ULL, 0xfc0000fcfcfcfc00ULL, 0x6900006969696900ULL, 0x5000005050505000ULL, 0xaa0000aaaaaaaa00ULL, 0xd00000d0d0d0d000ULL, 0xa00000a0a0a0a000ULL, 0x7d00007d7d7d7d00ULL, 0xa10000a1a1a1a100ULL, 0x8900008989898900ULL, 0x6200006262626200ULL, 0x9700009797979700ULL, 0x5400005454545400ULL, 0x5b00005b5b5b5b00ULL, 0x1e00001e1e1e1e00ULL, 0x9500009595959500ULL, 0xe00000e0e0e0e000ULL, 0xff0000ffffffff00ULL, 0x6400006464646400ULL, 0xd20000d2d2d2d200ULL, 0x1000001010101000ULL, 0xc40000c4c4c4c400ULL, 0x0000000000000000ULL, 0x4800004848484800ULL, 0xa30000a3a3a3a300ULL, 0xf70000f7f7f7f700ULL, 0x7500007575757500ULL, 0xdb0000dbdbdbdb00ULL, 0x8a00008a8a8a8a00ULL, 0x0300000303030300ULL, 0xe60000e6e6e6e600ULL, 0xda0000dadadada00ULL, 0x0900000909090900ULL, 0x3f00003f3f3f3f00ULL, 0xdd0000dddddddd00ULL, 0x9400009494949400ULL, 0x8700008787878700ULL, 0x5c00005c5c5c5c00ULL, 0x8300008383838300ULL, 0x0200000202020200ULL, 0xcd0000cdcdcdcd00ULL, 0x4a00004a4a4a4a00ULL, 0x9000009090909000ULL, 0x3300003333333300ULL, 0x7300007373737300ULL, 0x6700006767676700ULL, 0xf60000f6f6f6f600ULL, 0xf30000f3f3f3f300ULL, 0x9d00009d9d9d9d00ULL, 0x7f00007f7f7f7f00ULL, 0xbf0000bfbfbfbf00ULL, 0xe20000e2e2e2e200ULL, 0x5200005252525200ULL, 0x9b00009b9b9b9b00ULL, 0xd80000d8d8d8d800ULL, 0x2600002626262600ULL, 0xc80000c8c8c8c800ULL, 0x3700003737373700ULL, 0xc60000c6c6c6c600ULL, 0x3b00003b3b3b3b00ULL, 0x8100008181818100ULL, 0x9600009696969600ULL, 0x6f00006f6f6f6f00ULL, 0x4b00004b4b4b4b00ULL, 0x1300001313131300ULL, 0xbe0000bebebebe00ULL, 0x6300006363636300ULL, 0x2e00002e2e2e2e00ULL, 0xe90000e9e9e9e900ULL, 0x7900007979797900ULL, 0xa70000a7a7a7a700ULL, 0x8c00008c8c8c8c00ULL, 0x9f00009f9f9f9f00ULL, 0x6e00006e6e6e6e00ULL, 0xbc0000bcbcbcbc00ULL, 0x8e00008e8e8e8e00ULL, 0x2900002929292900ULL, 0xf50000f5f5f5f500ULL, 0xf90000f9f9f9f900ULL, 0xb60000b6b6b6b600ULL, 0x2f00002f2f2f2f00ULL, 0xfd0000fdfdfdfd00ULL, 0xb40000b4b4b4b400ULL, 0x5900005959595900ULL, 0x7800007878787800ULL, 0x9800009898989800ULL, 0x0600000606060600ULL, 0x6a00006a6a6a6a00ULL, 0xe70000e7e7e7e700ULL, 0x4600004646464600ULL, 0x7100007171717100ULL, 0xba0000babababa00ULL, 0xd40000d4d4d4d400ULL, 0x2500002525252500ULL, 0xab0000abababab00ULL, 0x4200004242424200ULL, 0x8800008888888800ULL, 0xa20000a2a2a2a200ULL, 0x8d00008d8d8d8d00ULL, 0xfa0000fafafafa00ULL, 0x7200007272727200ULL, 0x0700000707070700ULL, 0xb90000b9b9b9b900ULL, 0x5500005555555500ULL, 0xf80000f8f8f8f800ULL, 0xee0000eeeeeeee00ULL, 0xac0000acacacac00ULL, 0x0a00000a0a0a0a00ULL, 0x3600003636363600ULL, 0x4900004949494900ULL, 0x2a00002a2a2a2a00ULL, 0x6800006868686800ULL, 0x3c00003c3c3c3c00ULL, 0x3800003838383800ULL, 0xf10000f1f1f1f100ULL, 0xa40000a4a4a4a400ULL, 0x4000004040404000ULL, 0x2800002828282800ULL, 0xd30000d3d3d3d300ULL, 0x7b00007b7b7b7b00ULL, 0xbb0000bbbbbbbb00ULL, 0xc90000c9c9c9c900ULL, 0x4300004343434300ULL, 0xc10000c1c1c1c100ULL, 0x1500001515151500ULL, 0xe30000e3e3e3e300ULL, 0xad0000adadadad00ULL, 0xf40000f4f4f4f400ULL, 0x7700007777777700ULL, 0xc70000c7c7c7c700ULL, 0x8000008080808000ULL, 0x9e00009e9e9e9e00ULL, }; __visible const u64 camellia_sp22000222[256] = { 0xe0e0000000e0e0e0ULL, 0x0505000000050505ULL, 0x5858000000585858ULL, 0xd9d9000000d9d9d9ULL, 0x6767000000676767ULL, 0x4e4e0000004e4e4eULL, 0x8181000000818181ULL, 0xcbcb000000cbcbcbULL, 0xc9c9000000c9c9c9ULL, 0x0b0b0000000b0b0bULL, 0xaeae000000aeaeaeULL, 0x6a6a0000006a6a6aULL, 0xd5d5000000d5d5d5ULL, 0x1818000000181818ULL, 0x5d5d0000005d5d5dULL, 0x8282000000828282ULL, 0x4646000000464646ULL, 0xdfdf000000dfdfdfULL, 0xd6d6000000d6d6d6ULL, 0x2727000000272727ULL, 0x8a8a0000008a8a8aULL, 0x3232000000323232ULL, 0x4b4b0000004b4b4bULL, 0x4242000000424242ULL, 0xdbdb000000dbdbdbULL, 0x1c1c0000001c1c1cULL, 0x9e9e0000009e9e9eULL, 0x9c9c0000009c9c9cULL, 0x3a3a0000003a3a3aULL, 0xcaca000000cacacaULL, 0x2525000000252525ULL, 0x7b7b0000007b7b7bULL, 0x0d0d0000000d0d0dULL, 0x7171000000717171ULL, 0x5f5f0000005f5f5fULL, 0x1f1f0000001f1f1fULL, 0xf8f8000000f8f8f8ULL, 0xd7d7000000d7d7d7ULL, 0x3e3e0000003e3e3eULL, 0x9d9d0000009d9d9dULL, 0x7c7c0000007c7c7cULL, 0x6060000000606060ULL, 0xb9b9000000b9b9b9ULL, 0xbebe000000bebebeULL, 0xbcbc000000bcbcbcULL, 0x8b8b0000008b8b8bULL, 0x1616000000161616ULL, 0x3434000000343434ULL, 0x4d4d0000004d4d4dULL, 0xc3c3000000c3c3c3ULL, 0x7272000000727272ULL, 0x9595000000959595ULL, 0xabab000000abababULL, 0x8e8e0000008e8e8eULL, 0xbaba000000bababaULL, 0x7a7a0000007a7a7aULL, 0xb3b3000000b3b3b3ULL, 0x0202000000020202ULL, 0xb4b4000000b4b4b4ULL, 0xadad000000adadadULL, 0xa2a2000000a2a2a2ULL, 0xacac000000acacacULL, 0xd8d8000000d8d8d8ULL, 0x9a9a0000009a9a9aULL, 0x1717000000171717ULL, 0x1a1a0000001a1a1aULL, 0x3535000000353535ULL, 0xcccc000000ccccccULL, 0xf7f7000000f7f7f7ULL, 0x9999000000999999ULL, 0x6161000000616161ULL, 0x5a5a0000005a5a5aULL, 0xe8e8000000e8e8e8ULL, 0x2424000000242424ULL, 0x5656000000565656ULL, 0x4040000000404040ULL, 0xe1e1000000e1e1e1ULL, 0x6363000000636363ULL, 0x0909000000090909ULL, 0x3333000000333333ULL, 0xbfbf000000bfbfbfULL, 0x9898000000989898ULL, 0x9797000000979797ULL, 0x8585000000858585ULL, 0x6868000000686868ULL, 0xfcfc000000fcfcfcULL, 0xecec000000ecececULL, 0x0a0a0000000a0a0aULL, 0xdada000000dadadaULL, 0x6f6f0000006f6f6fULL, 0x5353000000535353ULL, 0x6262000000626262ULL, 0xa3a3000000a3a3a3ULL, 0x2e2e0000002e2e2eULL, 0x0808000000080808ULL, 0xafaf000000afafafULL, 0x2828000000282828ULL, 0xb0b0000000b0b0b0ULL, 0x7474000000747474ULL, 0xc2c2000000c2c2c2ULL, 0xbdbd000000bdbdbdULL, 0x3636000000363636ULL, 0x2222000000222222ULL, 0x3838000000383838ULL, 0x6464000000646464ULL, 0x1e1e0000001e1e1eULL, 0x3939000000393939ULL, 0x2c2c0000002c2c2cULL, 0xa6a6000000a6a6a6ULL, 0x3030000000303030ULL, 0xe5e5000000e5e5e5ULL, 0x4444000000444444ULL, 0xfdfd000000fdfdfdULL, 0x8888000000888888ULL, 0x9f9f0000009f9f9fULL, 0x6565000000656565ULL, 0x8787000000878787ULL, 0x6b6b0000006b6b6bULL, 0xf4f4000000f4f4f4ULL, 0x2323000000232323ULL, 0x4848000000484848ULL, 0x1010000000101010ULL, 0xd1d1000000d1d1d1ULL, 0x5151000000515151ULL, 0xc0c0000000c0c0c0ULL, 0xf9f9000000f9f9f9ULL, 0xd2d2000000d2d2d2ULL, 0xa0a0000000a0a0a0ULL, 0x5555000000555555ULL, 0xa1a1000000a1a1a1ULL, 0x4141000000414141ULL, 0xfafa000000fafafaULL, 0x4343000000434343ULL, 0x1313000000131313ULL, 0xc4c4000000c4c4c4ULL, 0x2f2f0000002f2f2fULL, 0xa8a8000000a8a8a8ULL, 0xb6b6000000b6b6b6ULL, 0x3c3c0000003c3c3cULL, 0x2b2b0000002b2b2bULL, 0xc1c1000000c1c1c1ULL, 0xffff000000ffffffULL, 0xc8c8000000c8c8c8ULL, 0xa5a5000000a5a5a5ULL, 0x2020000000202020ULL, 0x8989000000898989ULL, 0x0000000000000000ULL, 0x9090000000909090ULL, 0x4747000000474747ULL, 0xefef000000efefefULL, 0xeaea000000eaeaeaULL, 0xb7b7000000b7b7b7ULL, 0x1515000000151515ULL, 0x0606000000060606ULL, 0xcdcd000000cdcdcdULL, 0xb5b5000000b5b5b5ULL, 0x1212000000121212ULL, 0x7e7e0000007e7e7eULL, 0xbbbb000000bbbbbbULL, 0x2929000000292929ULL, 0x0f0f0000000f0f0fULL, 0xb8b8000000b8b8b8ULL, 0x0707000000070707ULL, 0x0404000000040404ULL, 0x9b9b0000009b9b9bULL, 0x9494000000949494ULL, 0x2121000000212121ULL, 0x6666000000666666ULL, 0xe6e6000000e6e6e6ULL, 0xcece000000cececeULL, 0xeded000000edededULL, 0xe7e7000000e7e7e7ULL, 0x3b3b0000003b3b3bULL, 0xfefe000000fefefeULL, 0x7f7f0000007f7f7fULL, 0xc5c5000000c5c5c5ULL, 0xa4a4000000a4a4a4ULL, 0x3737000000373737ULL, 0xb1b1000000b1b1b1ULL, 0x4c4c0000004c4c4cULL, 0x9191000000919191ULL, 0x6e6e0000006e6e6eULL, 0x8d8d0000008d8d8dULL, 0x7676000000767676ULL, 0x0303000000030303ULL, 0x2d2d0000002d2d2dULL, 0xdede000000dededeULL, 0x9696000000969696ULL, 0x2626000000262626ULL, 0x7d7d0000007d7d7dULL, 0xc6c6000000c6c6c6ULL, 0x5c5c0000005c5c5cULL, 0xd3d3000000d3d3d3ULL, 0xf2f2000000f2f2f2ULL, 0x4f4f0000004f4f4fULL, 0x1919000000191919ULL, 0x3f3f0000003f3f3fULL, 0xdcdc000000dcdcdcULL, 0x7979000000797979ULL, 0x1d1d0000001d1d1dULL, 0x5252000000525252ULL, 0xebeb000000ebebebULL, 0xf3f3000000f3f3f3ULL, 0x6d6d0000006d6d6dULL, 0x5e5e0000005e5e5eULL, 0xfbfb000000fbfbfbULL, 0x6969000000696969ULL, 0xb2b2000000b2b2b2ULL, 0xf0f0000000f0f0f0ULL, 0x3131000000313131ULL, 0x0c0c0000000c0c0cULL, 0xd4d4000000d4d4d4ULL, 0xcfcf000000cfcfcfULL, 0x8c8c0000008c8c8cULL, 0xe2e2000000e2e2e2ULL, 0x7575000000757575ULL, 0xa9a9000000a9a9a9ULL, 0x4a4a0000004a4a4aULL, 0x5757000000575757ULL, 0x8484000000848484ULL, 0x1111000000111111ULL, 0x4545000000454545ULL, 0x1b1b0000001b1b1bULL, 0xf5f5000000f5f5f5ULL, 0xe4e4000000e4e4e4ULL, 0x0e0e0000000e0e0eULL, 0x7373000000737373ULL, 0xaaaa000000aaaaaaULL, 0xf1f1000000f1f1f1ULL, 0xdddd000000ddddddULL, 0x5959000000595959ULL, 0x1414000000141414ULL, 0x6c6c0000006c6c6cULL, 0x9292000000929292ULL, 0x5454000000545454ULL, 0xd0d0000000d0d0d0ULL, 0x7878000000787878ULL, 0x7070000000707070ULL, 0xe3e3000000e3e3e3ULL, 0x4949000000494949ULL, 0x8080000000808080ULL, 0x5050000000505050ULL, 0xa7a7000000a7a7a7ULL, 0xf6f6000000f6f6f6ULL, 0x7777000000777777ULL, 0x9393000000939393ULL, 0x8686000000868686ULL, 0x8383000000838383ULL, 0x2a2a0000002a2a2aULL, 0xc7c7000000c7c7c7ULL, 0x5b5b0000005b5b5bULL, 0xe9e9000000e9e9e9ULL, 0xeeee000000eeeeeeULL, 0x8f8f0000008f8f8fULL, 0x0101000000010101ULL, 0x3d3d0000003d3d3dULL, }; __visible const u64 camellia_sp03303033[256] = { 0x0038380038003838ULL, 0x0041410041004141ULL, 0x0016160016001616ULL, 0x0076760076007676ULL, 0x00d9d900d900d9d9ULL, 0x0093930093009393ULL, 0x0060600060006060ULL, 0x00f2f200f200f2f2ULL, 0x0072720072007272ULL, 0x00c2c200c200c2c2ULL, 0x00abab00ab00ababULL, 0x009a9a009a009a9aULL, 0x0075750075007575ULL, 0x0006060006000606ULL, 0x0057570057005757ULL, 0x00a0a000a000a0a0ULL, 0x0091910091009191ULL, 0x00f7f700f700f7f7ULL, 0x00b5b500b500b5b5ULL, 0x00c9c900c900c9c9ULL, 0x00a2a200a200a2a2ULL, 0x008c8c008c008c8cULL, 0x00d2d200d200d2d2ULL, 0x0090900090009090ULL, 0x00f6f600f600f6f6ULL, 0x0007070007000707ULL, 0x00a7a700a700a7a7ULL, 0x0027270027002727ULL, 0x008e8e008e008e8eULL, 0x00b2b200b200b2b2ULL, 0x0049490049004949ULL, 0x00dede00de00dedeULL, 0x0043430043004343ULL, 0x005c5c005c005c5cULL, 0x00d7d700d700d7d7ULL, 0x00c7c700c700c7c7ULL, 0x003e3e003e003e3eULL, 0x00f5f500f500f5f5ULL, 0x008f8f008f008f8fULL, 0x0067670067006767ULL, 0x001f1f001f001f1fULL, 0x0018180018001818ULL, 0x006e6e006e006e6eULL, 0x00afaf00af00afafULL, 0x002f2f002f002f2fULL, 0x00e2e200e200e2e2ULL, 0x0085850085008585ULL, 0x000d0d000d000d0dULL, 0x0053530053005353ULL, 0x00f0f000f000f0f0ULL, 0x009c9c009c009c9cULL, 0x0065650065006565ULL, 0x00eaea00ea00eaeaULL, 0x00a3a300a300a3a3ULL, 0x00aeae00ae00aeaeULL, 0x009e9e009e009e9eULL, 0x00ecec00ec00ececULL, 0x0080800080008080ULL, 0x002d2d002d002d2dULL, 0x006b6b006b006b6bULL, 0x00a8a800a800a8a8ULL, 0x002b2b002b002b2bULL, 0x0036360036003636ULL, 0x00a6a600a600a6a6ULL, 0x00c5c500c500c5c5ULL, 0x0086860086008686ULL, 0x004d4d004d004d4dULL, 0x0033330033003333ULL, 0x00fdfd00fd00fdfdULL, 0x0066660066006666ULL, 0x0058580058005858ULL, 0x0096960096009696ULL, 0x003a3a003a003a3aULL, 0x0009090009000909ULL, 0x0095950095009595ULL, 0x0010100010001010ULL, 0x0078780078007878ULL, 0x00d8d800d800d8d8ULL, 0x0042420042004242ULL, 0x00cccc00cc00ccccULL, 0x00efef00ef00efefULL, 0x0026260026002626ULL, 0x00e5e500e500e5e5ULL, 0x0061610061006161ULL, 0x001a1a001a001a1aULL, 0x003f3f003f003f3fULL, 0x003b3b003b003b3bULL, 0x0082820082008282ULL, 0x00b6b600b600b6b6ULL, 0x00dbdb00db00dbdbULL, 0x00d4d400d400d4d4ULL, 0x0098980098009898ULL, 0x00e8e800e800e8e8ULL, 0x008b8b008b008b8bULL, 0x0002020002000202ULL, 0x00ebeb00eb00ebebULL, 0x000a0a000a000a0aULL, 0x002c2c002c002c2cULL, 0x001d1d001d001d1dULL, 0x00b0b000b000b0b0ULL, 0x006f6f006f006f6fULL, 0x008d8d008d008d8dULL, 0x0088880088008888ULL, 0x000e0e000e000e0eULL, 0x0019190019001919ULL, 0x0087870087008787ULL, 0x004e4e004e004e4eULL, 0x000b0b000b000b0bULL, 0x00a9a900a900a9a9ULL, 0x000c0c000c000c0cULL, 0x0079790079007979ULL, 0x0011110011001111ULL, 0x007f7f007f007f7fULL, 0x0022220022002222ULL, 0x00e7e700e700e7e7ULL, 0x0059590059005959ULL, 0x00e1e100e100e1e1ULL, 0x00dada00da00dadaULL, 0x003d3d003d003d3dULL, 0x00c8c800c800c8c8ULL, 0x0012120012001212ULL, 0x0004040004000404ULL, 0x0074740074007474ULL, 0x0054540054005454ULL, 0x0030300030003030ULL, 0x007e7e007e007e7eULL, 0x00b4b400b400b4b4ULL, 0x0028280028002828ULL, 0x0055550055005555ULL, 0x0068680068006868ULL, 0x0050500050005050ULL, 0x00bebe00be00bebeULL, 0x00d0d000d000d0d0ULL, 0x00c4c400c400c4c4ULL, 0x0031310031003131ULL, 0x00cbcb00cb00cbcbULL, 0x002a2a002a002a2aULL, 0x00adad00ad00adadULL, 0x000f0f000f000f0fULL, 0x00caca00ca00cacaULL, 0x0070700070007070ULL, 0x00ffff00ff00ffffULL, 0x0032320032003232ULL, 0x0069690069006969ULL, 0x0008080008000808ULL, 0x0062620062006262ULL, 0x0000000000000000ULL, 0x0024240024002424ULL, 0x00d1d100d100d1d1ULL, 0x00fbfb00fb00fbfbULL, 0x00baba00ba00babaULL, 0x00eded00ed00ededULL, 0x0045450045004545ULL, 0x0081810081008181ULL, 0x0073730073007373ULL, 0x006d6d006d006d6dULL, 0x0084840084008484ULL, 0x009f9f009f009f9fULL, 0x00eeee00ee00eeeeULL, 0x004a4a004a004a4aULL, 0x00c3c300c300c3c3ULL, 0x002e2e002e002e2eULL, 0x00c1c100c100c1c1ULL, 0x0001010001000101ULL, 0x00e6e600e600e6e6ULL, 0x0025250025002525ULL, 0x0048480048004848ULL, 0x0099990099009999ULL, 0x00b9b900b900b9b9ULL, 0x00b3b300b300b3b3ULL, 0x007b7b007b007b7bULL, 0x00f9f900f900f9f9ULL, 0x00cece00ce00ceceULL, 0x00bfbf00bf00bfbfULL, 0x00dfdf00df00dfdfULL, 0x0071710071007171ULL, 0x0029290029002929ULL, 0x00cdcd00cd00cdcdULL, 0x006c6c006c006c6cULL, 0x0013130013001313ULL, 0x0064640064006464ULL, 0x009b9b009b009b9bULL, 0x0063630063006363ULL, 0x009d9d009d009d9dULL, 0x00c0c000c000c0c0ULL, 0x004b4b004b004b4bULL, 0x00b7b700b700b7b7ULL, 0x00a5a500a500a5a5ULL, 0x0089890089008989ULL, 0x005f5f005f005f5fULL, 0x00b1b100b100b1b1ULL, 0x0017170017001717ULL, 0x00f4f400f400f4f4ULL, 0x00bcbc00bc00bcbcULL, 0x00d3d300d300d3d3ULL, 0x0046460046004646ULL, 0x00cfcf00cf00cfcfULL, 0x0037370037003737ULL, 0x005e5e005e005e5eULL, 0x0047470047004747ULL, 0x0094940094009494ULL, 0x00fafa00fa00fafaULL, 0x00fcfc00fc00fcfcULL, 0x005b5b005b005b5bULL, 0x0097970097009797ULL, 0x00fefe00fe00fefeULL, 0x005a5a005a005a5aULL, 0x00acac00ac00acacULL, 0x003c3c003c003c3cULL, 0x004c4c004c004c4cULL, 0x0003030003000303ULL, 0x0035350035003535ULL, 0x00f3f300f300f3f3ULL, 0x0023230023002323ULL, 0x00b8b800b800b8b8ULL, 0x005d5d005d005d5dULL, 0x006a6a006a006a6aULL, 0x0092920092009292ULL, 0x00d5d500d500d5d5ULL, 0x0021210021002121ULL, 0x0044440044004444ULL, 0x0051510051005151ULL, 0x00c6c600c600c6c6ULL, 0x007d7d007d007d7dULL, 0x0039390039003939ULL, 0x0083830083008383ULL, 0x00dcdc00dc00dcdcULL, 0x00aaaa00aa00aaaaULL, 0x007c7c007c007c7cULL, 0x0077770077007777ULL, 0x0056560056005656ULL, 0x0005050005000505ULL, 0x001b1b001b001b1bULL, 0x00a4a400a400a4a4ULL, 0x0015150015001515ULL, 0x0034340034003434ULL, 0x001e1e001e001e1eULL, 0x001c1c001c001c1cULL, 0x00f8f800f800f8f8ULL, 0x0052520052005252ULL, 0x0020200020002020ULL, 0x0014140014001414ULL, 0x00e9e900e900e9e9ULL, 0x00bdbd00bd00bdbdULL, 0x00dddd00dd00ddddULL, 0x00e4e400e400e4e4ULL, 0x00a1a100a100a1a1ULL, 0x00e0e000e000e0e0ULL, 0x008a8a008a008a8aULL, 0x00f1f100f100f1f1ULL, 0x00d6d600d600d6d6ULL, 0x007a7a007a007a7aULL, 0x00bbbb00bb00bbbbULL, 0x00e3e300e300e3e3ULL, 0x0040400040004040ULL, 0x004f4f004f004f4fULL, }; __visible const u64 camellia_sp00444404[256] = { 0x0000707070700070ULL, 0x00002c2c2c2c002cULL, 0x0000b3b3b3b300b3ULL, 0x0000c0c0c0c000c0ULL, 0x0000e4e4e4e400e4ULL, 0x0000575757570057ULL, 0x0000eaeaeaea00eaULL, 0x0000aeaeaeae00aeULL, 0x0000232323230023ULL, 0x00006b6b6b6b006bULL, 0x0000454545450045ULL, 0x0000a5a5a5a500a5ULL, 0x0000edededed00edULL, 0x00004f4f4f4f004fULL, 0x00001d1d1d1d001dULL, 0x0000929292920092ULL, 0x0000868686860086ULL, 0x0000afafafaf00afULL, 0x00007c7c7c7c007cULL, 0x00001f1f1f1f001fULL, 0x00003e3e3e3e003eULL, 0x0000dcdcdcdc00dcULL, 0x00005e5e5e5e005eULL, 0x00000b0b0b0b000bULL, 0x0000a6a6a6a600a6ULL, 0x0000393939390039ULL, 0x0000d5d5d5d500d5ULL, 0x00005d5d5d5d005dULL, 0x0000d9d9d9d900d9ULL, 0x00005a5a5a5a005aULL, 0x0000515151510051ULL, 0x00006c6c6c6c006cULL, 0x00008b8b8b8b008bULL, 0x00009a9a9a9a009aULL, 0x0000fbfbfbfb00fbULL, 0x0000b0b0b0b000b0ULL, 0x0000747474740074ULL, 0x00002b2b2b2b002bULL, 0x0000f0f0f0f000f0ULL, 0x0000848484840084ULL, 0x0000dfdfdfdf00dfULL, 0x0000cbcbcbcb00cbULL, 0x0000343434340034ULL, 0x0000767676760076ULL, 0x00006d6d6d6d006dULL, 0x0000a9a9a9a900a9ULL, 0x0000d1d1d1d100d1ULL, 0x0000040404040004ULL, 0x0000141414140014ULL, 0x00003a3a3a3a003aULL, 0x0000dededede00deULL, 0x0000111111110011ULL, 0x0000323232320032ULL, 0x00009c9c9c9c009cULL, 0x0000535353530053ULL, 0x0000f2f2f2f200f2ULL, 0x0000fefefefe00feULL, 0x0000cfcfcfcf00cfULL, 0x0000c3c3c3c300c3ULL, 0x00007a7a7a7a007aULL, 0x0000242424240024ULL, 0x0000e8e8e8e800e8ULL, 0x0000606060600060ULL, 0x0000696969690069ULL, 0x0000aaaaaaaa00aaULL, 0x0000a0a0a0a000a0ULL, 0x0000a1a1a1a100a1ULL, 0x0000626262620062ULL, 0x0000545454540054ULL, 0x00001e1e1e1e001eULL, 0x0000e0e0e0e000e0ULL, 0x0000646464640064ULL, 0x0000101010100010ULL, 0x0000000000000000ULL, 0x0000a3a3a3a300a3ULL, 0x0000757575750075ULL, 0x00008a8a8a8a008aULL, 0x0000e6e6e6e600e6ULL, 0x0000090909090009ULL, 0x0000dddddddd00ddULL, 0x0000878787870087ULL, 0x0000838383830083ULL, 0x0000cdcdcdcd00cdULL, 0x0000909090900090ULL, 0x0000737373730073ULL, 0x0000f6f6f6f600f6ULL, 0x00009d9d9d9d009dULL, 0x0000bfbfbfbf00bfULL, 0x0000525252520052ULL, 0x0000d8d8d8d800d8ULL, 0x0000c8c8c8c800c8ULL, 0x0000c6c6c6c600c6ULL, 0x0000818181810081ULL, 0x00006f6f6f6f006fULL, 0x0000131313130013ULL, 0x0000636363630063ULL, 0x0000e9e9e9e900e9ULL, 0x0000a7a7a7a700a7ULL, 0x00009f9f9f9f009fULL, 0x0000bcbcbcbc00bcULL, 0x0000292929290029ULL, 0x0000f9f9f9f900f9ULL, 0x00002f2f2f2f002fULL, 0x0000b4b4b4b400b4ULL, 0x0000787878780078ULL, 0x0000060606060006ULL, 0x0000e7e7e7e700e7ULL, 0x0000717171710071ULL, 0x0000d4d4d4d400d4ULL, 0x0000abababab00abULL, 0x0000888888880088ULL, 0x00008d8d8d8d008dULL, 0x0000727272720072ULL, 0x0000b9b9b9b900b9ULL, 0x0000f8f8f8f800f8ULL, 0x0000acacacac00acULL, 0x0000363636360036ULL, 0x00002a2a2a2a002aULL, 0x00003c3c3c3c003cULL, 0x0000f1f1f1f100f1ULL, 0x0000404040400040ULL, 0x0000d3d3d3d300d3ULL, 0x0000bbbbbbbb00bbULL, 0x0000434343430043ULL, 0x0000151515150015ULL, 0x0000adadadad00adULL, 0x0000777777770077ULL, 0x0000808080800080ULL, 0x0000828282820082ULL, 0x0000ecececec00ecULL, 0x0000272727270027ULL, 0x0000e5e5e5e500e5ULL, 0x0000858585850085ULL, 0x0000353535350035ULL, 0x00000c0c0c0c000cULL, 0x0000414141410041ULL, 0x0000efefefef00efULL, 0x0000939393930093ULL, 0x0000191919190019ULL, 0x0000212121210021ULL, 0x00000e0e0e0e000eULL, 0x00004e4e4e4e004eULL, 0x0000656565650065ULL, 0x0000bdbdbdbd00bdULL, 0x0000b8b8b8b800b8ULL, 0x00008f8f8f8f008fULL, 0x0000ebebebeb00ebULL, 0x0000cececece00ceULL, 0x0000303030300030ULL, 0x00005f5f5f5f005fULL, 0x0000c5c5c5c500c5ULL, 0x00001a1a1a1a001aULL, 0x0000e1e1e1e100e1ULL, 0x0000cacacaca00caULL, 0x0000474747470047ULL, 0x00003d3d3d3d003dULL, 0x0000010101010001ULL, 0x0000d6d6d6d600d6ULL, 0x0000565656560056ULL, 0x00004d4d4d4d004dULL, 0x00000d0d0d0d000dULL, 0x0000666666660066ULL, 0x0000cccccccc00ccULL, 0x00002d2d2d2d002dULL, 0x0000121212120012ULL, 0x0000202020200020ULL, 0x0000b1b1b1b100b1ULL, 0x0000999999990099ULL, 0x00004c4c4c4c004cULL, 0x0000c2c2c2c200c2ULL, 0x00007e7e7e7e007eULL, 0x0000050505050005ULL, 0x0000b7b7b7b700b7ULL, 0x0000313131310031ULL, 0x0000171717170017ULL, 0x0000d7d7d7d700d7ULL, 0x0000585858580058ULL, 0x0000616161610061ULL, 0x00001b1b1b1b001bULL, 0x00001c1c1c1c001cULL, 0x00000f0f0f0f000fULL, 0x0000161616160016ULL, 0x0000181818180018ULL, 0x0000222222220022ULL, 0x0000444444440044ULL, 0x0000b2b2b2b200b2ULL, 0x0000b5b5b5b500b5ULL, 0x0000919191910091ULL, 0x0000080808080008ULL, 0x0000a8a8a8a800a8ULL, 0x0000fcfcfcfc00fcULL, 0x0000505050500050ULL, 0x0000d0d0d0d000d0ULL, 0x00007d7d7d7d007dULL, 0x0000898989890089ULL, 0x0000979797970097ULL, 0x00005b5b5b5b005bULL, 0x0000959595950095ULL, 0x0000ffffffff00ffULL, 0x0000d2d2d2d200d2ULL, 0x0000c4c4c4c400c4ULL, 0x0000484848480048ULL, 0x0000f7f7f7f700f7ULL, 0x0000dbdbdbdb00dbULL, 0x0000030303030003ULL, 0x0000dadadada00daULL, 0x00003f3f3f3f003fULL, 0x0000949494940094ULL, 0x00005c5c5c5c005cULL, 0x0000020202020002ULL, 0x00004a4a4a4a004aULL, 0x0000333333330033ULL, 0x0000676767670067ULL, 0x0000f3f3f3f300f3ULL, 0x00007f7f7f7f007fULL, 0x0000e2e2e2e200e2ULL, 0x00009b9b9b9b009bULL, 0x0000262626260026ULL, 0x0000373737370037ULL, 0x00003b3b3b3b003bULL, 0x0000969696960096ULL, 0x00004b4b4b4b004bULL, 0x0000bebebebe00beULL, 0x00002e2e2e2e002eULL, 0x0000797979790079ULL, 0x00008c8c8c8c008cULL, 0x00006e6e6e6e006eULL, 0x00008e8e8e8e008eULL, 0x0000f5f5f5f500f5ULL, 0x0000b6b6b6b600b6ULL, 0x0000fdfdfdfd00fdULL, 0x0000595959590059ULL, 0x0000989898980098ULL, 0x00006a6a6a6a006aULL, 0x0000464646460046ULL, 0x0000babababa00baULL, 0x0000252525250025ULL, 0x0000424242420042ULL, 0x0000a2a2a2a200a2ULL, 0x0000fafafafa00faULL, 0x0000070707070007ULL, 0x0000555555550055ULL, 0x0000eeeeeeee00eeULL, 0x00000a0a0a0a000aULL, 0x0000494949490049ULL, 0x0000686868680068ULL, 0x0000383838380038ULL, 0x0000a4a4a4a400a4ULL, 0x0000282828280028ULL, 0x00007b7b7b7b007bULL, 0x0000c9c9c9c900c9ULL, 0x0000c1c1c1c100c1ULL, 0x0000e3e3e3e300e3ULL, 0x0000f4f4f4f400f4ULL, 0x0000c7c7c7c700c7ULL, 0x00009e9e9e9e009eULL, }; __visible const u64 camellia_sp02220222[256] = { 0x00e0e0e000e0e0e0ULL, 0x0005050500050505ULL, 0x0058585800585858ULL, 0x00d9d9d900d9d9d9ULL, 0x0067676700676767ULL, 0x004e4e4e004e4e4eULL, 0x0081818100818181ULL, 0x00cbcbcb00cbcbcbULL, 0x00c9c9c900c9c9c9ULL, 0x000b0b0b000b0b0bULL, 0x00aeaeae00aeaeaeULL, 0x006a6a6a006a6a6aULL, 0x00d5d5d500d5d5d5ULL, 0x0018181800181818ULL, 0x005d5d5d005d5d5dULL, 0x0082828200828282ULL, 0x0046464600464646ULL, 0x00dfdfdf00dfdfdfULL, 0x00d6d6d600d6d6d6ULL, 0x0027272700272727ULL, 0x008a8a8a008a8a8aULL, 0x0032323200323232ULL, 0x004b4b4b004b4b4bULL, 0x0042424200424242ULL, 0x00dbdbdb00dbdbdbULL, 0x001c1c1c001c1c1cULL, 0x009e9e9e009e9e9eULL, 0x009c9c9c009c9c9cULL, 0x003a3a3a003a3a3aULL, 0x00cacaca00cacacaULL, 0x0025252500252525ULL, 0x007b7b7b007b7b7bULL, 0x000d0d0d000d0d0dULL, 0x0071717100717171ULL, 0x005f5f5f005f5f5fULL, 0x001f1f1f001f1f1fULL, 0x00f8f8f800f8f8f8ULL, 0x00d7d7d700d7d7d7ULL, 0x003e3e3e003e3e3eULL, 0x009d9d9d009d9d9dULL, 0x007c7c7c007c7c7cULL, 0x0060606000606060ULL, 0x00b9b9b900b9b9b9ULL, 0x00bebebe00bebebeULL, 0x00bcbcbc00bcbcbcULL, 0x008b8b8b008b8b8bULL, 0x0016161600161616ULL, 0x0034343400343434ULL, 0x004d4d4d004d4d4dULL, 0x00c3c3c300c3c3c3ULL, 0x0072727200727272ULL, 0x0095959500959595ULL, 0x00ababab00abababULL, 0x008e8e8e008e8e8eULL, 0x00bababa00bababaULL, 0x007a7a7a007a7a7aULL, 0x00b3b3b300b3b3b3ULL, 0x0002020200020202ULL, 0x00b4b4b400b4b4b4ULL, 0x00adadad00adadadULL, 0x00a2a2a200a2a2a2ULL, 0x00acacac00acacacULL, 0x00d8d8d800d8d8d8ULL, 0x009a9a9a009a9a9aULL, 0x0017171700171717ULL, 0x001a1a1a001a1a1aULL, 0x0035353500353535ULL, 0x00cccccc00ccccccULL, 0x00f7f7f700f7f7f7ULL, 0x0099999900999999ULL, 0x0061616100616161ULL, 0x005a5a5a005a5a5aULL, 0x00e8e8e800e8e8e8ULL, 0x0024242400242424ULL, 0x0056565600565656ULL, 0x0040404000404040ULL, 0x00e1e1e100e1e1e1ULL, 0x0063636300636363ULL, 0x0009090900090909ULL, 0x0033333300333333ULL, 0x00bfbfbf00bfbfbfULL, 0x0098989800989898ULL, 0x0097979700979797ULL, 0x0085858500858585ULL, 0x0068686800686868ULL, 0x00fcfcfc00fcfcfcULL, 0x00ececec00ecececULL, 0x000a0a0a000a0a0aULL, 0x00dadada00dadadaULL, 0x006f6f6f006f6f6fULL, 0x0053535300535353ULL, 0x0062626200626262ULL, 0x00a3a3a300a3a3a3ULL, 0x002e2e2e002e2e2eULL, 0x0008080800080808ULL, 0x00afafaf00afafafULL, 0x0028282800282828ULL, 0x00b0b0b000b0b0b0ULL, 0x0074747400747474ULL, 0x00c2c2c200c2c2c2ULL, 0x00bdbdbd00bdbdbdULL, 0x0036363600363636ULL, 0x0022222200222222ULL, 0x0038383800383838ULL, 0x0064646400646464ULL, 0x001e1e1e001e1e1eULL, 0x0039393900393939ULL, 0x002c2c2c002c2c2cULL, 0x00a6a6a600a6a6a6ULL, 0x0030303000303030ULL, 0x00e5e5e500e5e5e5ULL, 0x0044444400444444ULL, 0x00fdfdfd00fdfdfdULL, 0x0088888800888888ULL, 0x009f9f9f009f9f9fULL, 0x0065656500656565ULL, 0x0087878700878787ULL, 0x006b6b6b006b6b6bULL, 0x00f4f4f400f4f4f4ULL, 0x0023232300232323ULL, 0x0048484800484848ULL, 0x0010101000101010ULL, 0x00d1d1d100d1d1d1ULL, 0x0051515100515151ULL, 0x00c0c0c000c0c0c0ULL, 0x00f9f9f900f9f9f9ULL, 0x00d2d2d200d2d2d2ULL, 0x00a0a0a000a0a0a0ULL, 0x0055555500555555ULL, 0x00a1a1a100a1a1a1ULL, 0x0041414100414141ULL, 0x00fafafa00fafafaULL, 0x0043434300434343ULL, 0x0013131300131313ULL, 0x00c4c4c400c4c4c4ULL, 0x002f2f2f002f2f2fULL, 0x00a8a8a800a8a8a8ULL, 0x00b6b6b600b6b6b6ULL, 0x003c3c3c003c3c3cULL, 0x002b2b2b002b2b2bULL, 0x00c1c1c100c1c1c1ULL, 0x00ffffff00ffffffULL, 0x00c8c8c800c8c8c8ULL, 0x00a5a5a500a5a5a5ULL, 0x0020202000202020ULL, 0x0089898900898989ULL, 0x0000000000000000ULL, 0x0090909000909090ULL, 0x0047474700474747ULL, 0x00efefef00efefefULL, 0x00eaeaea00eaeaeaULL, 0x00b7b7b700b7b7b7ULL, 0x0015151500151515ULL, 0x0006060600060606ULL, 0x00cdcdcd00cdcdcdULL, 0x00b5b5b500b5b5b5ULL, 0x0012121200121212ULL, 0x007e7e7e007e7e7eULL, 0x00bbbbbb00bbbbbbULL, 0x0029292900292929ULL, 0x000f0f0f000f0f0fULL, 0x00b8b8b800b8b8b8ULL, 0x0007070700070707ULL, 0x0004040400040404ULL, 0x009b9b9b009b9b9bULL, 0x0094949400949494ULL, 0x0021212100212121ULL, 0x0066666600666666ULL, 0x00e6e6e600e6e6e6ULL, 0x00cecece00cececeULL, 0x00ededed00edededULL, 0x00e7e7e700e7e7e7ULL, 0x003b3b3b003b3b3bULL, 0x00fefefe00fefefeULL, 0x007f7f7f007f7f7fULL, 0x00c5c5c500c5c5c5ULL, 0x00a4a4a400a4a4a4ULL, 0x0037373700373737ULL, 0x00b1b1b100b1b1b1ULL, 0x004c4c4c004c4c4cULL, 0x0091919100919191ULL, 0x006e6e6e006e6e6eULL, 0x008d8d8d008d8d8dULL, 0x0076767600767676ULL, 0x0003030300030303ULL, 0x002d2d2d002d2d2dULL, 0x00dedede00dededeULL, 0x0096969600969696ULL, 0x0026262600262626ULL, 0x007d7d7d007d7d7dULL, 0x00c6c6c600c6c6c6ULL, 0x005c5c5c005c5c5cULL, 0x00d3d3d300d3d3d3ULL, 0x00f2f2f200f2f2f2ULL, 0x004f4f4f004f4f4fULL, 0x0019191900191919ULL, 0x003f3f3f003f3f3fULL, 0x00dcdcdc00dcdcdcULL, 0x0079797900797979ULL, 0x001d1d1d001d1d1dULL, 0x0052525200525252ULL, 0x00ebebeb00ebebebULL, 0x00f3f3f300f3f3f3ULL, 0x006d6d6d006d6d6dULL, 0x005e5e5e005e5e5eULL, 0x00fbfbfb00fbfbfbULL, 0x0069696900696969ULL, 0x00b2b2b200b2b2b2ULL, 0x00f0f0f000f0f0f0ULL, 0x0031313100313131ULL, 0x000c0c0c000c0c0cULL, 0x00d4d4d400d4d4d4ULL, 0x00cfcfcf00cfcfcfULL, 0x008c8c8c008c8c8cULL, 0x00e2e2e200e2e2e2ULL, 0x0075757500757575ULL, 0x00a9a9a900a9a9a9ULL, 0x004a4a4a004a4a4aULL, 0x0057575700575757ULL, 0x0084848400848484ULL, 0x0011111100111111ULL, 0x0045454500454545ULL, 0x001b1b1b001b1b1bULL, 0x00f5f5f500f5f5f5ULL, 0x00e4e4e400e4e4e4ULL, 0x000e0e0e000e0e0eULL, 0x0073737300737373ULL, 0x00aaaaaa00aaaaaaULL, 0x00f1f1f100f1f1f1ULL, 0x00dddddd00ddddddULL, 0x0059595900595959ULL, 0x0014141400141414ULL, 0x006c6c6c006c6c6cULL, 0x0092929200929292ULL, 0x0054545400545454ULL, 0x00d0d0d000d0d0d0ULL, 0x0078787800787878ULL, 0x0070707000707070ULL, 0x00e3e3e300e3e3e3ULL, 0x0049494900494949ULL, 0x0080808000808080ULL, 0x0050505000505050ULL, 0x00a7a7a700a7a7a7ULL, 0x00f6f6f600f6f6f6ULL, 0x0077777700777777ULL, 0x0093939300939393ULL, 0x0086868600868686ULL, 0x0083838300838383ULL, 0x002a2a2a002a2a2aULL, 0x00c7c7c700c7c7c7ULL, 0x005b5b5b005b5b5bULL, 0x00e9e9e900e9e9e9ULL, 0x00eeeeee00eeeeeeULL, 0x008f8f8f008f8f8fULL, 0x0001010100010101ULL, 0x003d3d3d003d3d3dULL, }; __visible const u64 camellia_sp30333033[256] = { 0x3800383838003838ULL, 0x4100414141004141ULL, 0x1600161616001616ULL, 0x7600767676007676ULL, 0xd900d9d9d900d9d9ULL, 0x9300939393009393ULL, 0x6000606060006060ULL, 0xf200f2f2f200f2f2ULL, 0x7200727272007272ULL, 0xc200c2c2c200c2c2ULL, 0xab00ababab00ababULL, 0x9a009a9a9a009a9aULL, 0x7500757575007575ULL, 0x0600060606000606ULL, 0x5700575757005757ULL, 0xa000a0a0a000a0a0ULL, 0x9100919191009191ULL, 0xf700f7f7f700f7f7ULL, 0xb500b5b5b500b5b5ULL, 0xc900c9c9c900c9c9ULL, 0xa200a2a2a200a2a2ULL, 0x8c008c8c8c008c8cULL, 0xd200d2d2d200d2d2ULL, 0x9000909090009090ULL, 0xf600f6f6f600f6f6ULL, 0x0700070707000707ULL, 0xa700a7a7a700a7a7ULL, 0x2700272727002727ULL, 0x8e008e8e8e008e8eULL, 0xb200b2b2b200b2b2ULL, 0x4900494949004949ULL, 0xde00dedede00dedeULL, 0x4300434343004343ULL, 0x5c005c5c5c005c5cULL, 0xd700d7d7d700d7d7ULL, 0xc700c7c7c700c7c7ULL, 0x3e003e3e3e003e3eULL, 0xf500f5f5f500f5f5ULL, 0x8f008f8f8f008f8fULL, 0x6700676767006767ULL, 0x1f001f1f1f001f1fULL, 0x1800181818001818ULL, 0x6e006e6e6e006e6eULL, 0xaf00afafaf00afafULL, 0x2f002f2f2f002f2fULL, 0xe200e2e2e200e2e2ULL, 0x8500858585008585ULL, 0x0d000d0d0d000d0dULL, 0x5300535353005353ULL, 0xf000f0f0f000f0f0ULL, 0x9c009c9c9c009c9cULL, 0x6500656565006565ULL, 0xea00eaeaea00eaeaULL, 0xa300a3a3a300a3a3ULL, 0xae00aeaeae00aeaeULL, 0x9e009e9e9e009e9eULL, 0xec00ececec00ececULL, 0x8000808080008080ULL, 0x2d002d2d2d002d2dULL, 0x6b006b6b6b006b6bULL, 0xa800a8a8a800a8a8ULL, 0x2b002b2b2b002b2bULL, 0x3600363636003636ULL, 0xa600a6a6a600a6a6ULL, 0xc500c5c5c500c5c5ULL, 0x8600868686008686ULL, 0x4d004d4d4d004d4dULL, 0x3300333333003333ULL, 0xfd00fdfdfd00fdfdULL, 0x6600666666006666ULL, 0x5800585858005858ULL, 0x9600969696009696ULL, 0x3a003a3a3a003a3aULL, 0x0900090909000909ULL, 0x9500959595009595ULL, 0x1000101010001010ULL, 0x7800787878007878ULL, 0xd800d8d8d800d8d8ULL, 0x4200424242004242ULL, 0xcc00cccccc00ccccULL, 0xef00efefef00efefULL, 0x2600262626002626ULL, 0xe500e5e5e500e5e5ULL, 0x6100616161006161ULL, 0x1a001a1a1a001a1aULL, 0x3f003f3f3f003f3fULL, 0x3b003b3b3b003b3bULL, 0x8200828282008282ULL, 0xb600b6b6b600b6b6ULL, 0xdb00dbdbdb00dbdbULL, 0xd400d4d4d400d4d4ULL, 0x9800989898009898ULL, 0xe800e8e8e800e8e8ULL, 0x8b008b8b8b008b8bULL, 0x0200020202000202ULL, 0xeb00ebebeb00ebebULL, 0x0a000a0a0a000a0aULL, 0x2c002c2c2c002c2cULL, 0x1d001d1d1d001d1dULL, 0xb000b0b0b000b0b0ULL, 0x6f006f6f6f006f6fULL, 0x8d008d8d8d008d8dULL, 0x8800888888008888ULL, 0x0e000e0e0e000e0eULL, 0x1900191919001919ULL, 0x8700878787008787ULL, 0x4e004e4e4e004e4eULL, 0x0b000b0b0b000b0bULL, 0xa900a9a9a900a9a9ULL, 0x0c000c0c0c000c0cULL, 0x7900797979007979ULL, 0x1100111111001111ULL, 0x7f007f7f7f007f7fULL, 0x2200222222002222ULL, 0xe700e7e7e700e7e7ULL, 0x5900595959005959ULL, 0xe100e1e1e100e1e1ULL, 0xda00dadada00dadaULL, 0x3d003d3d3d003d3dULL, 0xc800c8c8c800c8c8ULL, 0x1200121212001212ULL, 0x0400040404000404ULL, 0x7400747474007474ULL, 0x5400545454005454ULL, 0x3000303030003030ULL, 0x7e007e7e7e007e7eULL, 0xb400b4b4b400b4b4ULL, 0x2800282828002828ULL, 0x5500555555005555ULL, 0x6800686868006868ULL, 0x5000505050005050ULL, 0xbe00bebebe00bebeULL, 0xd000d0d0d000d0d0ULL, 0xc400c4c4c400c4c4ULL, 0x3100313131003131ULL, 0xcb00cbcbcb00cbcbULL, 0x2a002a2a2a002a2aULL, 0xad00adadad00adadULL, 0x0f000f0f0f000f0fULL, 0xca00cacaca00cacaULL, 0x7000707070007070ULL, 0xff00ffffff00ffffULL, 0x3200323232003232ULL, 0x6900696969006969ULL, 0x0800080808000808ULL, 0x6200626262006262ULL, 0x0000000000000000ULL, 0x2400242424002424ULL, 0xd100d1d1d100d1d1ULL, 0xfb00fbfbfb00fbfbULL, 0xba00bababa00babaULL, 0xed00ededed00ededULL, 0x4500454545004545ULL, 0x8100818181008181ULL, 0x7300737373007373ULL, 0x6d006d6d6d006d6dULL, 0x8400848484008484ULL, 0x9f009f9f9f009f9fULL, 0xee00eeeeee00eeeeULL, 0x4a004a4a4a004a4aULL, 0xc300c3c3c300c3c3ULL, 0x2e002e2e2e002e2eULL, 0xc100c1c1c100c1c1ULL, 0x0100010101000101ULL, 0xe600e6e6e600e6e6ULL, 0x2500252525002525ULL, 0x4800484848004848ULL, 0x9900999999009999ULL, 0xb900b9b9b900b9b9ULL, 0xb300b3b3b300b3b3ULL, 0x7b007b7b7b007b7bULL, 0xf900f9f9f900f9f9ULL, 0xce00cecece00ceceULL, 0xbf00bfbfbf00bfbfULL, 0xdf00dfdfdf00dfdfULL, 0x7100717171007171ULL, 0x2900292929002929ULL, 0xcd00cdcdcd00cdcdULL, 0x6c006c6c6c006c6cULL, 0x1300131313001313ULL, 0x6400646464006464ULL, 0x9b009b9b9b009b9bULL, 0x6300636363006363ULL, 0x9d009d9d9d009d9dULL, 0xc000c0c0c000c0c0ULL, 0x4b004b4b4b004b4bULL, 0xb700b7b7b700b7b7ULL, 0xa500a5a5a500a5a5ULL, 0x8900898989008989ULL, 0x5f005f5f5f005f5fULL, 0xb100b1b1b100b1b1ULL, 0x1700171717001717ULL, 0xf400f4f4f400f4f4ULL, 0xbc00bcbcbc00bcbcULL, 0xd300d3d3d300d3d3ULL, 0x4600464646004646ULL, 0xcf00cfcfcf00cfcfULL, 0x3700373737003737ULL, 0x5e005e5e5e005e5eULL, 0x4700474747004747ULL, 0x9400949494009494ULL, 0xfa00fafafa00fafaULL, 0xfc00fcfcfc00fcfcULL, 0x5b005b5b5b005b5bULL, 0x9700979797009797ULL, 0xfe00fefefe00fefeULL, 0x5a005a5a5a005a5aULL, 0xac00acacac00acacULL, 0x3c003c3c3c003c3cULL, 0x4c004c4c4c004c4cULL, 0x0300030303000303ULL, 0x3500353535003535ULL, 0xf300f3f3f300f3f3ULL, 0x2300232323002323ULL, 0xb800b8b8b800b8b8ULL, 0x5d005d5d5d005d5dULL, 0x6a006a6a6a006a6aULL, 0x9200929292009292ULL, 0xd500d5d5d500d5d5ULL, 0x2100212121002121ULL, 0x4400444444004444ULL, 0x5100515151005151ULL, 0xc600c6c6c600c6c6ULL, 0x7d007d7d7d007d7dULL, 0x3900393939003939ULL, 0x8300838383008383ULL, 0xdc00dcdcdc00dcdcULL, 0xaa00aaaaaa00aaaaULL, 0x7c007c7c7c007c7cULL, 0x7700777777007777ULL, 0x5600565656005656ULL, 0x0500050505000505ULL, 0x1b001b1b1b001b1bULL, 0xa400a4a4a400a4a4ULL, 0x1500151515001515ULL, 0x3400343434003434ULL, 0x1e001e1e1e001e1eULL, 0x1c001c1c1c001c1cULL, 0xf800f8f8f800f8f8ULL, 0x5200525252005252ULL, 0x2000202020002020ULL, 0x1400141414001414ULL, 0xe900e9e9e900e9e9ULL, 0xbd00bdbdbd00bdbdULL, 0xdd00dddddd00ddddULL, 0xe400e4e4e400e4e4ULL, 0xa100a1a1a100a1a1ULL, 0xe000e0e0e000e0e0ULL, 0x8a008a8a8a008a8aULL, 0xf100f1f1f100f1f1ULL, 0xd600d6d6d600d6d6ULL, 0x7a007a7a7a007a7aULL, 0xbb00bbbbbb00bbbbULL, 0xe300e3e3e300e3e3ULL, 0x4000404040004040ULL, 0x4f004f4f4f004f4fULL, }; __visible const u64 camellia_sp44044404[256] = { 0x7070007070700070ULL, 0x2c2c002c2c2c002cULL, 0xb3b300b3b3b300b3ULL, 0xc0c000c0c0c000c0ULL, 0xe4e400e4e4e400e4ULL, 0x5757005757570057ULL, 0xeaea00eaeaea00eaULL, 0xaeae00aeaeae00aeULL, 0x2323002323230023ULL, 0x6b6b006b6b6b006bULL, 0x4545004545450045ULL, 0xa5a500a5a5a500a5ULL, 0xeded00ededed00edULL, 0x4f4f004f4f4f004fULL, 0x1d1d001d1d1d001dULL, 0x9292009292920092ULL, 0x8686008686860086ULL, 0xafaf00afafaf00afULL, 0x7c7c007c7c7c007cULL, 0x1f1f001f1f1f001fULL, 0x3e3e003e3e3e003eULL, 0xdcdc00dcdcdc00dcULL, 0x5e5e005e5e5e005eULL, 0x0b0b000b0b0b000bULL, 0xa6a600a6a6a600a6ULL, 0x3939003939390039ULL, 0xd5d500d5d5d500d5ULL, 0x5d5d005d5d5d005dULL, 0xd9d900d9d9d900d9ULL, 0x5a5a005a5a5a005aULL, 0x5151005151510051ULL, 0x6c6c006c6c6c006cULL, 0x8b8b008b8b8b008bULL, 0x9a9a009a9a9a009aULL, 0xfbfb00fbfbfb00fbULL, 0xb0b000b0b0b000b0ULL, 0x7474007474740074ULL, 0x2b2b002b2b2b002bULL, 0xf0f000f0f0f000f0ULL, 0x8484008484840084ULL, 0xdfdf00dfdfdf00dfULL, 0xcbcb00cbcbcb00cbULL, 0x3434003434340034ULL, 0x7676007676760076ULL, 0x6d6d006d6d6d006dULL, 0xa9a900a9a9a900a9ULL, 0xd1d100d1d1d100d1ULL, 0x0404000404040004ULL, 0x1414001414140014ULL, 0x3a3a003a3a3a003aULL, 0xdede00dedede00deULL, 0x1111001111110011ULL, 0x3232003232320032ULL, 0x9c9c009c9c9c009cULL, 0x5353005353530053ULL, 0xf2f200f2f2f200f2ULL, 0xfefe00fefefe00feULL, 0xcfcf00cfcfcf00cfULL, 0xc3c300c3c3c300c3ULL, 0x7a7a007a7a7a007aULL, 0x2424002424240024ULL, 0xe8e800e8e8e800e8ULL, 0x6060006060600060ULL, 0x6969006969690069ULL, 0xaaaa00aaaaaa00aaULL, 0xa0a000a0a0a000a0ULL, 0xa1a100a1a1a100a1ULL, 0x6262006262620062ULL, 0x5454005454540054ULL, 0x1e1e001e1e1e001eULL, 0xe0e000e0e0e000e0ULL, 0x6464006464640064ULL, 0x1010001010100010ULL, 0x0000000000000000ULL, 0xa3a300a3a3a300a3ULL, 0x7575007575750075ULL, 0x8a8a008a8a8a008aULL, 0xe6e600e6e6e600e6ULL, 0x0909000909090009ULL, 0xdddd00dddddd00ddULL, 0x8787008787870087ULL, 0x8383008383830083ULL, 0xcdcd00cdcdcd00cdULL, 0x9090009090900090ULL, 0x7373007373730073ULL, 0xf6f600f6f6f600f6ULL, 0x9d9d009d9d9d009dULL, 0xbfbf00bfbfbf00bfULL, 0x5252005252520052ULL, 0xd8d800d8d8d800d8ULL, 0xc8c800c8c8c800c8ULL, 0xc6c600c6c6c600c6ULL, 0x8181008181810081ULL, 0x6f6f006f6f6f006fULL, 0x1313001313130013ULL, 0x6363006363630063ULL, 0xe9e900e9e9e900e9ULL, 0xa7a700a7a7a700a7ULL, 0x9f9f009f9f9f009fULL, 0xbcbc00bcbcbc00bcULL, 0x2929002929290029ULL, 0xf9f900f9f9f900f9ULL, 0x2f2f002f2f2f002fULL, 0xb4b400b4b4b400b4ULL, 0x7878007878780078ULL, 0x0606000606060006ULL, 0xe7e700e7e7e700e7ULL, 0x7171007171710071ULL, 0xd4d400d4d4d400d4ULL, 0xabab00ababab00abULL, 0x8888008888880088ULL, 0x8d8d008d8d8d008dULL, 0x7272007272720072ULL, 0xb9b900b9b9b900b9ULL, 0xf8f800f8f8f800f8ULL, 0xacac00acacac00acULL, 0x3636003636360036ULL, 0x2a2a002a2a2a002aULL, 0x3c3c003c3c3c003cULL, 0xf1f100f1f1f100f1ULL, 0x4040004040400040ULL, 0xd3d300d3d3d300d3ULL, 0xbbbb00bbbbbb00bbULL, 0x4343004343430043ULL, 0x1515001515150015ULL, 0xadad00adadad00adULL, 0x7777007777770077ULL, 0x8080008080800080ULL, 0x8282008282820082ULL, 0xecec00ececec00ecULL, 0x2727002727270027ULL, 0xe5e500e5e5e500e5ULL, 0x8585008585850085ULL, 0x3535003535350035ULL, 0x0c0c000c0c0c000cULL, 0x4141004141410041ULL, 0xefef00efefef00efULL, 0x9393009393930093ULL, 0x1919001919190019ULL, 0x2121002121210021ULL, 0x0e0e000e0e0e000eULL, 0x4e4e004e4e4e004eULL, 0x6565006565650065ULL, 0xbdbd00bdbdbd00bdULL, 0xb8b800b8b8b800b8ULL, 0x8f8f008f8f8f008fULL, 0xebeb00ebebeb00ebULL, 0xcece00cecece00ceULL, 0x3030003030300030ULL, 0x5f5f005f5f5f005fULL, 0xc5c500c5c5c500c5ULL, 0x1a1a001a1a1a001aULL, 0xe1e100e1e1e100e1ULL, 0xcaca00cacaca00caULL, 0x4747004747470047ULL, 0x3d3d003d3d3d003dULL, 0x0101000101010001ULL, 0xd6d600d6d6d600d6ULL, 0x5656005656560056ULL, 0x4d4d004d4d4d004dULL, 0x0d0d000d0d0d000dULL, 0x6666006666660066ULL, 0xcccc00cccccc00ccULL, 0x2d2d002d2d2d002dULL, 0x1212001212120012ULL, 0x2020002020200020ULL, 0xb1b100b1b1b100b1ULL, 0x9999009999990099ULL, 0x4c4c004c4c4c004cULL, 0xc2c200c2c2c200c2ULL, 0x7e7e007e7e7e007eULL, 0x0505000505050005ULL, 0xb7b700b7b7b700b7ULL, 0x3131003131310031ULL, 0x1717001717170017ULL, 0xd7d700d7d7d700d7ULL, 0x5858005858580058ULL, 0x6161006161610061ULL, 0x1b1b001b1b1b001bULL, 0x1c1c001c1c1c001cULL, 0x0f0f000f0f0f000fULL, 0x1616001616160016ULL, 0x1818001818180018ULL, 0x2222002222220022ULL, 0x4444004444440044ULL, 0xb2b200b2b2b200b2ULL, 0xb5b500b5b5b500b5ULL, 0x9191009191910091ULL, 0x0808000808080008ULL, 0xa8a800a8a8a800a8ULL, 0xfcfc00fcfcfc00fcULL, 0x5050005050500050ULL, 0xd0d000d0d0d000d0ULL, 0x7d7d007d7d7d007dULL, 0x8989008989890089ULL, 0x9797009797970097ULL, 0x5b5b005b5b5b005bULL, 0x9595009595950095ULL, 0xffff00ffffff00ffULL, 0xd2d200d2d2d200d2ULL, 0xc4c400c4c4c400c4ULL, 0x4848004848480048ULL, 0xf7f700f7f7f700f7ULL, 0xdbdb00dbdbdb00dbULL, 0x0303000303030003ULL, 0xdada00dadada00daULL, 0x3f3f003f3f3f003fULL, 0x9494009494940094ULL, 0x5c5c005c5c5c005cULL, 0x0202000202020002ULL, 0x4a4a004a4a4a004aULL, 0x3333003333330033ULL, 0x6767006767670067ULL, 0xf3f300f3f3f300f3ULL, 0x7f7f007f7f7f007fULL, 0xe2e200e2e2e200e2ULL, 0x9b9b009b9b9b009bULL, 0x2626002626260026ULL, 0x3737003737370037ULL, 0x3b3b003b3b3b003bULL, 0x9696009696960096ULL, 0x4b4b004b4b4b004bULL, 0xbebe00bebebe00beULL, 0x2e2e002e2e2e002eULL, 0x7979007979790079ULL, 0x8c8c008c8c8c008cULL, 0x6e6e006e6e6e006eULL, 0x8e8e008e8e8e008eULL, 0xf5f500f5f5f500f5ULL, 0xb6b600b6b6b600b6ULL, 0xfdfd00fdfdfd00fdULL, 0x5959005959590059ULL, 0x9898009898980098ULL, 0x6a6a006a6a6a006aULL, 0x4646004646460046ULL, 0xbaba00bababa00baULL, 0x2525002525250025ULL, 0x4242004242420042ULL, 0xa2a200a2a2a200a2ULL, 0xfafa00fafafa00faULL, 0x0707000707070007ULL, 0x5555005555550055ULL, 0xeeee00eeeeee00eeULL, 0x0a0a000a0a0a000aULL, 0x4949004949490049ULL, 0x6868006868680068ULL, 0x3838003838380038ULL, 0xa4a400a4a4a400a4ULL, 0x2828002828280028ULL, 0x7b7b007b7b7b007bULL, 0xc9c900c9c9c900c9ULL, 0xc1c100c1c1c100c1ULL, 0xe3e300e3e3e300e3ULL, 0xf4f400f4f4f400f4ULL, 0xc7c700c7c7c700c7ULL, 0x9e9e009e9e9e009eULL, }; __visible const u64 camellia_sp11101110[256] = { 0x7070700070707000ULL, 0x8282820082828200ULL, 0x2c2c2c002c2c2c00ULL, 0xececec00ececec00ULL, 0xb3b3b300b3b3b300ULL, 0x2727270027272700ULL, 0xc0c0c000c0c0c000ULL, 0xe5e5e500e5e5e500ULL, 0xe4e4e400e4e4e400ULL, 0x8585850085858500ULL, 0x5757570057575700ULL, 0x3535350035353500ULL, 0xeaeaea00eaeaea00ULL, 0x0c0c0c000c0c0c00ULL, 0xaeaeae00aeaeae00ULL, 0x4141410041414100ULL, 0x2323230023232300ULL, 0xefefef00efefef00ULL, 0x6b6b6b006b6b6b00ULL, 0x9393930093939300ULL, 0x4545450045454500ULL, 0x1919190019191900ULL, 0xa5a5a500a5a5a500ULL, 0x2121210021212100ULL, 0xededed00ededed00ULL, 0x0e0e0e000e0e0e00ULL, 0x4f4f4f004f4f4f00ULL, 0x4e4e4e004e4e4e00ULL, 0x1d1d1d001d1d1d00ULL, 0x6565650065656500ULL, 0x9292920092929200ULL, 0xbdbdbd00bdbdbd00ULL, 0x8686860086868600ULL, 0xb8b8b800b8b8b800ULL, 0xafafaf00afafaf00ULL, 0x8f8f8f008f8f8f00ULL, 0x7c7c7c007c7c7c00ULL, 0xebebeb00ebebeb00ULL, 0x1f1f1f001f1f1f00ULL, 0xcecece00cecece00ULL, 0x3e3e3e003e3e3e00ULL, 0x3030300030303000ULL, 0xdcdcdc00dcdcdc00ULL, 0x5f5f5f005f5f5f00ULL, 0x5e5e5e005e5e5e00ULL, 0xc5c5c500c5c5c500ULL, 0x0b0b0b000b0b0b00ULL, 0x1a1a1a001a1a1a00ULL, 0xa6a6a600a6a6a600ULL, 0xe1e1e100e1e1e100ULL, 0x3939390039393900ULL, 0xcacaca00cacaca00ULL, 0xd5d5d500d5d5d500ULL, 0x4747470047474700ULL, 0x5d5d5d005d5d5d00ULL, 0x3d3d3d003d3d3d00ULL, 0xd9d9d900d9d9d900ULL, 0x0101010001010100ULL, 0x5a5a5a005a5a5a00ULL, 0xd6d6d600d6d6d600ULL, 0x5151510051515100ULL, 0x5656560056565600ULL, 0x6c6c6c006c6c6c00ULL, 0x4d4d4d004d4d4d00ULL, 0x8b8b8b008b8b8b00ULL, 0x0d0d0d000d0d0d00ULL, 0x9a9a9a009a9a9a00ULL, 0x6666660066666600ULL, 0xfbfbfb00fbfbfb00ULL, 0xcccccc00cccccc00ULL, 0xb0b0b000b0b0b000ULL, 0x2d2d2d002d2d2d00ULL, 0x7474740074747400ULL, 0x1212120012121200ULL, 0x2b2b2b002b2b2b00ULL, 0x2020200020202000ULL, 0xf0f0f000f0f0f000ULL, 0xb1b1b100b1b1b100ULL, 0x8484840084848400ULL, 0x9999990099999900ULL, 0xdfdfdf00dfdfdf00ULL, 0x4c4c4c004c4c4c00ULL, 0xcbcbcb00cbcbcb00ULL, 0xc2c2c200c2c2c200ULL, 0x3434340034343400ULL, 0x7e7e7e007e7e7e00ULL, 0x7676760076767600ULL, 0x0505050005050500ULL, 0x6d6d6d006d6d6d00ULL, 0xb7b7b700b7b7b700ULL, 0xa9a9a900a9a9a900ULL, 0x3131310031313100ULL, 0xd1d1d100d1d1d100ULL, 0x1717170017171700ULL, 0x0404040004040400ULL, 0xd7d7d700d7d7d700ULL, 0x1414140014141400ULL, 0x5858580058585800ULL, 0x3a3a3a003a3a3a00ULL, 0x6161610061616100ULL, 0xdedede00dedede00ULL, 0x1b1b1b001b1b1b00ULL, 0x1111110011111100ULL, 0x1c1c1c001c1c1c00ULL, 0x3232320032323200ULL, 0x0f0f0f000f0f0f00ULL, 0x9c9c9c009c9c9c00ULL, 0x1616160016161600ULL, 0x5353530053535300ULL, 0x1818180018181800ULL, 0xf2f2f200f2f2f200ULL, 0x2222220022222200ULL, 0xfefefe00fefefe00ULL, 0x4444440044444400ULL, 0xcfcfcf00cfcfcf00ULL, 0xb2b2b200b2b2b200ULL, 0xc3c3c300c3c3c300ULL, 0xb5b5b500b5b5b500ULL, 0x7a7a7a007a7a7a00ULL, 0x9191910091919100ULL, 0x2424240024242400ULL, 0x0808080008080800ULL, 0xe8e8e800e8e8e800ULL, 0xa8a8a800a8a8a800ULL, 0x6060600060606000ULL, 0xfcfcfc00fcfcfc00ULL, 0x6969690069696900ULL, 0x5050500050505000ULL, 0xaaaaaa00aaaaaa00ULL, 0xd0d0d000d0d0d000ULL, 0xa0a0a000a0a0a000ULL, 0x7d7d7d007d7d7d00ULL, 0xa1a1a100a1a1a100ULL, 0x8989890089898900ULL, 0x6262620062626200ULL, 0x9797970097979700ULL, 0x5454540054545400ULL, 0x5b5b5b005b5b5b00ULL, 0x1e1e1e001e1e1e00ULL, 0x9595950095959500ULL, 0xe0e0e000e0e0e000ULL, 0xffffff00ffffff00ULL, 0x6464640064646400ULL, 0xd2d2d200d2d2d200ULL, 0x1010100010101000ULL, 0xc4c4c400c4c4c400ULL, 0x0000000000000000ULL, 0x4848480048484800ULL, 0xa3a3a300a3a3a300ULL, 0xf7f7f700f7f7f700ULL, 0x7575750075757500ULL, 0xdbdbdb00dbdbdb00ULL, 0x8a8a8a008a8a8a00ULL, 0x0303030003030300ULL, 0xe6e6e600e6e6e600ULL, 0xdadada00dadada00ULL, 0x0909090009090900ULL, 0x3f3f3f003f3f3f00ULL, 0xdddddd00dddddd00ULL, 0x9494940094949400ULL, 0x8787870087878700ULL, 0x5c5c5c005c5c5c00ULL, 0x8383830083838300ULL, 0x0202020002020200ULL, 0xcdcdcd00cdcdcd00ULL, 0x4a4a4a004a4a4a00ULL, 0x9090900090909000ULL, 0x3333330033333300ULL, 0x7373730073737300ULL, 0x6767670067676700ULL, 0xf6f6f600f6f6f600ULL, 0xf3f3f300f3f3f300ULL, 0x9d9d9d009d9d9d00ULL, 0x7f7f7f007f7f7f00ULL, 0xbfbfbf00bfbfbf00ULL, 0xe2e2e200e2e2e200ULL, 0x5252520052525200ULL, 0x9b9b9b009b9b9b00ULL, 0xd8d8d800d8d8d800ULL, 0x2626260026262600ULL, 0xc8c8c800c8c8c800ULL, 0x3737370037373700ULL, 0xc6c6c600c6c6c600ULL, 0x3b3b3b003b3b3b00ULL, 0x8181810081818100ULL, 0x9696960096969600ULL, 0x6f6f6f006f6f6f00ULL, 0x4b4b4b004b4b4b00ULL, 0x1313130013131300ULL, 0xbebebe00bebebe00ULL, 0x6363630063636300ULL, 0x2e2e2e002e2e2e00ULL, 0xe9e9e900e9e9e900ULL, 0x7979790079797900ULL, 0xa7a7a700a7a7a700ULL, 0x8c8c8c008c8c8c00ULL, 0x9f9f9f009f9f9f00ULL, 0x6e6e6e006e6e6e00ULL, 0xbcbcbc00bcbcbc00ULL, 0x8e8e8e008e8e8e00ULL, 0x2929290029292900ULL, 0xf5f5f500f5f5f500ULL, 0xf9f9f900f9f9f900ULL, 0xb6b6b600b6b6b600ULL, 0x2f2f2f002f2f2f00ULL, 0xfdfdfd00fdfdfd00ULL, 0xb4b4b400b4b4b400ULL, 0x5959590059595900ULL, 0x7878780078787800ULL, 0x9898980098989800ULL, 0x0606060006060600ULL, 0x6a6a6a006a6a6a00ULL, 0xe7e7e700e7e7e700ULL, 0x4646460046464600ULL, 0x7171710071717100ULL, 0xbababa00bababa00ULL, 0xd4d4d400d4d4d400ULL, 0x2525250025252500ULL, 0xababab00ababab00ULL, 0x4242420042424200ULL, 0x8888880088888800ULL, 0xa2a2a200a2a2a200ULL, 0x8d8d8d008d8d8d00ULL, 0xfafafa00fafafa00ULL, 0x7272720072727200ULL, 0x0707070007070700ULL, 0xb9b9b900b9b9b900ULL, 0x5555550055555500ULL, 0xf8f8f800f8f8f800ULL, 0xeeeeee00eeeeee00ULL, 0xacacac00acacac00ULL, 0x0a0a0a000a0a0a00ULL, 0x3636360036363600ULL, 0x4949490049494900ULL, 0x2a2a2a002a2a2a00ULL, 0x6868680068686800ULL, 0x3c3c3c003c3c3c00ULL, 0x3838380038383800ULL, 0xf1f1f100f1f1f100ULL, 0xa4a4a400a4a4a400ULL, 0x4040400040404000ULL, 0x2828280028282800ULL, 0xd3d3d300d3d3d300ULL, 0x7b7b7b007b7b7b00ULL, 0xbbbbbb00bbbbbb00ULL, 0xc9c9c900c9c9c900ULL, 0x4343430043434300ULL, 0xc1c1c100c1c1c100ULL, 0x1515150015151500ULL, 0xe3e3e300e3e3e300ULL, 0xadadad00adadad00ULL, 0xf4f4f400f4f4f400ULL, 0x7777770077777700ULL, 0xc7c7c700c7c7c700ULL, 0x8080800080808000ULL, 0x9e9e9e009e9e9e00ULL, }; /* key constants */ #define CAMELLIA_SIGMA1L (0xA09E667FL) #define CAMELLIA_SIGMA1R (0x3BCC908BL) #define CAMELLIA_SIGMA2L (0xB67AE858L) #define CAMELLIA_SIGMA2R (0x4CAA73B2L) #define CAMELLIA_SIGMA3L (0xC6EF372FL) #define CAMELLIA_SIGMA3R (0xE94F82BEL) #define CAMELLIA_SIGMA4L (0x54FF53A5L) #define CAMELLIA_SIGMA4R (0xF1D36F1CL) #define CAMELLIA_SIGMA5L (0x10E527FAL) #define CAMELLIA_SIGMA5R (0xDE682D1DL) #define CAMELLIA_SIGMA6L (0xB05688C2L) #define CAMELLIA_SIGMA6R (0xB3E6C1FDL) /* macros */ #define ROLDQ(l, r, bits) ({ \ u64 t = l; \ l = (l << bits) | (r >> (64 - bits)); \ r = (r << bits) | (t >> (64 - bits)); \ }) #define CAMELLIA_F(x, kl, kr, y) ({ \ u64 ii = x ^ (((u64)kl << 32) | kr); \ y = camellia_sp11101110[(uint8_t)ii]; \ y ^= camellia_sp44044404[(uint8_t)(ii >> 8)]; \ ii >>= 16; \ y ^= camellia_sp30333033[(uint8_t)ii]; \ y ^= camellia_sp02220222[(uint8_t)(ii >> 8)]; \ ii >>= 16; \ y ^= camellia_sp00444404[(uint8_t)ii]; \ y ^= camellia_sp03303033[(uint8_t)(ii >> 8)]; \ ii >>= 16; \ y ^= camellia_sp22000222[(uint8_t)ii]; \ y ^= camellia_sp10011110[(uint8_t)(ii >> 8)]; \ y = ror64(y, 32); \ }) #define SET_SUBKEY_LR(INDEX, sRL) (subkey[(INDEX)] = ror64((sRL), 32)) static void camellia_setup_tail(u64 *subkey, u64 *subRL, int max) { u64 kw4, tt; u32 dw, tl, tr; /* absorb kw2 to other subkeys */ /* round 2 */ subRL[3] ^= subRL[1]; /* round 4 */ subRL[5] ^= subRL[1]; /* round 6 */ subRL[7] ^= subRL[1]; subRL[1] ^= (subRL[1] & ~subRL[9]) << 32; /* modified for FLinv(kl2) */ dw = (subRL[1] & subRL[9]) >> 32; subRL[1] ^= rol32(dw, 1); /* round 8 */ subRL[11] ^= subRL[1]; /* round 10 */ subRL[13] ^= subRL[1]; /* round 12 */ subRL[15] ^= subRL[1]; subRL[1] ^= (subRL[1] & ~subRL[17]) << 32; /* modified for FLinv(kl4) */ dw = (subRL[1] & subRL[17]) >> 32; subRL[1] ^= rol32(dw, 1); /* round 14 */ subRL[19] ^= subRL[1]; /* round 16 */ subRL[21] ^= subRL[1]; /* round 18 */ subRL[23] ^= subRL[1]; if (max == 24) { /* kw3 */ subRL[24] ^= subRL[1]; /* absorb kw4 to other subkeys */ kw4 = subRL[25]; } else { subRL[1] ^= (subRL[1] & ~subRL[25]) << 32; /* modified for FLinv(kl6) */ dw = (subRL[1] & subRL[25]) >> 32; subRL[1] ^= rol32(dw, 1); /* round 20 */ subRL[27] ^= subRL[1]; /* round 22 */ subRL[29] ^= subRL[1]; /* round 24 */ subRL[31] ^= subRL[1]; /* kw3 */ subRL[32] ^= subRL[1]; /* absorb kw4 to other subkeys */ kw4 = subRL[33]; /* round 23 */ subRL[30] ^= kw4; /* round 21 */ subRL[28] ^= kw4; /* round 19 */ subRL[26] ^= kw4; kw4 ^= (kw4 & ~subRL[24]) << 32; /* modified for FL(kl5) */ dw = (kw4 & subRL[24]) >> 32; kw4 ^= rol32(dw, 1); } /* round 17 */ subRL[22] ^= kw4; /* round 15 */ subRL[20] ^= kw4; /* round 13 */ subRL[18] ^= kw4; kw4 ^= (kw4 & ~subRL[16]) << 32; /* modified for FL(kl3) */ dw = (kw4 & subRL[16]) >> 32; kw4 ^= rol32(dw, 1); /* round 11 */ subRL[14] ^= kw4; /* round 9 */ subRL[12] ^= kw4; /* round 7 */ subRL[10] ^= kw4; kw4 ^= (kw4 & ~subRL[8]) << 32; /* modified for FL(kl1) */ dw = (kw4 & subRL[8]) >> 32; kw4 ^= rol32(dw, 1); /* round 5 */ subRL[6] ^= kw4; /* round 3 */ subRL[4] ^= kw4; /* round 1 */ subRL[2] ^= kw4; /* kw1 */ subRL[0] ^= kw4; /* key XOR is end of F-function */ SET_SUBKEY_LR(0, subRL[0] ^ subRL[2]); /* kw1 */ SET_SUBKEY_LR(2, subRL[3]); /* round 1 */ SET_SUBKEY_LR(3, subRL[2] ^ subRL[4]); /* round 2 */ SET_SUBKEY_LR(4, subRL[3] ^ subRL[5]); /* round 3 */ SET_SUBKEY_LR(5, subRL[4] ^ subRL[6]); /* round 4 */ SET_SUBKEY_LR(6, subRL[5] ^ subRL[7]); /* round 5 */ tl = (subRL[10] >> 32) ^ (subRL[10] & ~subRL[8]); dw = tl & (subRL[8] >> 32); /* FL(kl1) */ tr = subRL[10] ^ rol32(dw, 1); tt = (tr | ((u64)tl << 32)); SET_SUBKEY_LR(7, subRL[6] ^ tt); /* round 6 */ SET_SUBKEY_LR(8, subRL[8]); /* FL(kl1) */ SET_SUBKEY_LR(9, subRL[9]); /* FLinv(kl2) */ tl = (subRL[7] >> 32) ^ (subRL[7] & ~subRL[9]); dw = tl & (subRL[9] >> 32); /* FLinv(kl2) */ tr = subRL[7] ^ rol32(dw, 1); tt = (tr | ((u64)tl << 32)); SET_SUBKEY_LR(10, subRL[11] ^ tt); /* round 7 */ SET_SUBKEY_LR(11, subRL[10] ^ subRL[12]); /* round 8 */ SET_SUBKEY_LR(12, subRL[11] ^ subRL[13]); /* round 9 */ SET_SUBKEY_LR(13, subRL[12] ^ subRL[14]); /* round 10 */ SET_SUBKEY_LR(14, subRL[13] ^ subRL[15]); /* round 11 */ tl = (subRL[18] >> 32) ^ (subRL[18] & ~subRL[16]); dw = tl & (subRL[16] >> 32); /* FL(kl3) */ tr = subRL[18] ^ rol32(dw, 1); tt = (tr | ((u64)tl << 32)); SET_SUBKEY_LR(15, subRL[14] ^ tt); /* round 12 */ SET_SUBKEY_LR(16, subRL[16]); /* FL(kl3) */ SET_SUBKEY_LR(17, subRL[17]); /* FLinv(kl4) */ tl = (subRL[15] >> 32) ^ (subRL[15] & ~subRL[17]); dw = tl & (subRL[17] >> 32); /* FLinv(kl4) */ tr = subRL[15] ^ rol32(dw, 1); tt = (tr | ((u64)tl << 32)); SET_SUBKEY_LR(18, subRL[19] ^ tt); /* round 13 */ SET_SUBKEY_LR(19, subRL[18] ^ subRL[20]); /* round 14 */ SET_SUBKEY_LR(20, subRL[19] ^ subRL[21]); /* round 15 */ SET_SUBKEY_LR(21, subRL[20] ^ subRL[22]); /* round 16 */ SET_SUBKEY_LR(22, subRL[21] ^ subRL[23]); /* round 17 */ if (max == 24) { SET_SUBKEY_LR(23, subRL[22]); /* round 18 */ SET_SUBKEY_LR(24, subRL[24] ^ subRL[23]); /* kw3 */ } else { tl = (subRL[26] >> 32) ^ (subRL[26] & ~subRL[24]); dw = tl & (subRL[24] >> 32); /* FL(kl5) */ tr = subRL[26] ^ rol32(dw, 1); tt = (tr | ((u64)tl << 32)); SET_SUBKEY_LR(23, subRL[22] ^ tt); /* round 18 */ SET_SUBKEY_LR(24, subRL[24]); /* FL(kl5) */ SET_SUBKEY_LR(25, subRL[25]); /* FLinv(kl6) */ tl = (subRL[23] >> 32) ^ (subRL[23] & ~subRL[25]); dw = tl & (subRL[25] >> 32); /* FLinv(kl6) */ tr = subRL[23] ^ rol32(dw, 1); tt = (tr | ((u64)tl << 32)); SET_SUBKEY_LR(26, subRL[27] ^ tt); /* round 19 */ SET_SUBKEY_LR(27, subRL[26] ^ subRL[28]); /* round 20 */ SET_SUBKEY_LR(28, subRL[27] ^ subRL[29]); /* round 21 */ SET_SUBKEY_LR(29, subRL[28] ^ subRL[30]); /* round 22 */ SET_SUBKEY_LR(30, subRL[29] ^ subRL[31]); /* round 23 */ SET_SUBKEY_LR(31, subRL[30]); /* round 24 */ SET_SUBKEY_LR(32, subRL[32] ^ subRL[31]); /* kw3 */ } } static void camellia_setup128(const unsigned char *key, u64 *subkey) { u64 kl, kr, ww; u64 subRL[26]; /** * k == kl || kr (|| is concatenation) */ kl = get_unaligned_be64(key); kr = get_unaligned_be64(key + 8); /* generate KL dependent subkeys */ /* kw1 */ subRL[0] = kl; /* kw2 */ subRL[1] = kr; /* rotation left shift 15bit */ ROLDQ(kl, kr, 15); /* k3 */ subRL[4] = kl; /* k4 */ subRL[5] = kr; /* rotation left shift 15+30bit */ ROLDQ(kl, kr, 30); /* k7 */ subRL[10] = kl; /* k8 */ subRL[11] = kr; /* rotation left shift 15+30+15bit */ ROLDQ(kl, kr, 15); /* k10 */ subRL[13] = kr; /* rotation left shift 15+30+15+17 bit */ ROLDQ(kl, kr, 17); /* kl3 */ subRL[16] = kl; /* kl4 */ subRL[17] = kr; /* rotation left shift 15+30+15+17+17 bit */ ROLDQ(kl, kr, 17); /* k13 */ subRL[18] = kl; /* k14 */ subRL[19] = kr; /* rotation left shift 15+30+15+17+17+17 bit */ ROLDQ(kl, kr, 17); /* k17 */ subRL[22] = kl; /* k18 */ subRL[23] = kr; /* generate KA */ kl = subRL[0]; kr = subRL[1]; CAMELLIA_F(kl, CAMELLIA_SIGMA1L, CAMELLIA_SIGMA1R, ww); kr ^= ww; CAMELLIA_F(kr, CAMELLIA_SIGMA2L, CAMELLIA_SIGMA2R, kl); /* current status == (kll, klr, w0, w1) */ CAMELLIA_F(kl, CAMELLIA_SIGMA3L, CAMELLIA_SIGMA3R, kr); kr ^= ww; CAMELLIA_F(kr, CAMELLIA_SIGMA4L, CAMELLIA_SIGMA4R, ww); kl ^= ww; /* generate KA dependent subkeys */ /* k1, k2 */ subRL[2] = kl; subRL[3] = kr; ROLDQ(kl, kr, 15); /* k5,k6 */ subRL[6] = kl; subRL[7] = kr; ROLDQ(kl, kr, 15); /* kl1, kl2 */ subRL[8] = kl; subRL[9] = kr; ROLDQ(kl, kr, 15); /* k9 */ subRL[12] = kl; ROLDQ(kl, kr, 15); /* k11, k12 */ subRL[14] = kl; subRL[15] = kr; ROLDQ(kl, kr, 34); /* k15, k16 */ subRL[20] = kl; subRL[21] = kr; ROLDQ(kl, kr, 17); /* kw3, kw4 */ subRL[24] = kl; subRL[25] = kr; camellia_setup_tail(subkey, subRL, 24); } static void camellia_setup256(const unsigned char *key, u64 *subkey) { u64 kl, kr; /* left half of key */ u64 krl, krr; /* right half of key */ u64 ww; /* temporary variables */ u64 subRL[34]; /** * key = (kl || kr || krl || krr) (|| is concatenation) */ kl = get_unaligned_be64(key); kr = get_unaligned_be64(key + 8); krl = get_unaligned_be64(key + 16); krr = get_unaligned_be64(key + 24); /* generate KL dependent subkeys */ /* kw1 */ subRL[0] = kl; /* kw2 */ subRL[1] = kr; ROLDQ(kl, kr, 45); /* k9 */ subRL[12] = kl; /* k10 */ subRL[13] = kr; ROLDQ(kl, kr, 15); /* kl3 */ subRL[16] = kl; /* kl4 */ subRL[17] = kr; ROLDQ(kl, kr, 17); /* k17 */ subRL[22] = kl; /* k18 */ subRL[23] = kr; ROLDQ(kl, kr, 34); /* k23 */ subRL[30] = kl; /* k24 */ subRL[31] = kr; /* generate KR dependent subkeys */ ROLDQ(krl, krr, 15); /* k3 */ subRL[4] = krl; /* k4 */ subRL[5] = krr; ROLDQ(krl, krr, 15); /* kl1 */ subRL[8] = krl; /* kl2 */ subRL[9] = krr; ROLDQ(krl, krr, 30); /* k13 */ subRL[18] = krl; /* k14 */ subRL[19] = krr; ROLDQ(krl, krr, 34); /* k19 */ subRL[26] = krl; /* k20 */ subRL[27] = krr; ROLDQ(krl, krr, 34); /* generate KA */ kl = subRL[0] ^ krl; kr = subRL[1] ^ krr; CAMELLIA_F(kl, CAMELLIA_SIGMA1L, CAMELLIA_SIGMA1R, ww); kr ^= ww; CAMELLIA_F(kr, CAMELLIA_SIGMA2L, CAMELLIA_SIGMA2R, kl); kl ^= krl; CAMELLIA_F(kl, CAMELLIA_SIGMA3L, CAMELLIA_SIGMA3R, kr); kr ^= ww ^ krr; CAMELLIA_F(kr, CAMELLIA_SIGMA4L, CAMELLIA_SIGMA4R, ww); kl ^= ww; /* generate KB */ krl ^= kl; krr ^= kr; CAMELLIA_F(krl, CAMELLIA_SIGMA5L, CAMELLIA_SIGMA5R, ww); krr ^= ww; CAMELLIA_F(krr, CAMELLIA_SIGMA6L, CAMELLIA_SIGMA6R, ww); krl ^= ww; /* generate KA dependent subkeys */ ROLDQ(kl, kr, 15); /* k5 */ subRL[6] = kl; /* k6 */ subRL[7] = kr; ROLDQ(kl, kr, 30); /* k11 */ subRL[14] = kl; /* k12 */ subRL[15] = kr; /* rotation left shift 32bit */ ROLDQ(kl, kr, 32); /* kl5 */ subRL[24] = kl; /* kl6 */ subRL[25] = kr; /* rotation left shift 17 from k11,k12 -> k21,k22 */ ROLDQ(kl, kr, 17); /* k21 */ subRL[28] = kl; /* k22 */ subRL[29] = kr; /* generate KB dependent subkeys */ /* k1 */ subRL[2] = krl; /* k2 */ subRL[3] = krr; ROLDQ(krl, krr, 30); /* k7 */ subRL[10] = krl; /* k8 */ subRL[11] = krr; ROLDQ(krl, krr, 30); /* k15 */ subRL[20] = krl; /* k16 */ subRL[21] = krr; ROLDQ(krl, krr, 51); /* kw3 */ subRL[32] = krl; /* kw4 */ subRL[33] = krr; camellia_setup_tail(subkey, subRL, 32); } static void camellia_setup192(const unsigned char *key, u64 *subkey) { unsigned char kk[32]; u64 krl, krr; memcpy(kk, key, 24); memcpy((unsigned char *)&krl, key+16, 8); krr = ~krl; memcpy(kk+24, (unsigned char *)&krr, 8); camellia_setup256(kk, subkey); } int __camellia_setkey(struct camellia_ctx *cctx, const unsigned char *key, unsigned int key_len, u32 *flags) { if (key_len != 16 && key_len != 24 && key_len != 32) { *flags |= CRYPTO_TFM_RES_BAD_KEY_LEN; return -EINVAL; } cctx->key_length = key_len; switch (key_len) { case 16: camellia_setup128(key, cctx->key_table); break; case 24: camellia_setup192(key, cctx->key_table); break; case 32: camellia_setup256(key, cctx->key_table); break; } return 0; } EXPORT_SYMBOL_GPL(__camellia_setkey); static int camellia_setkey(struct crypto_tfm *tfm, const u8 *in_key, unsigned int key_len) { return __camellia_setkey(crypto_tfm_ctx(tfm), in_key, key_len, &tfm->crt_flags); } void camellia_decrypt_cbc_2way(void *ctx, u128 *dst, const u128 *src) { u128 iv = *src; camellia_dec_blk_2way(ctx, (u8 *)dst, (u8 *)src); u128_xor(&dst[1], &dst[1], &iv); } EXPORT_SYMBOL_GPL(camellia_decrypt_cbc_2way); void camellia_crypt_ctr(void *ctx, u128 *dst, const u128 *src, le128 *iv) { be128 ctrblk; if (dst != src) *dst = *src; le128_to_be128(&ctrblk, iv); le128_inc(iv); camellia_enc_blk_xor(ctx, (u8 *)dst, (u8 *)&ctrblk); } EXPORT_SYMBOL_GPL(camellia_crypt_ctr); void camellia_crypt_ctr_2way(void *ctx, u128 *dst, const u128 *src, le128 *iv) { be128 ctrblks[2]; if (dst != src) { dst[0] = src[0]; dst[1] = src[1]; } le128_to_be128(&ctrblks[0], iv); le128_inc(iv); le128_to_be128(&ctrblks[1], iv); le128_inc(iv); camellia_enc_blk_xor_2way(ctx, (u8 *)dst, (u8 *)ctrblks); } EXPORT_SYMBOL_GPL(camellia_crypt_ctr_2way); static const struct common_glue_ctx camellia_enc = { .num_funcs = 2, .fpu_blocks_limit = -1, .funcs = { { .num_blocks = 2, .fn_u = { .ecb = GLUE_FUNC_CAST(camellia_enc_blk_2way) } }, { .num_blocks = 1, .fn_u = { .ecb = GLUE_FUNC_CAST(camellia_enc_blk) } } } }; static const struct common_glue_ctx camellia_ctr = { .num_funcs = 2, .fpu_blocks_limit = -1, .funcs = { { .num_blocks = 2, .fn_u = { .ctr = GLUE_CTR_FUNC_CAST(camellia_crypt_ctr_2way) } }, { .num_blocks = 1, .fn_u = { .ctr = GLUE_CTR_FUNC_CAST(camellia_crypt_ctr) } } } }; static const struct common_glue_ctx camellia_dec = { .num_funcs = 2, .fpu_blocks_limit = -1, .funcs = { { .num_blocks = 2, .fn_u = { .ecb = GLUE_FUNC_CAST(camellia_dec_blk_2way) } }, { .num_blocks = 1, .fn_u = { .ecb = GLUE_FUNC_CAST(camellia_dec_blk) } } } }; static const struct common_glue_ctx camellia_dec_cbc = { .num_funcs = 2, .fpu_blocks_limit = -1, .funcs = { { .num_blocks = 2, .fn_u = { .cbc = GLUE_CBC_FUNC_CAST(camellia_decrypt_cbc_2way) } }, { .num_blocks = 1, .fn_u = { .cbc = GLUE_CBC_FUNC_CAST(camellia_dec_blk) } } } }; static int ecb_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_ecb_crypt_128bit(&camellia_enc, desc, dst, src, nbytes); } static int ecb_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_ecb_crypt_128bit(&camellia_dec, desc, dst, src, nbytes); } static int cbc_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_cbc_encrypt_128bit(GLUE_FUNC_CAST(camellia_enc_blk), desc, dst, src, nbytes); } static int cbc_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_cbc_decrypt_128bit(&camellia_dec_cbc, desc, dst, src, nbytes); } static int ctr_crypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_ctr_crypt_128bit(&camellia_ctr, desc, dst, src, nbytes); } static void encrypt_callback(void *priv, u8 *srcdst, unsigned int nbytes) { const unsigned int bsize = CAMELLIA_BLOCK_SIZE; struct camellia_ctx *ctx = priv; int i; while (nbytes >= 2 * bsize) { camellia_enc_blk_2way(ctx, srcdst, srcdst); srcdst += bsize * 2; nbytes -= bsize * 2; } for (i = 0; i < nbytes / bsize; i++, srcdst += bsize) camellia_enc_blk(ctx, srcdst, srcdst); } static void decrypt_callback(void *priv, u8 *srcdst, unsigned int nbytes) { const unsigned int bsize = CAMELLIA_BLOCK_SIZE; struct camellia_ctx *ctx = priv; int i; while (nbytes >= 2 * bsize) { camellia_dec_blk_2way(ctx, srcdst, srcdst); srcdst += bsize * 2; nbytes -= bsize * 2; } for (i = 0; i < nbytes / bsize; i++, srcdst += bsize) camellia_dec_blk(ctx, srcdst, srcdst); } int lrw_camellia_setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen) { struct camellia_lrw_ctx *ctx = crypto_tfm_ctx(tfm); int err; err = __camellia_setkey(&ctx->camellia_ctx, key, keylen - CAMELLIA_BLOCK_SIZE, &tfm->crt_flags); if (err) return err; return lrw_init_table(&ctx->lrw_table, key + keylen - CAMELLIA_BLOCK_SIZE); } EXPORT_SYMBOL_GPL(lrw_camellia_setkey); static int lrw_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct camellia_lrw_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); be128 buf[2 * 4]; struct lrw_crypt_req req = { .tbuf = buf, .tbuflen = sizeof(buf), .table_ctx = &ctx->lrw_table, .crypt_ctx = &ctx->camellia_ctx, .crypt_fn = encrypt_callback, }; return lrw_crypt(desc, dst, src, nbytes, &req); } static int lrw_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct camellia_lrw_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); be128 buf[2 * 4]; struct lrw_crypt_req req = { .tbuf = buf, .tbuflen = sizeof(buf), .table_ctx = &ctx->lrw_table, .crypt_ctx = &ctx->camellia_ctx, .crypt_fn = decrypt_callback, }; return lrw_crypt(desc, dst, src, nbytes, &req); } void lrw_camellia_exit_tfm(struct crypto_tfm *tfm) { struct camellia_lrw_ctx *ctx = crypto_tfm_ctx(tfm); lrw_free_table(&ctx->lrw_table); } EXPORT_SYMBOL_GPL(lrw_camellia_exit_tfm); int xts_camellia_setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen) { struct camellia_xts_ctx *ctx = crypto_tfm_ctx(tfm); u32 *flags = &tfm->crt_flags; int err; /* key consists of keys of equal size concatenated, therefore * the length must be even */ if (keylen % 2) { *flags |= CRYPTO_TFM_RES_BAD_KEY_LEN; return -EINVAL; } /* first half of xts-key is for crypt */ err = __camellia_setkey(&ctx->crypt_ctx, key, keylen / 2, flags); if (err) return err; /* second half of xts-key is for tweak */ return __camellia_setkey(&ctx->tweak_ctx, key + keylen / 2, keylen / 2, flags); } EXPORT_SYMBOL_GPL(xts_camellia_setkey); static int xts_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct camellia_xts_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); be128 buf[2 * 4]; struct xts_crypt_req req = { .tbuf = buf, .tbuflen = sizeof(buf), .tweak_ctx = &ctx->tweak_ctx, .tweak_fn = XTS_TWEAK_CAST(camellia_enc_blk), .crypt_ctx = &ctx->crypt_ctx, .crypt_fn = encrypt_callback, }; return xts_crypt(desc, dst, src, nbytes, &req); } static int xts_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct camellia_xts_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); be128 buf[2 * 4]; struct xts_crypt_req req = { .tbuf = buf, .tbuflen = sizeof(buf), .tweak_ctx = &ctx->tweak_ctx, .tweak_fn = XTS_TWEAK_CAST(camellia_enc_blk), .crypt_ctx = &ctx->crypt_ctx, .crypt_fn = decrypt_callback, }; return xts_crypt(desc, dst, src, nbytes, &req); } static struct crypto_alg camellia_algs[6] = { { .cra_name = "camellia", .cra_driver_name = "camellia-asm", .cra_priority = 200, .cra_flags = CRYPTO_ALG_TYPE_CIPHER, .cra_blocksize = CAMELLIA_BLOCK_SIZE, .cra_ctxsize = sizeof(struct camellia_ctx), .cra_alignmask = 0, .cra_module = THIS_MODULE, .cra_u = { .cipher = { .cia_min_keysize = CAMELLIA_MIN_KEY_SIZE, .cia_max_keysize = CAMELLIA_MAX_KEY_SIZE, .cia_setkey = camellia_setkey, .cia_encrypt = camellia_encrypt, .cia_decrypt = camellia_decrypt } } }, { .cra_name = "ecb(camellia)", .cra_driver_name = "ecb-camellia-asm", .cra_priority = 300, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = CAMELLIA_BLOCK_SIZE, .cra_ctxsize = sizeof(struct camellia_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = CAMELLIA_MIN_KEY_SIZE, .max_keysize = CAMELLIA_MAX_KEY_SIZE, .setkey = camellia_setkey, .encrypt = ecb_encrypt, .decrypt = ecb_decrypt, }, }, }, { .cra_name = "cbc(camellia)", .cra_driver_name = "cbc-camellia-asm", .cra_priority = 300, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = CAMELLIA_BLOCK_SIZE, .cra_ctxsize = sizeof(struct camellia_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = CAMELLIA_MIN_KEY_SIZE, .max_keysize = CAMELLIA_MAX_KEY_SIZE, .ivsize = CAMELLIA_BLOCK_SIZE, .setkey = camellia_setkey, .encrypt = cbc_encrypt, .decrypt = cbc_decrypt, }, }, }, { .cra_name = "ctr(camellia)", .cra_driver_name = "ctr-camellia-asm", .cra_priority = 300, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = 1, .cra_ctxsize = sizeof(struct camellia_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = CAMELLIA_MIN_KEY_SIZE, .max_keysize = CAMELLIA_MAX_KEY_SIZE, .ivsize = CAMELLIA_BLOCK_SIZE, .setkey = camellia_setkey, .encrypt = ctr_crypt, .decrypt = ctr_crypt, }, }, }, { .cra_name = "lrw(camellia)", .cra_driver_name = "lrw-camellia-asm", .cra_priority = 300, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = CAMELLIA_BLOCK_SIZE, .cra_ctxsize = sizeof(struct camellia_lrw_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_exit = lrw_camellia_exit_tfm, .cra_u = { .blkcipher = { .min_keysize = CAMELLIA_MIN_KEY_SIZE + CAMELLIA_BLOCK_SIZE, .max_keysize = CAMELLIA_MAX_KEY_SIZE + CAMELLIA_BLOCK_SIZE, .ivsize = CAMELLIA_BLOCK_SIZE, .setkey = lrw_camellia_setkey, .encrypt = lrw_encrypt, .decrypt = lrw_decrypt, }, }, }, { .cra_name = "xts(camellia)", .cra_driver_name = "xts-camellia-asm", .cra_priority = 300, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = CAMELLIA_BLOCK_SIZE, .cra_ctxsize = sizeof(struct camellia_xts_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = CAMELLIA_MIN_KEY_SIZE * 2, .max_keysize = CAMELLIA_MAX_KEY_SIZE * 2, .ivsize = CAMELLIA_BLOCK_SIZE, .setkey = xts_camellia_setkey, .encrypt = xts_encrypt, .decrypt = xts_decrypt, }, }, } }; static bool is_blacklisted_cpu(void) { if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL) return false; if (boot_cpu_data.x86 == 0x0f) { /* * On Pentium 4, camellia-asm is slower than original assembler * implementation because excessive uses of 64bit rotate and * left-shifts (which are really slow on P4) needed to store and * handle 128bit block in two 64bit registers. */ return true; } return false; } static int force; module_param(force, int, 0); MODULE_PARM_DESC(force, "Force module load, ignore CPU blacklist"); static int __init init(void) { if (!force && is_blacklisted_cpu()) { printk(KERN_INFO "camellia-x86_64: performance on this CPU " "would be suboptimal: disabling " "camellia-x86_64.\n"); return -ENODEV; } return crypto_register_algs(camellia_algs, ARRAY_SIZE(camellia_algs)); } static void __exit fini(void) { crypto_unregister_algs(camellia_algs, ARRAY_SIZE(camellia_algs)); } module_init(init); module_exit(fini); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Camellia Cipher Algorithm, asm optimized"); MODULE_ALIAS("camellia"); MODULE_ALIAS("camellia-asm");
./CrossVul/dataset_final_sorted/CWE-264/c/bad_5861_26
crossvul-cpp_data_bad_2399_12
/* * eseqiv: Encrypted Sequence Number IV Generator * * This generator generates an IV based on a sequence number by xoring it * with a salt and then encrypting it with the same key as used to encrypt * the plain text. This algorithm requires that the block size be equal * to the IV size. It is mainly useful for CBC. * * Copyright (c) 2007 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/internal/skcipher.h> #include <crypto/rng.h> #include <crypto/scatterwalk.h> #include <linux/err.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/scatterlist.h> #include <linux/spinlock.h> #include <linux/string.h> struct eseqiv_request_ctx { struct scatterlist src[2]; struct scatterlist dst[2]; char tail[]; }; struct eseqiv_ctx { spinlock_t lock; unsigned int reqoff; char salt[]; }; static void eseqiv_complete2(struct skcipher_givcrypt_request *req) { struct crypto_ablkcipher *geniv = skcipher_givcrypt_reqtfm(req); struct eseqiv_request_ctx *reqctx = skcipher_givcrypt_reqctx(req); memcpy(req->giv, PTR_ALIGN((u8 *)reqctx->tail, crypto_ablkcipher_alignmask(geniv) + 1), crypto_ablkcipher_ivsize(geniv)); } static void eseqiv_complete(struct crypto_async_request *base, int err) { struct skcipher_givcrypt_request *req = base->data; if (err) goto out; eseqiv_complete2(req); out: skcipher_givcrypt_complete(req, err); } static int eseqiv_givencrypt(struct skcipher_givcrypt_request *req) { struct crypto_ablkcipher *geniv = skcipher_givcrypt_reqtfm(req); struct eseqiv_ctx *ctx = crypto_ablkcipher_ctx(geniv); struct eseqiv_request_ctx *reqctx = skcipher_givcrypt_reqctx(req); struct ablkcipher_request *subreq; crypto_completion_t compl; void *data; struct scatterlist *osrc, *odst; struct scatterlist *dst; struct page *srcp; struct page *dstp; u8 *giv; u8 *vsrc; u8 *vdst; __be64 seq; unsigned int ivsize; unsigned int len; int err; subreq = (void *)(reqctx->tail + ctx->reqoff); ablkcipher_request_set_tfm(subreq, skcipher_geniv_cipher(geniv)); giv = req->giv; compl = req->creq.base.complete; data = req->creq.base.data; osrc = req->creq.src; odst = req->creq.dst; srcp = sg_page(osrc); dstp = sg_page(odst); vsrc = PageHighMem(srcp) ? NULL : page_address(srcp) + osrc->offset; vdst = PageHighMem(dstp) ? NULL : page_address(dstp) + odst->offset; ivsize = crypto_ablkcipher_ivsize(geniv); if (vsrc != giv + ivsize && vdst != giv + ivsize) { giv = PTR_ALIGN((u8 *)reqctx->tail, crypto_ablkcipher_alignmask(geniv) + 1); compl = eseqiv_complete; data = req; } ablkcipher_request_set_callback(subreq, req->creq.base.flags, compl, data); sg_init_table(reqctx->src, 2); sg_set_buf(reqctx->src, giv, ivsize); scatterwalk_crypto_chain(reqctx->src, osrc, vsrc == giv + ivsize, 2); dst = reqctx->src; if (osrc != odst) { sg_init_table(reqctx->dst, 2); sg_set_buf(reqctx->dst, giv, ivsize); scatterwalk_crypto_chain(reqctx->dst, odst, vdst == giv + ivsize, 2); dst = reqctx->dst; } ablkcipher_request_set_crypt(subreq, reqctx->src, dst, req->creq.nbytes + ivsize, req->creq.info); memcpy(req->creq.info, ctx->salt, ivsize); len = ivsize; if (ivsize > sizeof(u64)) { memset(req->giv, 0, ivsize - sizeof(u64)); len = sizeof(u64); } seq = cpu_to_be64(req->seq); memcpy(req->giv + ivsize - len, &seq, len); err = crypto_ablkcipher_encrypt(subreq); if (err) goto out; if (giv != req->giv) eseqiv_complete2(req); out: return err; } static int eseqiv_givencrypt_first(struct skcipher_givcrypt_request *req) { struct crypto_ablkcipher *geniv = skcipher_givcrypt_reqtfm(req); struct eseqiv_ctx *ctx = crypto_ablkcipher_ctx(geniv); int err = 0; spin_lock_bh(&ctx->lock); if (crypto_ablkcipher_crt(geniv)->givencrypt != eseqiv_givencrypt_first) goto unlock; crypto_ablkcipher_crt(geniv)->givencrypt = eseqiv_givencrypt; err = crypto_rng_get_bytes(crypto_default_rng, ctx->salt, crypto_ablkcipher_ivsize(geniv)); unlock: spin_unlock_bh(&ctx->lock); if (err) return err; return eseqiv_givencrypt(req); } static int eseqiv_init(struct crypto_tfm *tfm) { struct crypto_ablkcipher *geniv = __crypto_ablkcipher_cast(tfm); struct eseqiv_ctx *ctx = crypto_ablkcipher_ctx(geniv); unsigned long alignmask; unsigned int reqsize; spin_lock_init(&ctx->lock); alignmask = crypto_tfm_ctx_alignment() - 1; reqsize = sizeof(struct eseqiv_request_ctx); if (alignmask & reqsize) { alignmask &= reqsize; alignmask--; } alignmask = ~alignmask; alignmask &= crypto_ablkcipher_alignmask(geniv); reqsize += alignmask; reqsize += crypto_ablkcipher_ivsize(geniv); reqsize = ALIGN(reqsize, crypto_tfm_ctx_alignment()); ctx->reqoff = reqsize - sizeof(struct eseqiv_request_ctx); tfm->crt_ablkcipher.reqsize = reqsize + sizeof(struct ablkcipher_request); return skcipher_geniv_init(tfm); } static struct crypto_template eseqiv_tmpl; static struct crypto_instance *eseqiv_alloc(struct rtattr **tb) { struct crypto_instance *inst; int err; err = crypto_get_default_rng(); if (err) return ERR_PTR(err); inst = skcipher_geniv_alloc(&eseqiv_tmpl, tb, 0, 0); if (IS_ERR(inst)) goto put_rng; err = -EINVAL; if (inst->alg.cra_ablkcipher.ivsize != inst->alg.cra_blocksize) goto free_inst; inst->alg.cra_ablkcipher.givencrypt = eseqiv_givencrypt_first; inst->alg.cra_init = eseqiv_init; inst->alg.cra_exit = skcipher_geniv_exit; inst->alg.cra_ctxsize = sizeof(struct eseqiv_ctx); inst->alg.cra_ctxsize += inst->alg.cra_ablkcipher.ivsize; out: return inst; free_inst: skcipher_geniv_free(inst); inst = ERR_PTR(err); put_rng: crypto_put_default_rng(); goto out; } static void eseqiv_free(struct crypto_instance *inst) { skcipher_geniv_free(inst); crypto_put_default_rng(); } static struct crypto_template eseqiv_tmpl = { .name = "eseqiv", .alloc = eseqiv_alloc, .free = eseqiv_free, .module = THIS_MODULE, }; static int __init eseqiv_module_init(void) { return crypto_register_template(&eseqiv_tmpl); } static void __exit eseqiv_module_exit(void) { crypto_unregister_template(&eseqiv_tmpl); } module_init(eseqiv_module_init); module_exit(eseqiv_module_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Encrypted Sequence Number IV Generator");
./CrossVul/dataset_final_sorted/CWE-264/c/bad_2399_12
crossvul-cpp_data_bad_1715_1
/* Copyright (C) 2014 Daniel Dressler and contributors * * 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. */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include "options.h" #include "logging.h" #include "tcp.h" struct tcp_sock_t *tcp_open(uint16_t port) { struct tcp_sock_t *this = calloc(1, sizeof *this); if (this == NULL) { ERR("callocing this failed"); goto error; } // Open [S]ocket [D]escriptor this->sd = -1; this->sd = socket(AF_INET6, SOCK_STREAM, 0); if (this->sd < 0) { ERR("sockect open failed"); goto error; } // Configure socket params struct sockaddr_in6 addr; memset(&addr, 0, sizeof addr); addr.sin6_family = AF_INET6; addr.sin6_port = htons(port); addr.sin6_addr = in6addr_any; // Bind to localhost if (bind(this->sd, (struct sockaddr *)&addr, sizeof addr) < 0) { if (g_options.only_desired_port == 1) ERR("Bind on port failed. " "Requested port may be taken or require root permissions."); goto error; } // Let kernel over-accept max number of connections if (listen(this->sd, HTTP_MAX_PENDING_CONNS) < 0) { ERR("listen failed on socket"); goto error; } return this; error: if (this != NULL) { if (this->sd != -1) { close(this->sd); } free(this); } return NULL; } void tcp_close(struct tcp_sock_t *this) { close(this->sd); free(this); } uint16_t tcp_port_number_get(struct tcp_sock_t *sock) { sock->info_size = sizeof sock->info; int query_status = getsockname( sock->sd, (struct sockaddr *) &(sock->info), &(sock->info_size)); if (query_status == -1) { ERR("query on socket port number failed"); goto error; } return ntohs(sock->info.sin6_port); error: return 0; } struct http_packet_t *tcp_packet_get(struct tcp_conn_t *tcp, struct http_message_t *msg) { // Alloc packet ==---------------------------------------------------== struct http_packet_t *pkt = packet_new(msg); if (pkt == NULL) { ERR("failed to create packet for incoming tcp message"); goto error; } size_t want_size = packet_pending_bytes(pkt); if (want_size == 0) { NOTE("TCP: Got %lu from spare buffer", pkt->filled_size); return pkt; } while (want_size != 0 && !msg->is_completed) { NOTE("TCP: Getting %d bytes", want_size); uint8_t *subbuffer = pkt->buffer + pkt->filled_size; ssize_t gotten_size = recv(tcp->sd, subbuffer, want_size, 0); if (gotten_size < 0) { int errno_saved = errno; ERR("recv failed with err %d:%s", errno_saved, strerror(errno_saved)); goto error; } NOTE("TCP: Got %d bytes", gotten_size); if (gotten_size == 0) { tcp->is_closed = 1; if (pkt->filled_size == 0) { // Client closed TCP conn goto error; } else { break; } } packet_mark_received(pkt, (unsigned) gotten_size); want_size = packet_pending_bytes(pkt); NOTE("TCP: Want more %d bytes; Message %scompleted", want_size, msg->is_completed ? "" : "not "); } NOTE("TCP: Received %lu bytes", pkt->filled_size); return pkt; error: if (pkt != NULL) packet_free(pkt); return NULL; } void tcp_packet_send(struct tcp_conn_t *conn, struct http_packet_t *pkt) { size_t remaining = pkt->filled_size; size_t total = 0; while (remaining > 0) { ssize_t sent = send(conn->sd, pkt->buffer + total, remaining, MSG_NOSIGNAL); if (sent < 0) { if (errno == EPIPE) { conn->is_closed = 1; return; } ERR_AND_EXIT("Failed to sent data over TCP"); } size_t sent_ulong = (unsigned) sent; total += sent_ulong; if (sent_ulong >= remaining) remaining = 0; else remaining -= sent_ulong; } NOTE("TCP: sent %lu bytes", total); } struct tcp_conn_t *tcp_conn_accept(struct tcp_sock_t *sock) { struct tcp_conn_t *conn = calloc(1, sizeof *conn); if (conn == NULL) { ERR("Calloc for connection struct failed"); goto error; } conn->sd = accept(sock->sd, NULL, NULL); if (conn->sd < 0) { ERR("accept failed"); goto error; } return conn; error: if (conn != NULL) free(conn); return NULL; } void tcp_conn_close(struct tcp_conn_t *conn) { close(conn->sd); free(conn); }
./CrossVul/dataset_final_sorted/CWE-264/c/bad_1715_1
crossvul-cpp_data_good_5861_47
/* * Cryptographic API. * * Anubis Algorithm * * The Anubis algorithm was developed by Paulo S. L. M. Barreto and * Vincent Rijmen. * * See * * P.S.L.M. Barreto, V. Rijmen, * ``The Anubis block cipher,'' * NESSIE submission, 2000. * * This software implements the "tweaked" version of Anubis. * Only the S-box and (consequently) the rounds constants have been * changed. * * The original authors have disclaimed all copyright interest in this * code and thus put it in the public domain. The subsequent authors * have put this under the GNU General Public License. * * By Aaron Grothe ajgrothe@yahoo.com, October 28, 2004 * * 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/init.h> #include <linux/module.h> #include <linux/mm.h> #include <asm/byteorder.h> #include <linux/crypto.h> #include <linux/types.h> #define ANUBIS_MIN_KEY_SIZE 16 #define ANUBIS_MAX_KEY_SIZE 40 #define ANUBIS_BLOCK_SIZE 16 #define ANUBIS_MAX_N 10 #define ANUBIS_MAX_ROUNDS (8 + ANUBIS_MAX_N) struct anubis_ctx { int key_len; // in bits int R; u32 E[ANUBIS_MAX_ROUNDS + 1][4]; u32 D[ANUBIS_MAX_ROUNDS + 1][4]; }; static const u32 T0[256] = { 0xba69d2bbU, 0x54a84de5U, 0x2f5ebce2U, 0x74e8cd25U, 0x53a651f7U, 0xd3bb6bd0U, 0xd2b96fd6U, 0x4d9a29b3U, 0x50a05dfdU, 0xac458acfU, 0x8d070e09U, 0xbf63c6a5U, 0x70e0dd3dU, 0x52a455f1U, 0x9a29527bU, 0x4c982db5U, 0xeac98f46U, 0xd5b773c4U, 0x97336655U, 0xd1bf63dcU, 0x3366ccaaU, 0x51a259fbU, 0x5bb671c7U, 0xa651a2f3U, 0xdea15ffeU, 0x48903dadU, 0xa84d9ad7U, 0x992f5e71U, 0xdbab4be0U, 0x3264c8acU, 0xb773e695U, 0xfce5d732U, 0xe3dbab70U, 0x9e214263U, 0x913f7e41U, 0x9b2b567dU, 0xe2d9af76U, 0xbb6bd6bdU, 0x4182199bU, 0x6edca579U, 0xa557aef9U, 0xcb8b0b80U, 0x6bd6b167U, 0x95376e59U, 0xa15fbee1U, 0xf3fbeb10U, 0xb17ffe81U, 0x0204080cU, 0xcc851792U, 0xc49537a2U, 0x1d3a744eU, 0x14285078U, 0xc39b2bb0U, 0x63c69157U, 0xdaa94fe6U, 0x5dba69d3U, 0x5fbe61dfU, 0xdca557f2U, 0x7dfae913U, 0xcd871394U, 0x7ffee11fU, 0x5ab475c1U, 0x6cd8ad75U, 0x5cb86dd5U, 0xf7f3fb08U, 0x264c98d4U, 0xffe3db38U, 0xedc79354U, 0xe8cd874aU, 0x9d274e69U, 0x6fdea17fU, 0x8e010203U, 0x19326456U, 0xa05dbae7U, 0xf0fde71aU, 0x890f1e11U, 0x0f1e3c22U, 0x070e1c12U, 0xaf4386c5U, 0xfbebcb20U, 0x08102030U, 0x152a547eU, 0x0d1a342eU, 0x04081018U, 0x01020406U, 0x64c88d45U, 0xdfa35bf8U, 0x76ecc529U, 0x79f2f90bU, 0xdda753f4U, 0x3d7af48eU, 0x162c5874U, 0x3f7efc82U, 0x376edcb2U, 0x6ddaa973U, 0x3870e090U, 0xb96fdeb1U, 0x73e6d137U, 0xe9cf834cU, 0x356ad4beU, 0x55aa49e3U, 0x71e2d93bU, 0x7bf6f107U, 0x8c050a0fU, 0x72e4d531U, 0x880d1a17U, 0xf6f1ff0eU, 0x2a54a8fcU, 0x3e7cf884U, 0x5ebc65d9U, 0x274e9cd2U, 0x468c0589U, 0x0c183028U, 0x65ca8943U, 0x68d0bd6dU, 0x61c2995bU, 0x03060c0aU, 0xc19f23bcU, 0x57ae41efU, 0xd6b17fceU, 0xd9af43ecU, 0x58b07dcdU, 0xd8ad47eaU, 0x66cc8549U, 0xd7b37bc8U, 0x3a74e89cU, 0xc88d078aU, 0x3c78f088U, 0xfae9cf26U, 0x96316253U, 0xa753a6f5U, 0x982d5a77U, 0xecc59752U, 0xb86ddab7U, 0xc7933ba8U, 0xae4182c3U, 0x69d2b96bU, 0x4b9631a7U, 0xab4b96ddU, 0xa94f9ed1U, 0x67ce814fU, 0x0a14283cU, 0x478e018fU, 0xf2f9ef16U, 0xb577ee99U, 0x224488ccU, 0xe5d7b364U, 0xeec19f5eU, 0xbe61c2a3U, 0x2b56acfaU, 0x811f3e21U, 0x1224486cU, 0x831b362dU, 0x1b366c5aU, 0x0e1c3824U, 0x23468ccaU, 0xf5f7f304U, 0x458a0983U, 0x214284c6U, 0xce811f9eU, 0x499239abU, 0x2c58b0e8U, 0xf9efc32cU, 0xe6d1bf6eU, 0xb671e293U, 0x2850a0f0U, 0x172e5c72U, 0x8219322bU, 0x1a34685cU, 0x8b0b161dU, 0xfee1df3eU, 0x8a09121bU, 0x09122436U, 0xc98f038cU, 0x87132635U, 0x4e9c25b9U, 0xe1dfa37cU, 0x2e5cb8e4U, 0xe4d5b762U, 0xe0dda77aU, 0xebcb8b40U, 0x903d7a47U, 0xa455aaffU, 0x1e3c7844U, 0x85172e39U, 0x60c09d5dU, 0x00000000U, 0x254a94deU, 0xf4f5f702U, 0xf1ffe31cU, 0x94356a5fU, 0x0b162c3aU, 0xe7d3bb68U, 0x75eac923U, 0xefc39b58U, 0x3468d0b8U, 0x3162c4a6U, 0xd4b577c2U, 0xd0bd67daU, 0x86112233U, 0x7efce519U, 0xad478ec9U, 0xfde7d334U, 0x2952a4f6U, 0x3060c0a0U, 0x3b76ec9aU, 0x9f234665U, 0xf8edc72aU, 0xc6913faeU, 0x13264c6aU, 0x060c1814U, 0x050a141eU, 0xc59733a4U, 0x11224466U, 0x77eec12fU, 0x7cf8ed15U, 0x7af4f501U, 0x78f0fd0dU, 0x366cd8b4U, 0x1c387048U, 0x3972e496U, 0x59b279cbU, 0x18306050U, 0x56ac45e9U, 0xb37bf68dU, 0xb07dfa87U, 0x244890d8U, 0x204080c0U, 0xb279f28bU, 0x9239724bU, 0xa35bb6edU, 0xc09d27baU, 0x44880d85U, 0x62c49551U, 0x10204060U, 0xb475ea9fU, 0x84152a3fU, 0x43861197U, 0x933b764dU, 0xc2992fb6U, 0x4a9435a1U, 0xbd67cea9U, 0x8f030605U, 0x2d5ab4eeU, 0xbc65caafU, 0x9c254a6fU, 0x6ad4b561U, 0x40801d9dU, 0xcf831b98U, 0xa259b2ebU, 0x801d3a27U, 0x4f9e21bfU, 0x1f3e7c42U, 0xca890f86U, 0xaa4992dbU, 0x42841591U, }; static const u32 T1[256] = { 0x69babbd2U, 0xa854e54dU, 0x5e2fe2bcU, 0xe87425cdU, 0xa653f751U, 0xbbd3d06bU, 0xb9d2d66fU, 0x9a4db329U, 0xa050fd5dU, 0x45accf8aU, 0x078d090eU, 0x63bfa5c6U, 0xe0703dddU, 0xa452f155U, 0x299a7b52U, 0x984cb52dU, 0xc9ea468fU, 0xb7d5c473U, 0x33975566U, 0xbfd1dc63U, 0x6633aaccU, 0xa251fb59U, 0xb65bc771U, 0x51a6f3a2U, 0xa1defe5fU, 0x9048ad3dU, 0x4da8d79aU, 0x2f99715eU, 0xabdbe04bU, 0x6432acc8U, 0x73b795e6U, 0xe5fc32d7U, 0xdbe370abU, 0x219e6342U, 0x3f91417eU, 0x2b9b7d56U, 0xd9e276afU, 0x6bbbbdd6U, 0x82419b19U, 0xdc6e79a5U, 0x57a5f9aeU, 0x8bcb800bU, 0xd66b67b1U, 0x3795596eU, 0x5fa1e1beU, 0xfbf310ebU, 0x7fb181feU, 0x04020c08U, 0x85cc9217U, 0x95c4a237U, 0x3a1d4e74U, 0x28147850U, 0x9bc3b02bU, 0xc6635791U, 0xa9dae64fU, 0xba5dd369U, 0xbe5fdf61U, 0xa5dcf257U, 0xfa7d13e9U, 0x87cd9413U, 0xfe7f1fe1U, 0xb45ac175U, 0xd86c75adU, 0xb85cd56dU, 0xf3f708fbU, 0x4c26d498U, 0xe3ff38dbU, 0xc7ed5493U, 0xcde84a87U, 0x279d694eU, 0xde6f7fa1U, 0x018e0302U, 0x32195664U, 0x5da0e7baU, 0xfdf01ae7U, 0x0f89111eU, 0x1e0f223cU, 0x0e07121cU, 0x43afc586U, 0xebfb20cbU, 0x10083020U, 0x2a157e54U, 0x1a0d2e34U, 0x08041810U, 0x02010604U, 0xc864458dU, 0xa3dff85bU, 0xec7629c5U, 0xf2790bf9U, 0xa7ddf453U, 0x7a3d8ef4U, 0x2c167458U, 0x7e3f82fcU, 0x6e37b2dcU, 0xda6d73a9U, 0x703890e0U, 0x6fb9b1deU, 0xe67337d1U, 0xcfe94c83U, 0x6a35bed4U, 0xaa55e349U, 0xe2713bd9U, 0xf67b07f1U, 0x058c0f0aU, 0xe47231d5U, 0x0d88171aU, 0xf1f60effU, 0x542afca8U, 0x7c3e84f8U, 0xbc5ed965U, 0x4e27d29cU, 0x8c468905U, 0x180c2830U, 0xca654389U, 0xd0686dbdU, 0xc2615b99U, 0x06030a0cU, 0x9fc1bc23U, 0xae57ef41U, 0xb1d6ce7fU, 0xafd9ec43U, 0xb058cd7dU, 0xadd8ea47U, 0xcc664985U, 0xb3d7c87bU, 0x743a9ce8U, 0x8dc88a07U, 0x783c88f0U, 0xe9fa26cfU, 0x31965362U, 0x53a7f5a6U, 0x2d98775aU, 0xc5ec5297U, 0x6db8b7daU, 0x93c7a83bU, 0x41aec382U, 0xd2696bb9U, 0x964ba731U, 0x4babdd96U, 0x4fa9d19eU, 0xce674f81U, 0x140a3c28U, 0x8e478f01U, 0xf9f216efU, 0x77b599eeU, 0x4422cc88U, 0xd7e564b3U, 0xc1ee5e9fU, 0x61bea3c2U, 0x562bfaacU, 0x1f81213eU, 0x24126c48U, 0x1b832d36U, 0x361b5a6cU, 0x1c0e2438U, 0x4623ca8cU, 0xf7f504f3U, 0x8a458309U, 0x4221c684U, 0x81ce9e1fU, 0x9249ab39U, 0x582ce8b0U, 0xeff92cc3U, 0xd1e66ebfU, 0x71b693e2U, 0x5028f0a0U, 0x2e17725cU, 0x19822b32U, 0x341a5c68U, 0x0b8b1d16U, 0xe1fe3edfU, 0x098a1b12U, 0x12093624U, 0x8fc98c03U, 0x13873526U, 0x9c4eb925U, 0xdfe17ca3U, 0x5c2ee4b8U, 0xd5e462b7U, 0xdde07aa7U, 0xcbeb408bU, 0x3d90477aU, 0x55a4ffaaU, 0x3c1e4478U, 0x1785392eU, 0xc0605d9dU, 0x00000000U, 0x4a25de94U, 0xf5f402f7U, 0xfff11ce3U, 0x35945f6aU, 0x160b3a2cU, 0xd3e768bbU, 0xea7523c9U, 0xc3ef589bU, 0x6834b8d0U, 0x6231a6c4U, 0xb5d4c277U, 0xbdd0da67U, 0x11863322U, 0xfc7e19e5U, 0x47adc98eU, 0xe7fd34d3U, 0x5229f6a4U, 0x6030a0c0U, 0x763b9aecU, 0x239f6546U, 0xedf82ac7U, 0x91c6ae3fU, 0x26136a4cU, 0x0c061418U, 0x0a051e14U, 0x97c5a433U, 0x22116644U, 0xee772fc1U, 0xf87c15edU, 0xf47a01f5U, 0xf0780dfdU, 0x6c36b4d8U, 0x381c4870U, 0x723996e4U, 0xb259cb79U, 0x30185060U, 0xac56e945U, 0x7bb38df6U, 0x7db087faU, 0x4824d890U, 0x4020c080U, 0x79b28bf2U, 0x39924b72U, 0x5ba3edb6U, 0x9dc0ba27U, 0x8844850dU, 0xc4625195U, 0x20106040U, 0x75b49feaU, 0x15843f2aU, 0x86439711U, 0x3b934d76U, 0x99c2b62fU, 0x944aa135U, 0x67bda9ceU, 0x038f0506U, 0x5a2deeb4U, 0x65bcafcaU, 0x259c6f4aU, 0xd46a61b5U, 0x80409d1dU, 0x83cf981bU, 0x59a2ebb2U, 0x1d80273aU, 0x9e4fbf21U, 0x3e1f427cU, 0x89ca860fU, 0x49aadb92U, 0x84429115U, }; static const u32 T2[256] = { 0xd2bbba69U, 0x4de554a8U, 0xbce22f5eU, 0xcd2574e8U, 0x51f753a6U, 0x6bd0d3bbU, 0x6fd6d2b9U, 0x29b34d9aU, 0x5dfd50a0U, 0x8acfac45U, 0x0e098d07U, 0xc6a5bf63U, 0xdd3d70e0U, 0x55f152a4U, 0x527b9a29U, 0x2db54c98U, 0x8f46eac9U, 0x73c4d5b7U, 0x66559733U, 0x63dcd1bfU, 0xccaa3366U, 0x59fb51a2U, 0x71c75bb6U, 0xa2f3a651U, 0x5ffedea1U, 0x3dad4890U, 0x9ad7a84dU, 0x5e71992fU, 0x4be0dbabU, 0xc8ac3264U, 0xe695b773U, 0xd732fce5U, 0xab70e3dbU, 0x42639e21U, 0x7e41913fU, 0x567d9b2bU, 0xaf76e2d9U, 0xd6bdbb6bU, 0x199b4182U, 0xa5796edcU, 0xaef9a557U, 0x0b80cb8bU, 0xb1676bd6U, 0x6e599537U, 0xbee1a15fU, 0xeb10f3fbU, 0xfe81b17fU, 0x080c0204U, 0x1792cc85U, 0x37a2c495U, 0x744e1d3aU, 0x50781428U, 0x2bb0c39bU, 0x915763c6U, 0x4fe6daa9U, 0x69d35dbaU, 0x61df5fbeU, 0x57f2dca5U, 0xe9137dfaU, 0x1394cd87U, 0xe11f7ffeU, 0x75c15ab4U, 0xad756cd8U, 0x6dd55cb8U, 0xfb08f7f3U, 0x98d4264cU, 0xdb38ffe3U, 0x9354edc7U, 0x874ae8cdU, 0x4e699d27U, 0xa17f6fdeU, 0x02038e01U, 0x64561932U, 0xbae7a05dU, 0xe71af0fdU, 0x1e11890fU, 0x3c220f1eU, 0x1c12070eU, 0x86c5af43U, 0xcb20fbebU, 0x20300810U, 0x547e152aU, 0x342e0d1aU, 0x10180408U, 0x04060102U, 0x8d4564c8U, 0x5bf8dfa3U, 0xc52976ecU, 0xf90b79f2U, 0x53f4dda7U, 0xf48e3d7aU, 0x5874162cU, 0xfc823f7eU, 0xdcb2376eU, 0xa9736ddaU, 0xe0903870U, 0xdeb1b96fU, 0xd13773e6U, 0x834ce9cfU, 0xd4be356aU, 0x49e355aaU, 0xd93b71e2U, 0xf1077bf6U, 0x0a0f8c05U, 0xd53172e4U, 0x1a17880dU, 0xff0ef6f1U, 0xa8fc2a54U, 0xf8843e7cU, 0x65d95ebcU, 0x9cd2274eU, 0x0589468cU, 0x30280c18U, 0x894365caU, 0xbd6d68d0U, 0x995b61c2U, 0x0c0a0306U, 0x23bcc19fU, 0x41ef57aeU, 0x7fced6b1U, 0x43ecd9afU, 0x7dcd58b0U, 0x47ead8adU, 0x854966ccU, 0x7bc8d7b3U, 0xe89c3a74U, 0x078ac88dU, 0xf0883c78U, 0xcf26fae9U, 0x62539631U, 0xa6f5a753U, 0x5a77982dU, 0x9752ecc5U, 0xdab7b86dU, 0x3ba8c793U, 0x82c3ae41U, 0xb96b69d2U, 0x31a74b96U, 0x96ddab4bU, 0x9ed1a94fU, 0x814f67ceU, 0x283c0a14U, 0x018f478eU, 0xef16f2f9U, 0xee99b577U, 0x88cc2244U, 0xb364e5d7U, 0x9f5eeec1U, 0xc2a3be61U, 0xacfa2b56U, 0x3e21811fU, 0x486c1224U, 0x362d831bU, 0x6c5a1b36U, 0x38240e1cU, 0x8cca2346U, 0xf304f5f7U, 0x0983458aU, 0x84c62142U, 0x1f9ece81U, 0x39ab4992U, 0xb0e82c58U, 0xc32cf9efU, 0xbf6ee6d1U, 0xe293b671U, 0xa0f02850U, 0x5c72172eU, 0x322b8219U, 0x685c1a34U, 0x161d8b0bU, 0xdf3efee1U, 0x121b8a09U, 0x24360912U, 0x038cc98fU, 0x26358713U, 0x25b94e9cU, 0xa37ce1dfU, 0xb8e42e5cU, 0xb762e4d5U, 0xa77ae0ddU, 0x8b40ebcbU, 0x7a47903dU, 0xaaffa455U, 0x78441e3cU, 0x2e398517U, 0x9d5d60c0U, 0x00000000U, 0x94de254aU, 0xf702f4f5U, 0xe31cf1ffU, 0x6a5f9435U, 0x2c3a0b16U, 0xbb68e7d3U, 0xc92375eaU, 0x9b58efc3U, 0xd0b83468U, 0xc4a63162U, 0x77c2d4b5U, 0x67dad0bdU, 0x22338611U, 0xe5197efcU, 0x8ec9ad47U, 0xd334fde7U, 0xa4f62952U, 0xc0a03060U, 0xec9a3b76U, 0x46659f23U, 0xc72af8edU, 0x3faec691U, 0x4c6a1326U, 0x1814060cU, 0x141e050aU, 0x33a4c597U, 0x44661122U, 0xc12f77eeU, 0xed157cf8U, 0xf5017af4U, 0xfd0d78f0U, 0xd8b4366cU, 0x70481c38U, 0xe4963972U, 0x79cb59b2U, 0x60501830U, 0x45e956acU, 0xf68db37bU, 0xfa87b07dU, 0x90d82448U, 0x80c02040U, 0xf28bb279U, 0x724b9239U, 0xb6eda35bU, 0x27bac09dU, 0x0d854488U, 0x955162c4U, 0x40601020U, 0xea9fb475U, 0x2a3f8415U, 0x11974386U, 0x764d933bU, 0x2fb6c299U, 0x35a14a94U, 0xcea9bd67U, 0x06058f03U, 0xb4ee2d5aU, 0xcaafbc65U, 0x4a6f9c25U, 0xb5616ad4U, 0x1d9d4080U, 0x1b98cf83U, 0xb2eba259U, 0x3a27801dU, 0x21bf4f9eU, 0x7c421f3eU, 0x0f86ca89U, 0x92dbaa49U, 0x15914284U, }; static const u32 T3[256] = { 0xbbd269baU, 0xe54da854U, 0xe2bc5e2fU, 0x25cde874U, 0xf751a653U, 0xd06bbbd3U, 0xd66fb9d2U, 0xb3299a4dU, 0xfd5da050U, 0xcf8a45acU, 0x090e078dU, 0xa5c663bfU, 0x3ddde070U, 0xf155a452U, 0x7b52299aU, 0xb52d984cU, 0x468fc9eaU, 0xc473b7d5U, 0x55663397U, 0xdc63bfd1U, 0xaacc6633U, 0xfb59a251U, 0xc771b65bU, 0xf3a251a6U, 0xfe5fa1deU, 0xad3d9048U, 0xd79a4da8U, 0x715e2f99U, 0xe04babdbU, 0xacc86432U, 0x95e673b7U, 0x32d7e5fcU, 0x70abdbe3U, 0x6342219eU, 0x417e3f91U, 0x7d562b9bU, 0x76afd9e2U, 0xbdd66bbbU, 0x9b198241U, 0x79a5dc6eU, 0xf9ae57a5U, 0x800b8bcbU, 0x67b1d66bU, 0x596e3795U, 0xe1be5fa1U, 0x10ebfbf3U, 0x81fe7fb1U, 0x0c080402U, 0x921785ccU, 0xa23795c4U, 0x4e743a1dU, 0x78502814U, 0xb02b9bc3U, 0x5791c663U, 0xe64fa9daU, 0xd369ba5dU, 0xdf61be5fU, 0xf257a5dcU, 0x13e9fa7dU, 0x941387cdU, 0x1fe1fe7fU, 0xc175b45aU, 0x75add86cU, 0xd56db85cU, 0x08fbf3f7U, 0xd4984c26U, 0x38dbe3ffU, 0x5493c7edU, 0x4a87cde8U, 0x694e279dU, 0x7fa1de6fU, 0x0302018eU, 0x56643219U, 0xe7ba5da0U, 0x1ae7fdf0U, 0x111e0f89U, 0x223c1e0fU, 0x121c0e07U, 0xc58643afU, 0x20cbebfbU, 0x30201008U, 0x7e542a15U, 0x2e341a0dU, 0x18100804U, 0x06040201U, 0x458dc864U, 0xf85ba3dfU, 0x29c5ec76U, 0x0bf9f279U, 0xf453a7ddU, 0x8ef47a3dU, 0x74582c16U, 0x82fc7e3fU, 0xb2dc6e37U, 0x73a9da6dU, 0x90e07038U, 0xb1de6fb9U, 0x37d1e673U, 0x4c83cfe9U, 0xbed46a35U, 0xe349aa55U, 0x3bd9e271U, 0x07f1f67bU, 0x0f0a058cU, 0x31d5e472U, 0x171a0d88U, 0x0efff1f6U, 0xfca8542aU, 0x84f87c3eU, 0xd965bc5eU, 0xd29c4e27U, 0x89058c46U, 0x2830180cU, 0x4389ca65U, 0x6dbdd068U, 0x5b99c261U, 0x0a0c0603U, 0xbc239fc1U, 0xef41ae57U, 0xce7fb1d6U, 0xec43afd9U, 0xcd7db058U, 0xea47add8U, 0x4985cc66U, 0xc87bb3d7U, 0x9ce8743aU, 0x8a078dc8U, 0x88f0783cU, 0x26cfe9faU, 0x53623196U, 0xf5a653a7U, 0x775a2d98U, 0x5297c5ecU, 0xb7da6db8U, 0xa83b93c7U, 0xc38241aeU, 0x6bb9d269U, 0xa731964bU, 0xdd964babU, 0xd19e4fa9U, 0x4f81ce67U, 0x3c28140aU, 0x8f018e47U, 0x16eff9f2U, 0x99ee77b5U, 0xcc884422U, 0x64b3d7e5U, 0x5e9fc1eeU, 0xa3c261beU, 0xfaac562bU, 0x213e1f81U, 0x6c482412U, 0x2d361b83U, 0x5a6c361bU, 0x24381c0eU, 0xca8c4623U, 0x04f3f7f5U, 0x83098a45U, 0xc6844221U, 0x9e1f81ceU, 0xab399249U, 0xe8b0582cU, 0x2cc3eff9U, 0x6ebfd1e6U, 0x93e271b6U, 0xf0a05028U, 0x725c2e17U, 0x2b321982U, 0x5c68341aU, 0x1d160b8bU, 0x3edfe1feU, 0x1b12098aU, 0x36241209U, 0x8c038fc9U, 0x35261387U, 0xb9259c4eU, 0x7ca3dfe1U, 0xe4b85c2eU, 0x62b7d5e4U, 0x7aa7dde0U, 0x408bcbebU, 0x477a3d90U, 0xffaa55a4U, 0x44783c1eU, 0x392e1785U, 0x5d9dc060U, 0x00000000U, 0xde944a25U, 0x02f7f5f4U, 0x1ce3fff1U, 0x5f6a3594U, 0x3a2c160bU, 0x68bbd3e7U, 0x23c9ea75U, 0x589bc3efU, 0xb8d06834U, 0xa6c46231U, 0xc277b5d4U, 0xda67bdd0U, 0x33221186U, 0x19e5fc7eU, 0xc98e47adU, 0x34d3e7fdU, 0xf6a45229U, 0xa0c06030U, 0x9aec763bU, 0x6546239fU, 0x2ac7edf8U, 0xae3f91c6U, 0x6a4c2613U, 0x14180c06U, 0x1e140a05U, 0xa43397c5U, 0x66442211U, 0x2fc1ee77U, 0x15edf87cU, 0x01f5f47aU, 0x0dfdf078U, 0xb4d86c36U, 0x4870381cU, 0x96e47239U, 0xcb79b259U, 0x50603018U, 0xe945ac56U, 0x8df67bb3U, 0x87fa7db0U, 0xd8904824U, 0xc0804020U, 0x8bf279b2U, 0x4b723992U, 0xedb65ba3U, 0xba279dc0U, 0x850d8844U, 0x5195c462U, 0x60402010U, 0x9fea75b4U, 0x3f2a1584U, 0x97118643U, 0x4d763b93U, 0xb62f99c2U, 0xa135944aU, 0xa9ce67bdU, 0x0506038fU, 0xeeb45a2dU, 0xafca65bcU, 0x6f4a259cU, 0x61b5d46aU, 0x9d1d8040U, 0x981b83cfU, 0xebb259a2U, 0x273a1d80U, 0xbf219e4fU, 0x427c3e1fU, 0x860f89caU, 0xdb9249aaU, 0x91158442U, }; static const u32 T4[256] = { 0xbabababaU, 0x54545454U, 0x2f2f2f2fU, 0x74747474U, 0x53535353U, 0xd3d3d3d3U, 0xd2d2d2d2U, 0x4d4d4d4dU, 0x50505050U, 0xacacacacU, 0x8d8d8d8dU, 0xbfbfbfbfU, 0x70707070U, 0x52525252U, 0x9a9a9a9aU, 0x4c4c4c4cU, 0xeaeaeaeaU, 0xd5d5d5d5U, 0x97979797U, 0xd1d1d1d1U, 0x33333333U, 0x51515151U, 0x5b5b5b5bU, 0xa6a6a6a6U, 0xdedededeU, 0x48484848U, 0xa8a8a8a8U, 0x99999999U, 0xdbdbdbdbU, 0x32323232U, 0xb7b7b7b7U, 0xfcfcfcfcU, 0xe3e3e3e3U, 0x9e9e9e9eU, 0x91919191U, 0x9b9b9b9bU, 0xe2e2e2e2U, 0xbbbbbbbbU, 0x41414141U, 0x6e6e6e6eU, 0xa5a5a5a5U, 0xcbcbcbcbU, 0x6b6b6b6bU, 0x95959595U, 0xa1a1a1a1U, 0xf3f3f3f3U, 0xb1b1b1b1U, 0x02020202U, 0xccccccccU, 0xc4c4c4c4U, 0x1d1d1d1dU, 0x14141414U, 0xc3c3c3c3U, 0x63636363U, 0xdadadadaU, 0x5d5d5d5dU, 0x5f5f5f5fU, 0xdcdcdcdcU, 0x7d7d7d7dU, 0xcdcdcdcdU, 0x7f7f7f7fU, 0x5a5a5a5aU, 0x6c6c6c6cU, 0x5c5c5c5cU, 0xf7f7f7f7U, 0x26262626U, 0xffffffffU, 0xededededU, 0xe8e8e8e8U, 0x9d9d9d9dU, 0x6f6f6f6fU, 0x8e8e8e8eU, 0x19191919U, 0xa0a0a0a0U, 0xf0f0f0f0U, 0x89898989U, 0x0f0f0f0fU, 0x07070707U, 0xafafafafU, 0xfbfbfbfbU, 0x08080808U, 0x15151515U, 0x0d0d0d0dU, 0x04040404U, 0x01010101U, 0x64646464U, 0xdfdfdfdfU, 0x76767676U, 0x79797979U, 0xddddddddU, 0x3d3d3d3dU, 0x16161616U, 0x3f3f3f3fU, 0x37373737U, 0x6d6d6d6dU, 0x38383838U, 0xb9b9b9b9U, 0x73737373U, 0xe9e9e9e9U, 0x35353535U, 0x55555555U, 0x71717171U, 0x7b7b7b7bU, 0x8c8c8c8cU, 0x72727272U, 0x88888888U, 0xf6f6f6f6U, 0x2a2a2a2aU, 0x3e3e3e3eU, 0x5e5e5e5eU, 0x27272727U, 0x46464646U, 0x0c0c0c0cU, 0x65656565U, 0x68686868U, 0x61616161U, 0x03030303U, 0xc1c1c1c1U, 0x57575757U, 0xd6d6d6d6U, 0xd9d9d9d9U, 0x58585858U, 0xd8d8d8d8U, 0x66666666U, 0xd7d7d7d7U, 0x3a3a3a3aU, 0xc8c8c8c8U, 0x3c3c3c3cU, 0xfafafafaU, 0x96969696U, 0xa7a7a7a7U, 0x98989898U, 0xececececU, 0xb8b8b8b8U, 0xc7c7c7c7U, 0xaeaeaeaeU, 0x69696969U, 0x4b4b4b4bU, 0xababababU, 0xa9a9a9a9U, 0x67676767U, 0x0a0a0a0aU, 0x47474747U, 0xf2f2f2f2U, 0xb5b5b5b5U, 0x22222222U, 0xe5e5e5e5U, 0xeeeeeeeeU, 0xbebebebeU, 0x2b2b2b2bU, 0x81818181U, 0x12121212U, 0x83838383U, 0x1b1b1b1bU, 0x0e0e0e0eU, 0x23232323U, 0xf5f5f5f5U, 0x45454545U, 0x21212121U, 0xcecececeU, 0x49494949U, 0x2c2c2c2cU, 0xf9f9f9f9U, 0xe6e6e6e6U, 0xb6b6b6b6U, 0x28282828U, 0x17171717U, 0x82828282U, 0x1a1a1a1aU, 0x8b8b8b8bU, 0xfefefefeU, 0x8a8a8a8aU, 0x09090909U, 0xc9c9c9c9U, 0x87878787U, 0x4e4e4e4eU, 0xe1e1e1e1U, 0x2e2e2e2eU, 0xe4e4e4e4U, 0xe0e0e0e0U, 0xebebebebU, 0x90909090U, 0xa4a4a4a4U, 0x1e1e1e1eU, 0x85858585U, 0x60606060U, 0x00000000U, 0x25252525U, 0xf4f4f4f4U, 0xf1f1f1f1U, 0x94949494U, 0x0b0b0b0bU, 0xe7e7e7e7U, 0x75757575U, 0xefefefefU, 0x34343434U, 0x31313131U, 0xd4d4d4d4U, 0xd0d0d0d0U, 0x86868686U, 0x7e7e7e7eU, 0xadadadadU, 0xfdfdfdfdU, 0x29292929U, 0x30303030U, 0x3b3b3b3bU, 0x9f9f9f9fU, 0xf8f8f8f8U, 0xc6c6c6c6U, 0x13131313U, 0x06060606U, 0x05050505U, 0xc5c5c5c5U, 0x11111111U, 0x77777777U, 0x7c7c7c7cU, 0x7a7a7a7aU, 0x78787878U, 0x36363636U, 0x1c1c1c1cU, 0x39393939U, 0x59595959U, 0x18181818U, 0x56565656U, 0xb3b3b3b3U, 0xb0b0b0b0U, 0x24242424U, 0x20202020U, 0xb2b2b2b2U, 0x92929292U, 0xa3a3a3a3U, 0xc0c0c0c0U, 0x44444444U, 0x62626262U, 0x10101010U, 0xb4b4b4b4U, 0x84848484U, 0x43434343U, 0x93939393U, 0xc2c2c2c2U, 0x4a4a4a4aU, 0xbdbdbdbdU, 0x8f8f8f8fU, 0x2d2d2d2dU, 0xbcbcbcbcU, 0x9c9c9c9cU, 0x6a6a6a6aU, 0x40404040U, 0xcfcfcfcfU, 0xa2a2a2a2U, 0x80808080U, 0x4f4f4f4fU, 0x1f1f1f1fU, 0xcacacacaU, 0xaaaaaaaaU, 0x42424242U, }; static const u32 T5[256] = { 0x00000000U, 0x01020608U, 0x02040c10U, 0x03060a18U, 0x04081820U, 0x050a1e28U, 0x060c1430U, 0x070e1238U, 0x08103040U, 0x09123648U, 0x0a143c50U, 0x0b163a58U, 0x0c182860U, 0x0d1a2e68U, 0x0e1c2470U, 0x0f1e2278U, 0x10206080U, 0x11226688U, 0x12246c90U, 0x13266a98U, 0x142878a0U, 0x152a7ea8U, 0x162c74b0U, 0x172e72b8U, 0x183050c0U, 0x193256c8U, 0x1a345cd0U, 0x1b365ad8U, 0x1c3848e0U, 0x1d3a4ee8U, 0x1e3c44f0U, 0x1f3e42f8U, 0x2040c01dU, 0x2142c615U, 0x2244cc0dU, 0x2346ca05U, 0x2448d83dU, 0x254ade35U, 0x264cd42dU, 0x274ed225U, 0x2850f05dU, 0x2952f655U, 0x2a54fc4dU, 0x2b56fa45U, 0x2c58e87dU, 0x2d5aee75U, 0x2e5ce46dU, 0x2f5ee265U, 0x3060a09dU, 0x3162a695U, 0x3264ac8dU, 0x3366aa85U, 0x3468b8bdU, 0x356abeb5U, 0x366cb4adU, 0x376eb2a5U, 0x387090ddU, 0x397296d5U, 0x3a749ccdU, 0x3b769ac5U, 0x3c7888fdU, 0x3d7a8ef5U, 0x3e7c84edU, 0x3f7e82e5U, 0x40809d3aU, 0x41829b32U, 0x4284912aU, 0x43869722U, 0x4488851aU, 0x458a8312U, 0x468c890aU, 0x478e8f02U, 0x4890ad7aU, 0x4992ab72U, 0x4a94a16aU, 0x4b96a762U, 0x4c98b55aU, 0x4d9ab352U, 0x4e9cb94aU, 0x4f9ebf42U, 0x50a0fdbaU, 0x51a2fbb2U, 0x52a4f1aaU, 0x53a6f7a2U, 0x54a8e59aU, 0x55aae392U, 0x56ace98aU, 0x57aeef82U, 0x58b0cdfaU, 0x59b2cbf2U, 0x5ab4c1eaU, 0x5bb6c7e2U, 0x5cb8d5daU, 0x5dbad3d2U, 0x5ebcd9caU, 0x5fbedfc2U, 0x60c05d27U, 0x61c25b2fU, 0x62c45137U, 0x63c6573fU, 0x64c84507U, 0x65ca430fU, 0x66cc4917U, 0x67ce4f1fU, 0x68d06d67U, 0x69d26b6fU, 0x6ad46177U, 0x6bd6677fU, 0x6cd87547U, 0x6dda734fU, 0x6edc7957U, 0x6fde7f5fU, 0x70e03da7U, 0x71e23bafU, 0x72e431b7U, 0x73e637bfU, 0x74e82587U, 0x75ea238fU, 0x76ec2997U, 0x77ee2f9fU, 0x78f00de7U, 0x79f20befU, 0x7af401f7U, 0x7bf607ffU, 0x7cf815c7U, 0x7dfa13cfU, 0x7efc19d7U, 0x7ffe1fdfU, 0x801d2774U, 0x811f217cU, 0x82192b64U, 0x831b2d6cU, 0x84153f54U, 0x8517395cU, 0x86113344U, 0x8713354cU, 0x880d1734U, 0x890f113cU, 0x8a091b24U, 0x8b0b1d2cU, 0x8c050f14U, 0x8d07091cU, 0x8e010304U, 0x8f03050cU, 0x903d47f4U, 0x913f41fcU, 0x92394be4U, 0x933b4decU, 0x94355fd4U, 0x953759dcU, 0x963153c4U, 0x973355ccU, 0x982d77b4U, 0x992f71bcU, 0x9a297ba4U, 0x9b2b7dacU, 0x9c256f94U, 0x9d27699cU, 0x9e216384U, 0x9f23658cU, 0xa05de769U, 0xa15fe161U, 0xa259eb79U, 0xa35bed71U, 0xa455ff49U, 0xa557f941U, 0xa651f359U, 0xa753f551U, 0xa84dd729U, 0xa94fd121U, 0xaa49db39U, 0xab4bdd31U, 0xac45cf09U, 0xad47c901U, 0xae41c319U, 0xaf43c511U, 0xb07d87e9U, 0xb17f81e1U, 0xb2798bf9U, 0xb37b8df1U, 0xb4759fc9U, 0xb57799c1U, 0xb67193d9U, 0xb77395d1U, 0xb86db7a9U, 0xb96fb1a1U, 0xba69bbb9U, 0xbb6bbdb1U, 0xbc65af89U, 0xbd67a981U, 0xbe61a399U, 0xbf63a591U, 0xc09dba4eU, 0xc19fbc46U, 0xc299b65eU, 0xc39bb056U, 0xc495a26eU, 0xc597a466U, 0xc691ae7eU, 0xc793a876U, 0xc88d8a0eU, 0xc98f8c06U, 0xca89861eU, 0xcb8b8016U, 0xcc85922eU, 0xcd879426U, 0xce819e3eU, 0xcf839836U, 0xd0bddaceU, 0xd1bfdcc6U, 0xd2b9d6deU, 0xd3bbd0d6U, 0xd4b5c2eeU, 0xd5b7c4e6U, 0xd6b1cefeU, 0xd7b3c8f6U, 0xd8adea8eU, 0xd9afec86U, 0xdaa9e69eU, 0xdbabe096U, 0xdca5f2aeU, 0xdda7f4a6U, 0xdea1febeU, 0xdfa3f8b6U, 0xe0dd7a53U, 0xe1df7c5bU, 0xe2d97643U, 0xe3db704bU, 0xe4d56273U, 0xe5d7647bU, 0xe6d16e63U, 0xe7d3686bU, 0xe8cd4a13U, 0xe9cf4c1bU, 0xeac94603U, 0xebcb400bU, 0xecc55233U, 0xedc7543bU, 0xeec15e23U, 0xefc3582bU, 0xf0fd1ad3U, 0xf1ff1cdbU, 0xf2f916c3U, 0xf3fb10cbU, 0xf4f502f3U, 0xf5f704fbU, 0xf6f10ee3U, 0xf7f308ebU, 0xf8ed2a93U, 0xf9ef2c9bU, 0xfae92683U, 0xfbeb208bU, 0xfce532b3U, 0xfde734bbU, 0xfee13ea3U, 0xffe338abU, }; static const u32 rc[] = { 0xba542f74U, 0x53d3d24dU, 0x50ac8dbfU, 0x70529a4cU, 0xead597d1U, 0x33515ba6U, 0xde48a899U, 0xdb32b7fcU, 0xe39e919bU, 0xe2bb416eU, 0xa5cb6b95U, 0xa1f3b102U, 0xccc41d14U, 0xc363da5dU, 0x5fdc7dcdU, 0x7f5a6c5cU, 0xf726ffedU, 0xe89d6f8eU, 0x19a0f089U, }; static int anubis_setkey(struct crypto_tfm *tfm, const u8 *in_key, unsigned int key_len) { struct anubis_ctx *ctx = crypto_tfm_ctx(tfm); const __be32 *key = (const __be32 *)in_key; u32 *flags = &tfm->crt_flags; int N, R, i, r; u32 kappa[ANUBIS_MAX_N]; u32 inter[ANUBIS_MAX_N]; switch (key_len) { case 16: case 20: case 24: case 28: case 32: case 36: case 40: break; default: *flags |= CRYPTO_TFM_RES_BAD_KEY_LEN; return -EINVAL; } ctx->key_len = key_len * 8; N = ctx->key_len >> 5; ctx->R = R = 8 + N; /* * map cipher key to initial key state (mu): */ for (i = 0; i < N; i++) kappa[i] = be32_to_cpu(key[i]); /* * generate R + 1 round keys: */ for (r = 0; r <= R; r++) { u32 K0, K1, K2, K3; /* * generate r-th round key K^r: */ K0 = T4[(kappa[N - 1] >> 24) ]; K1 = T4[(kappa[N - 1] >> 16) & 0xff]; K2 = T4[(kappa[N - 1] >> 8) & 0xff]; K3 = T4[(kappa[N - 1] ) & 0xff]; for (i = N - 2; i >= 0; i--) { K0 = T4[(kappa[i] >> 24) ] ^ (T5[(K0 >> 24) ] & 0xff000000U) ^ (T5[(K0 >> 16) & 0xff] & 0x00ff0000U) ^ (T5[(K0 >> 8) & 0xff] & 0x0000ff00U) ^ (T5[(K0 ) & 0xff] & 0x000000ffU); K1 = T4[(kappa[i] >> 16) & 0xff] ^ (T5[(K1 >> 24) ] & 0xff000000U) ^ (T5[(K1 >> 16) & 0xff] & 0x00ff0000U) ^ (T5[(K1 >> 8) & 0xff] & 0x0000ff00U) ^ (T5[(K1 ) & 0xff] & 0x000000ffU); K2 = T4[(kappa[i] >> 8) & 0xff] ^ (T5[(K2 >> 24) ] & 0xff000000U) ^ (T5[(K2 >> 16) & 0xff] & 0x00ff0000U) ^ (T5[(K2 >> 8) & 0xff] & 0x0000ff00U) ^ (T5[(K2 ) & 0xff] & 0x000000ffU); K3 = T4[(kappa[i] ) & 0xff] ^ (T5[(K3 >> 24) ] & 0xff000000U) ^ (T5[(K3 >> 16) & 0xff] & 0x00ff0000U) ^ (T5[(K3 >> 8) & 0xff] & 0x0000ff00U) ^ (T5[(K3 ) & 0xff] & 0x000000ffU); } ctx->E[r][0] = K0; ctx->E[r][1] = K1; ctx->E[r][2] = K2; ctx->E[r][3] = K3; /* * compute kappa^{r+1} from kappa^r: */ if (r == R) break; for (i = 0; i < N; i++) { int j = i; inter[i] = T0[(kappa[j--] >> 24) ]; if (j < 0) j = N - 1; inter[i] ^= T1[(kappa[j--] >> 16) & 0xff]; if (j < 0) j = N - 1; inter[i] ^= T2[(kappa[j--] >> 8) & 0xff]; if (j < 0) j = N - 1; inter[i] ^= T3[(kappa[j ] ) & 0xff]; } kappa[0] = inter[0] ^ rc[r]; for (i = 1; i < N; i++) kappa[i] = inter[i]; } /* * generate inverse key schedule: K'^0 = K^R, K'^R = * K^0, K'^r = theta(K^{R-r}): */ for (i = 0; i < 4; i++) { ctx->D[0][i] = ctx->E[R][i]; ctx->D[R][i] = ctx->E[0][i]; } for (r = 1; r < R; r++) { for (i = 0; i < 4; i++) { u32 v = ctx->E[R - r][i]; ctx->D[r][i] = T0[T4[(v >> 24) ] & 0xff] ^ T1[T4[(v >> 16) & 0xff] & 0xff] ^ T2[T4[(v >> 8) & 0xff] & 0xff] ^ T3[T4[(v ) & 0xff] & 0xff]; } } return 0; } static void anubis_crypt(u32 roundKey[ANUBIS_MAX_ROUNDS + 1][4], u8 *ciphertext, const u8 *plaintext, const int R) { const __be32 *src = (const __be32 *)plaintext; __be32 *dst = (__be32 *)ciphertext; int i, r; u32 state[4]; u32 inter[4]; /* * map plaintext block to cipher state (mu) * and add initial round key (sigma[K^0]): */ for (i = 0; i < 4; i++) state[i] = be32_to_cpu(src[i]) ^ roundKey[0][i]; /* * R - 1 full rounds: */ for (r = 1; r < R; r++) { inter[0] = T0[(state[0] >> 24) ] ^ T1[(state[1] >> 24) ] ^ T2[(state[2] >> 24) ] ^ T3[(state[3] >> 24) ] ^ roundKey[r][0]; inter[1] = T0[(state[0] >> 16) & 0xff] ^ T1[(state[1] >> 16) & 0xff] ^ T2[(state[2] >> 16) & 0xff] ^ T3[(state[3] >> 16) & 0xff] ^ roundKey[r][1]; inter[2] = T0[(state[0] >> 8) & 0xff] ^ T1[(state[1] >> 8) & 0xff] ^ T2[(state[2] >> 8) & 0xff] ^ T3[(state[3] >> 8) & 0xff] ^ roundKey[r][2]; inter[3] = T0[(state[0] ) & 0xff] ^ T1[(state[1] ) & 0xff] ^ T2[(state[2] ) & 0xff] ^ T3[(state[3] ) & 0xff] ^ roundKey[r][3]; state[0] = inter[0]; state[1] = inter[1]; state[2] = inter[2]; state[3] = inter[3]; } /* * last round: */ inter[0] = (T0[(state[0] >> 24) ] & 0xff000000U) ^ (T1[(state[1] >> 24) ] & 0x00ff0000U) ^ (T2[(state[2] >> 24) ] & 0x0000ff00U) ^ (T3[(state[3] >> 24) ] & 0x000000ffU) ^ roundKey[R][0]; inter[1] = (T0[(state[0] >> 16) & 0xff] & 0xff000000U) ^ (T1[(state[1] >> 16) & 0xff] & 0x00ff0000U) ^ (T2[(state[2] >> 16) & 0xff] & 0x0000ff00U) ^ (T3[(state[3] >> 16) & 0xff] & 0x000000ffU) ^ roundKey[R][1]; inter[2] = (T0[(state[0] >> 8) & 0xff] & 0xff000000U) ^ (T1[(state[1] >> 8) & 0xff] & 0x00ff0000U) ^ (T2[(state[2] >> 8) & 0xff] & 0x0000ff00U) ^ (T3[(state[3] >> 8) & 0xff] & 0x000000ffU) ^ roundKey[R][2]; inter[3] = (T0[(state[0] ) & 0xff] & 0xff000000U) ^ (T1[(state[1] ) & 0xff] & 0x00ff0000U) ^ (T2[(state[2] ) & 0xff] & 0x0000ff00U) ^ (T3[(state[3] ) & 0xff] & 0x000000ffU) ^ roundKey[R][3]; /* * map cipher state to ciphertext block (mu^{-1}): */ for (i = 0; i < 4; i++) dst[i] = cpu_to_be32(inter[i]); } static void anubis_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src) { struct anubis_ctx *ctx = crypto_tfm_ctx(tfm); anubis_crypt(ctx->E, dst, src, ctx->R); } static void anubis_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src) { struct anubis_ctx *ctx = crypto_tfm_ctx(tfm); anubis_crypt(ctx->D, dst, src, ctx->R); } static struct crypto_alg anubis_alg = { .cra_name = "anubis", .cra_flags = CRYPTO_ALG_TYPE_CIPHER, .cra_blocksize = ANUBIS_BLOCK_SIZE, .cra_ctxsize = sizeof (struct anubis_ctx), .cra_alignmask = 3, .cra_module = THIS_MODULE, .cra_u = { .cipher = { .cia_min_keysize = ANUBIS_MIN_KEY_SIZE, .cia_max_keysize = ANUBIS_MAX_KEY_SIZE, .cia_setkey = anubis_setkey, .cia_encrypt = anubis_encrypt, .cia_decrypt = anubis_decrypt } } }; static int __init anubis_mod_init(void) { int ret = 0; ret = crypto_register_alg(&anubis_alg); return ret; } static void __exit anubis_mod_fini(void) { crypto_unregister_alg(&anubis_alg); } module_init(anubis_mod_init); module_exit(anubis_mod_fini); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Anubis Cryptographic Algorithm"); MODULE_ALIAS_CRYPTO("anubis");
./CrossVul/dataset_final_sorted/CWE-264/c/good_5861_47
crossvul-cpp_data_bad_3526_1
/* * Copyright (C) 2001-2003 Sistina Software (UK) Limited. * * This file is released under the GPL. */ #include "dm.h" #include <linux/module.h> #include <linux/init.h> #include <linux/blkdev.h> #include <linux/bio.h> #include <linux/slab.h> #include <linux/device-mapper.h> #define DM_MSG_PREFIX "linear" /* * Linear: maps a linear range of a device. */ struct linear_c { struct dm_dev *dev; sector_t start; }; /* * Construct a linear mapping: <dev_path> <offset> */ static int linear_ctr(struct dm_target *ti, unsigned int argc, char **argv) { struct linear_c *lc; unsigned long long tmp; if (argc != 2) { ti->error = "Invalid argument count"; return -EINVAL; } lc = kmalloc(sizeof(*lc), GFP_KERNEL); if (lc == NULL) { ti->error = "dm-linear: Cannot allocate linear context"; return -ENOMEM; } if (sscanf(argv[1], "%llu", &tmp) != 1) { ti->error = "dm-linear: Invalid device sector"; goto bad; } lc->start = tmp; if (dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &lc->dev)) { ti->error = "dm-linear: Device lookup failed"; goto bad; } ti->num_flush_requests = 1; ti->num_discard_requests = 1; ti->private = lc; return 0; bad: kfree(lc); return -EINVAL; } static void linear_dtr(struct dm_target *ti) { struct linear_c *lc = (struct linear_c *) ti->private; dm_put_device(ti, lc->dev); kfree(lc); } static sector_t linear_map_sector(struct dm_target *ti, sector_t bi_sector) { struct linear_c *lc = ti->private; return lc->start + dm_target_offset(ti, bi_sector); } static void linear_map_bio(struct dm_target *ti, struct bio *bio) { struct linear_c *lc = ti->private; bio->bi_bdev = lc->dev->bdev; if (bio_sectors(bio)) bio->bi_sector = linear_map_sector(ti, bio->bi_sector); } static int linear_map(struct dm_target *ti, struct bio *bio, union map_info *map_context) { linear_map_bio(ti, bio); return DM_MAPIO_REMAPPED; } static int linear_status(struct dm_target *ti, status_type_t type, char *result, unsigned int maxlen) { struct linear_c *lc = (struct linear_c *) ti->private; switch (type) { case STATUSTYPE_INFO: result[0] = '\0'; break; case STATUSTYPE_TABLE: snprintf(result, maxlen, "%s %llu", lc->dev->name, (unsigned long long)lc->start); break; } return 0; } static int linear_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg) { struct linear_c *lc = (struct linear_c *) ti->private; return __blkdev_driver_ioctl(lc->dev->bdev, lc->dev->mode, cmd, arg); } static int linear_merge(struct dm_target *ti, struct bvec_merge_data *bvm, struct bio_vec *biovec, int max_size) { struct linear_c *lc = ti->private; struct request_queue *q = bdev_get_queue(lc->dev->bdev); if (!q->merge_bvec_fn) return max_size; bvm->bi_bdev = lc->dev->bdev; bvm->bi_sector = linear_map_sector(ti, bvm->bi_sector); return min(max_size, q->merge_bvec_fn(q, bvm, biovec)); } static int linear_iterate_devices(struct dm_target *ti, iterate_devices_callout_fn fn, void *data) { struct linear_c *lc = ti->private; return fn(ti, lc->dev, lc->start, ti->len, data); } static struct target_type linear_target = { .name = "linear", .version = {1, 1, 0}, .module = THIS_MODULE, .ctr = linear_ctr, .dtr = linear_dtr, .map = linear_map, .status = linear_status, .ioctl = linear_ioctl, .merge = linear_merge, .iterate_devices = linear_iterate_devices, }; int __init dm_linear_init(void) { int r = dm_register_target(&linear_target); if (r < 0) DMERR("register failed %d", r); return r; } void dm_linear_exit(void) { dm_unregister_target(&linear_target); }
./CrossVul/dataset_final_sorted/CWE-264/c/bad_3526_1
crossvul-cpp_data_bad_891_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-264/c/bad_891_0
crossvul-cpp_data_good_5018_0
/* * Copyright (C) 1995 Linus Torvalds * * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999 * * Memory region support * David Parsons <orc@pell.chi.il.us>, July-August 1999 * * Added E820 sanitization routine (removes overlapping memory regions); * Brian Moyle <bmoyle@mvista.com>, February 2001 * * Moved CPU detection code to cpu/${cpu}.c * Patrick Mochel <mochel@osdl.org>, March 2002 * * Provisions for empty E820 memory regions (reported by certain BIOSes). * Alex Achenbach <xela@slit.de>, December 2002. * */ /* * This file handles the architecture-dependent parts of initialization */ #include <linux/sched.h> #include <linux/mm.h> #include <linux/mmzone.h> #include <linux/screen_info.h> #include <linux/ioport.h> #include <linux/acpi.h> #include <linux/sfi.h> #include <linux/apm_bios.h> #include <linux/initrd.h> #include <linux/bootmem.h> #include <linux/memblock.h> #include <linux/seq_file.h> #include <linux/console.h> #include <linux/root_dev.h> #include <linux/highmem.h> #include <linux/module.h> #include <linux/efi.h> #include <linux/init.h> #include <linux/edd.h> #include <linux/iscsi_ibft.h> #include <linux/nodemask.h> #include <linux/kexec.h> #include <linux/dmi.h> #include <linux/pfn.h> #include <linux/pci.h> #include <asm/pci-direct.h> #include <linux/init_ohci1394_dma.h> #include <linux/kvm_para.h> #include <linux/dma-contiguous.h> #include <linux/security.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/stddef.h> #include <linux/unistd.h> #include <linux/ptrace.h> #include <linux/user.h> #include <linux/delay.h> #include <linux/kallsyms.h> #include <linux/cpufreq.h> #include <linux/dma-mapping.h> #include <linux/ctype.h> #include <linux/uaccess.h> #include <linux/percpu.h> #include <linux/crash_dump.h> #include <linux/tboot.h> #include <linux/jiffies.h> #include <video/edid.h> #include <asm/mtrr.h> #include <asm/apic.h> #include <asm/realmode.h> #include <asm/e820.h> #include <asm/mpspec.h> #include <asm/setup.h> #include <asm/efi.h> #include <asm/timer.h> #include <asm/i8259.h> #include <asm/sections.h> #include <asm/io_apic.h> #include <asm/ist.h> #include <asm/setup_arch.h> #include <asm/bios_ebda.h> #include <asm/cacheflush.h> #include <asm/processor.h> #include <asm/bugs.h> #include <asm/kasan.h> #include <asm/vsyscall.h> #include <asm/cpu.h> #include <asm/desc.h> #include <asm/dma.h> #include <asm/iommu.h> #include <asm/gart.h> #include <asm/mmu_context.h> #include <asm/proto.h> #include <asm/paravirt.h> #include <asm/hypervisor.h> #include <asm/olpc_ofw.h> #include <asm/percpu.h> #include <asm/topology.h> #include <asm/apicdef.h> #include <asm/amd_nb.h> #include <asm/mce.h> #include <asm/alternative.h> #include <asm/prom.h> #include <asm/microcode.h> #include <asm/mmu_context.h> /* * max_low_pfn_mapped: highest direct mapped pfn under 4GB * max_pfn_mapped: highest direct mapped pfn over 4GB * * The direct mapping only covers E820_RAM regions, so the ranges and gaps are * represented by pfn_mapped */ unsigned long max_low_pfn_mapped; unsigned long max_pfn_mapped; #ifdef CONFIG_DMI RESERVE_BRK(dmi_alloc, 65536); #endif static __initdata unsigned long _brk_start = (unsigned long)__brk_base; unsigned long _brk_end = (unsigned long)__brk_base; #ifdef CONFIG_X86_64 int default_cpu_present_to_apicid(int mps_cpu) { return __default_cpu_present_to_apicid(mps_cpu); } int default_check_phys_apicid_present(int phys_apicid) { return __default_check_phys_apicid_present(phys_apicid); } #endif struct boot_params boot_params; /* * Machine setup.. */ static struct resource data_resource = { .name = "Kernel data", .start = 0, .end = 0, .flags = IORESOURCE_BUSY | IORESOURCE_SYSTEM_RAM }; static struct resource code_resource = { .name = "Kernel code", .start = 0, .end = 0, .flags = IORESOURCE_BUSY | IORESOURCE_SYSTEM_RAM }; static struct resource bss_resource = { .name = "Kernel bss", .start = 0, .end = 0, .flags = IORESOURCE_BUSY | IORESOURCE_SYSTEM_RAM }; #ifdef CONFIG_X86_32 /* cpu data as detected by the assembly code in head.S */ struct cpuinfo_x86 new_cpu_data = { .wp_works_ok = -1, }; /* common cpu data for all cpus */ struct cpuinfo_x86 boot_cpu_data __read_mostly = { .wp_works_ok = -1, }; EXPORT_SYMBOL(boot_cpu_data); unsigned int def_to_bigsmp; /* for MCA, but anyone else can use it if they want */ unsigned int machine_id; unsigned int machine_submodel_id; unsigned int BIOS_revision; struct apm_info apm_info; EXPORT_SYMBOL(apm_info); #if defined(CONFIG_X86_SPEEDSTEP_SMI) || \ defined(CONFIG_X86_SPEEDSTEP_SMI_MODULE) struct ist_info ist_info; EXPORT_SYMBOL(ist_info); #else struct ist_info ist_info; #endif #else struct cpuinfo_x86 boot_cpu_data __read_mostly = { .x86_phys_bits = MAX_PHYSMEM_BITS, }; EXPORT_SYMBOL(boot_cpu_data); #endif #if !defined(CONFIG_X86_PAE) || defined(CONFIG_X86_64) __visible unsigned long mmu_cr4_features; #else __visible unsigned long mmu_cr4_features = X86_CR4_PAE; #endif /* Boot loader ID and version as integers, for the benefit of proc_dointvec */ int bootloader_type, bootloader_version; /* * Setup options */ struct screen_info screen_info; EXPORT_SYMBOL(screen_info); struct edid_info edid_info; EXPORT_SYMBOL_GPL(edid_info); extern int root_mountflags; unsigned long saved_video_mode; #define RAMDISK_IMAGE_START_MASK 0x07FF #define RAMDISK_PROMPT_FLAG 0x8000 #define RAMDISK_LOAD_FLAG 0x4000 static char __initdata command_line[COMMAND_LINE_SIZE]; #ifdef CONFIG_CMDLINE_BOOL static char __initdata builtin_cmdline[COMMAND_LINE_SIZE] = CONFIG_CMDLINE; #endif #if defined(CONFIG_EDD) || defined(CONFIG_EDD_MODULE) struct edd edd; #ifdef CONFIG_EDD_MODULE EXPORT_SYMBOL(edd); #endif /** * copy_edd() - Copy the BIOS EDD information * from boot_params into a safe place. * */ static inline void __init copy_edd(void) { memcpy(edd.mbr_signature, boot_params.edd_mbr_sig_buffer, sizeof(edd.mbr_signature)); memcpy(edd.edd_info, boot_params.eddbuf, sizeof(edd.edd_info)); edd.mbr_signature_nr = boot_params.edd_mbr_sig_buf_entries; edd.edd_info_nr = boot_params.eddbuf_entries; } #else static inline void __init copy_edd(void) { } #endif void * __init extend_brk(size_t size, size_t align) { size_t mask = align - 1; void *ret; BUG_ON(_brk_start == 0); BUG_ON(align & mask); _brk_end = (_brk_end + mask) & ~mask; BUG_ON((char *)(_brk_end + size) > __brk_limit); ret = (void *)_brk_end; _brk_end += size; memset(ret, 0, size); return ret; } #ifdef CONFIG_X86_32 static void __init cleanup_highmap(void) { } #endif static void __init reserve_brk(void) { if (_brk_end > _brk_start) memblock_reserve(__pa_symbol(_brk_start), _brk_end - _brk_start); /* Mark brk area as locked down and no longer taking any new allocations */ _brk_start = 0; } u64 relocated_ramdisk; #ifdef CONFIG_BLK_DEV_INITRD static u64 __init get_ramdisk_image(void) { u64 ramdisk_image = boot_params.hdr.ramdisk_image; ramdisk_image |= (u64)boot_params.ext_ramdisk_image << 32; return ramdisk_image; } static u64 __init get_ramdisk_size(void) { u64 ramdisk_size = boot_params.hdr.ramdisk_size; ramdisk_size |= (u64)boot_params.ext_ramdisk_size << 32; return ramdisk_size; } static void __init relocate_initrd(void) { /* Assume only end is not page aligned */ u64 ramdisk_image = get_ramdisk_image(); u64 ramdisk_size = get_ramdisk_size(); u64 area_size = PAGE_ALIGN(ramdisk_size); /* We need to move the initrd down into directly mapped mem */ relocated_ramdisk = memblock_find_in_range(0, PFN_PHYS(max_pfn_mapped), area_size, PAGE_SIZE); if (!relocated_ramdisk) panic("Cannot find place for new RAMDISK of size %lld\n", ramdisk_size); /* Note: this includes all the mem currently occupied by the initrd, we rely on that fact to keep the data intact. */ memblock_reserve(relocated_ramdisk, area_size); initrd_start = relocated_ramdisk + PAGE_OFFSET; initrd_end = initrd_start + ramdisk_size; printk(KERN_INFO "Allocated new RAMDISK: [mem %#010llx-%#010llx]\n", relocated_ramdisk, relocated_ramdisk + ramdisk_size - 1); copy_from_early_mem((void *)initrd_start, ramdisk_image, ramdisk_size); printk(KERN_INFO "Move RAMDISK from [mem %#010llx-%#010llx] to" " [mem %#010llx-%#010llx]\n", ramdisk_image, ramdisk_image + ramdisk_size - 1, relocated_ramdisk, relocated_ramdisk + ramdisk_size - 1); } static void __init early_reserve_initrd(void) { /* Assume only end is not page aligned */ u64 ramdisk_image = get_ramdisk_image(); u64 ramdisk_size = get_ramdisk_size(); u64 ramdisk_end = PAGE_ALIGN(ramdisk_image + ramdisk_size); if (!boot_params.hdr.type_of_loader || !ramdisk_image || !ramdisk_size) return; /* No initrd provided by bootloader */ memblock_reserve(ramdisk_image, ramdisk_end - ramdisk_image); } static void __init reserve_initrd(void) { /* Assume only end is not page aligned */ u64 ramdisk_image = get_ramdisk_image(); u64 ramdisk_size = get_ramdisk_size(); u64 ramdisk_end = PAGE_ALIGN(ramdisk_image + ramdisk_size); u64 mapped_size; if (!boot_params.hdr.type_of_loader || !ramdisk_image || !ramdisk_size) return; /* No initrd provided by bootloader */ initrd_start = 0; mapped_size = memblock_mem_size(max_pfn_mapped); if (ramdisk_size >= (mapped_size>>1)) panic("initrd too large to handle, " "disabling initrd (%lld needed, %lld available)\n", ramdisk_size, mapped_size>>1); printk(KERN_INFO "RAMDISK: [mem %#010llx-%#010llx]\n", ramdisk_image, ramdisk_end - 1); if (pfn_range_is_mapped(PFN_DOWN(ramdisk_image), PFN_DOWN(ramdisk_end))) { /* All are mapped, easy case */ initrd_start = ramdisk_image + PAGE_OFFSET; initrd_end = initrd_start + ramdisk_size; return; } relocate_initrd(); memblock_free(ramdisk_image, ramdisk_end - ramdisk_image); } #else static void __init early_reserve_initrd(void) { } static void __init reserve_initrd(void) { } #endif /* CONFIG_BLK_DEV_INITRD */ static void __init parse_setup_data(void) { struct setup_data *data; u64 pa_data, pa_next; pa_data = boot_params.hdr.setup_data; while (pa_data) { u32 data_len, data_type; data = early_memremap(pa_data, sizeof(*data)); data_len = data->len + sizeof(struct setup_data); data_type = data->type; pa_next = data->next; early_memunmap(data, sizeof(*data)); switch (data_type) { case SETUP_E820_EXT: parse_e820_ext(pa_data, data_len); break; case SETUP_DTB: add_dtb(pa_data); break; case SETUP_EFI: parse_efi_setup(pa_data, data_len); break; default: break; } pa_data = pa_next; } } static void __init e820_reserve_setup_data(void) { struct setup_data *data; u64 pa_data; pa_data = boot_params.hdr.setup_data; if (!pa_data) return; while (pa_data) { data = early_memremap(pa_data, sizeof(*data)); e820_update_range(pa_data, sizeof(*data)+data->len, E820_RAM, E820_RESERVED_KERN); pa_data = data->next; early_memunmap(data, sizeof(*data)); } sanitize_e820_map(e820.map, ARRAY_SIZE(e820.map), &e820.nr_map); memcpy(&e820_saved, &e820, sizeof(struct e820map)); printk(KERN_INFO "extended physical RAM map:\n"); e820_print_map("reserve setup_data"); } static void __init memblock_x86_reserve_range_setup_data(void) { struct setup_data *data; u64 pa_data; pa_data = boot_params.hdr.setup_data; while (pa_data) { data = early_memremap(pa_data, sizeof(*data)); memblock_reserve(pa_data, sizeof(*data) + data->len); pa_data = data->next; early_memunmap(data, sizeof(*data)); } } /* * --------- Crashkernel reservation ------------------------------ */ #ifdef CONFIG_KEXEC_CORE /* 16M alignment for crash kernel regions */ #define CRASH_ALIGN (16 << 20) /* * Keep the crash kernel below this limit. On 32 bits earlier kernels * would limit the kernel to the low 512 MiB due to mapping restrictions. * On 64bit, old kexec-tools need to under 896MiB. */ #ifdef CONFIG_X86_32 # define CRASH_ADDR_LOW_MAX (512 << 20) # define CRASH_ADDR_HIGH_MAX (512 << 20) #else # define CRASH_ADDR_LOW_MAX (896UL << 20) # define CRASH_ADDR_HIGH_MAX MAXMEM #endif static int __init reserve_crashkernel_low(void) { #ifdef CONFIG_X86_64 unsigned long long base, low_base = 0, low_size = 0; unsigned long total_low_mem; int ret; total_low_mem = memblock_mem_size(1UL << (32 - PAGE_SHIFT)); /* crashkernel=Y,low */ ret = parse_crashkernel_low(boot_command_line, total_low_mem, &low_size, &base); if (ret) { /* * two parts from lib/swiotlb.c: * -swiotlb size: user-specified with swiotlb= or default. * * -swiotlb overflow buffer: now hardcoded to 32k. We round it * to 8M for other buffers that may need to stay low too. Also * make sure we allocate enough extra low memory so that we * don't run out of DMA buffers for 32-bit devices. */ low_size = max(swiotlb_size_or_default() + (8UL << 20), 256UL << 20); } else { /* passed with crashkernel=0,low ? */ if (!low_size) return 0; } low_base = memblock_find_in_range(low_size, 1ULL << 32, low_size, CRASH_ALIGN); if (!low_base) { pr_err("Cannot reserve %ldMB crashkernel low memory, please try smaller size.\n", (unsigned long)(low_size >> 20)); return -ENOMEM; } ret = memblock_reserve(low_base, low_size); if (ret) { pr_err("%s: Error reserving crashkernel low memblock.\n", __func__); return ret; } pr_info("Reserving %ldMB of low memory at %ldMB for crashkernel (System low RAM: %ldMB)\n", (unsigned long)(low_size >> 20), (unsigned long)(low_base >> 20), (unsigned long)(total_low_mem >> 20)); crashk_low_res.start = low_base; crashk_low_res.end = low_base + low_size - 1; insert_resource(&iomem_resource, &crashk_low_res); #endif return 0; } static void __init reserve_crashkernel(void) { unsigned long long crash_size, crash_base, total_mem; bool high = false; int ret; total_mem = memblock_phys_mem_size(); /* crashkernel=XM */ ret = parse_crashkernel(boot_command_line, total_mem, &crash_size, &crash_base); if (ret != 0 || crash_size <= 0) { /* crashkernel=X,high */ ret = parse_crashkernel_high(boot_command_line, total_mem, &crash_size, &crash_base); if (ret != 0 || crash_size <= 0) return; high = true; } /* 0 means: find the address automatically */ if (crash_base <= 0) { /* * kexec want bzImage is below CRASH_KERNEL_ADDR_MAX */ crash_base = memblock_find_in_range(CRASH_ALIGN, high ? CRASH_ADDR_HIGH_MAX : CRASH_ADDR_LOW_MAX, crash_size, CRASH_ALIGN); if (!crash_base) { pr_info("crashkernel reservation failed - No suitable area found.\n"); return; } } else { unsigned long long start; start = memblock_find_in_range(crash_base, crash_base + crash_size, crash_size, 1 << 20); if (start != crash_base) { pr_info("crashkernel reservation failed - memory is in use.\n"); return; } } ret = memblock_reserve(crash_base, crash_size); if (ret) { pr_err("%s: Error reserving crashkernel memblock.\n", __func__); return; } if (crash_base >= (1ULL << 32) && reserve_crashkernel_low()) { memblock_free(crash_base, crash_size); return; } pr_info("Reserving %ldMB of memory at %ldMB for crashkernel (System RAM: %ldMB)\n", (unsigned long)(crash_size >> 20), (unsigned long)(crash_base >> 20), (unsigned long)(total_mem >> 20)); crashk_res.start = crash_base; crashk_res.end = crash_base + crash_size - 1; insert_resource(&iomem_resource, &crashk_res); } #else static void __init reserve_crashkernel(void) { } #endif static struct resource standard_io_resources[] = { { .name = "dma1", .start = 0x00, .end = 0x1f, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "pic1", .start = 0x20, .end = 0x21, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "timer0", .start = 0x40, .end = 0x43, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "timer1", .start = 0x50, .end = 0x53, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "keyboard", .start = 0x60, .end = 0x60, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "keyboard", .start = 0x64, .end = 0x64, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "dma page reg", .start = 0x80, .end = 0x8f, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "pic2", .start = 0xa0, .end = 0xa1, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "dma2", .start = 0xc0, .end = 0xdf, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "fpu", .start = 0xf0, .end = 0xff, .flags = IORESOURCE_BUSY | IORESOURCE_IO } }; void __init reserve_standard_io_resources(void) { int i; /* request I/O space for devices used on all i[345]86 PCs */ for (i = 0; i < ARRAY_SIZE(standard_io_resources); i++) request_resource(&ioport_resource, &standard_io_resources[i]); } static __init void reserve_ibft_region(void) { unsigned long addr, size = 0; addr = find_ibft_region(&size); if (size) memblock_reserve(addr, size); } static bool __init snb_gfx_workaround_needed(void) { #ifdef CONFIG_PCI int i; u16 vendor, devid; static const __initconst u16 snb_ids[] = { 0x0102, 0x0112, 0x0122, 0x0106, 0x0116, 0x0126, 0x010a, }; /* Assume no if something weird is going on with PCI */ if (!early_pci_allowed()) return false; vendor = read_pci_config_16(0, 2, 0, PCI_VENDOR_ID); if (vendor != 0x8086) return false; devid = read_pci_config_16(0, 2, 0, PCI_DEVICE_ID); for (i = 0; i < ARRAY_SIZE(snb_ids); i++) if (devid == snb_ids[i]) return true; #endif return false; } /* * Sandy Bridge graphics has trouble with certain ranges, exclude * them from allocation. */ static void __init trim_snb_memory(void) { static const __initconst unsigned long bad_pages[] = { 0x20050000, 0x20110000, 0x20130000, 0x20138000, 0x40004000, }; int i; if (!snb_gfx_workaround_needed()) return; printk(KERN_DEBUG "reserving inaccessible SNB gfx pages\n"); /* * Reserve all memory below the 1 MB mark that has not * already been reserved. */ memblock_reserve(0, 1<<20); for (i = 0; i < ARRAY_SIZE(bad_pages); i++) { if (memblock_reserve(bad_pages[i], PAGE_SIZE)) printk(KERN_WARNING "failed to reserve 0x%08lx\n", bad_pages[i]); } } /* * Here we put platform-specific memory range workarounds, i.e. * memory known to be corrupt or otherwise in need to be reserved on * specific platforms. * * If this gets used more widely it could use a real dispatch mechanism. */ static void __init trim_platform_memory_ranges(void) { trim_snb_memory(); } static void __init trim_bios_range(void) { /* * A special case is the first 4Kb of memory; * This is a BIOS owned area, not kernel ram, but generally * not listed as such in the E820 table. * * This typically reserves additional memory (64KiB by default) * since some BIOSes are known to corrupt low memory. See the * Kconfig help text for X86_RESERVE_LOW. */ e820_update_range(0, PAGE_SIZE, E820_RAM, E820_RESERVED); /* * special case: Some BIOSen report the PC BIOS * area (640->1Mb) as ram even though it is not. * take them out. */ e820_remove_range(BIOS_BEGIN, BIOS_END - BIOS_BEGIN, E820_RAM, 1); sanitize_e820_map(e820.map, ARRAY_SIZE(e820.map), &e820.nr_map); } /* called before trim_bios_range() to spare extra sanitize */ static void __init e820_add_kernel_range(void) { u64 start = __pa_symbol(_text); u64 size = __pa_symbol(_end) - start; /* * Complain if .text .data and .bss are not marked as E820_RAM and * attempt to fix it by adding the range. We may have a confused BIOS, * or the user may have used memmap=exactmap or memmap=xxM$yyM to * exclude kernel range. If we really are running on top non-RAM, * we will crash later anyways. */ if (e820_all_mapped(start, start + size, E820_RAM)) return; pr_warn(".text .data .bss are not marked as E820_RAM!\n"); e820_remove_range(start, size, E820_RAM, 0); e820_add_region(start, size, E820_RAM); } static unsigned reserve_low = CONFIG_X86_RESERVE_LOW << 10; static int __init parse_reservelow(char *p) { unsigned long long size; if (!p) return -EINVAL; size = memparse(p, &p); if (size < 4096) size = 4096; if (size > 640*1024) size = 640*1024; reserve_low = size; return 0; } early_param("reservelow", parse_reservelow); static void __init trim_low_memory_range(void) { memblock_reserve(0, ALIGN(reserve_low, PAGE_SIZE)); } /* * Dump out kernel offset information on panic. */ static int dump_kernel_offset(struct notifier_block *self, unsigned long v, void *p) { if (kaslr_enabled()) { pr_emerg("Kernel Offset: 0x%lx from 0x%lx (relocation range: 0x%lx-0x%lx)\n", kaslr_offset(), __START_KERNEL, __START_KERNEL_map, MODULES_VADDR-1); } else { pr_emerg("Kernel Offset: disabled\n"); } return 0; } /* * Determine if we were loaded by an EFI loader. If so, then we have also been * passed the efi memmap, systab, etc., so we should use these data structures * for initialization. Note, the efi init code path is determined by the * global efi_enabled. This allows the same kernel image to be used on existing * systems (with a traditional BIOS) as well as on EFI systems. */ /* * setup_arch - architecture-specific boot-time initializations * * Note: On x86_64, fixmaps are ready for use even before this is called. */ void __init setup_arch(char **cmdline_p) { memblock_reserve(__pa_symbol(_text), (unsigned long)__bss_stop - (unsigned long)_text); early_reserve_initrd(); /* * At this point everything still needed from the boot loader * or BIOS or kernel text should be early reserved or marked not * RAM in e820. All other memory is free game. */ #ifdef CONFIG_X86_32 memcpy(&boot_cpu_data, &new_cpu_data, sizeof(new_cpu_data)); /* * copy kernel address range established so far and switch * to the proper swapper page table */ clone_pgd_range(swapper_pg_dir + KERNEL_PGD_BOUNDARY, initial_page_table + KERNEL_PGD_BOUNDARY, KERNEL_PGD_PTRS); load_cr3(swapper_pg_dir); /* * Note: Quark X1000 CPUs advertise PGE incorrectly and require * a cr3 based tlb flush, so the following __flush_tlb_all() * will not flush anything because the cpu quirk which clears * X86_FEATURE_PGE has not been invoked yet. Though due to the * load_cr3() above the TLB has been flushed already. The * quirk is invoked before subsequent calls to __flush_tlb_all() * so proper operation is guaranteed. */ __flush_tlb_all(); #else printk(KERN_INFO "Command line: %s\n", boot_command_line); #endif /* * If we have OLPC OFW, we might end up relocating the fixmap due to * reserve_top(), so do this before touching the ioremap area. */ olpc_ofw_detect(); early_trap_init(); early_cpu_init(); early_ioremap_init(); setup_olpc_ofw_pgd(); ROOT_DEV = old_decode_dev(boot_params.hdr.root_dev); screen_info = boot_params.screen_info; edid_info = boot_params.edid_info; #ifdef CONFIG_X86_32 apm_info.bios = boot_params.apm_bios_info; ist_info = boot_params.ist_info; #endif saved_video_mode = boot_params.hdr.vid_mode; bootloader_type = boot_params.hdr.type_of_loader; if ((bootloader_type >> 4) == 0xe) { bootloader_type &= 0xf; bootloader_type |= (boot_params.hdr.ext_loader_type+0x10) << 4; } bootloader_version = bootloader_type & 0xf; bootloader_version |= boot_params.hdr.ext_loader_ver << 4; #ifdef CONFIG_BLK_DEV_RAM rd_image_start = boot_params.hdr.ram_size & RAMDISK_IMAGE_START_MASK; rd_prompt = ((boot_params.hdr.ram_size & RAMDISK_PROMPT_FLAG) != 0); rd_doload = ((boot_params.hdr.ram_size & RAMDISK_LOAD_FLAG) != 0); #endif #ifdef CONFIG_EFI if (!strncmp((char *)&boot_params.efi_info.efi_loader_signature, EFI32_LOADER_SIGNATURE, 4)) { set_bit(EFI_BOOT, &efi.flags); } else if (!strncmp((char *)&boot_params.efi_info.efi_loader_signature, EFI64_LOADER_SIGNATURE, 4)) { set_bit(EFI_BOOT, &efi.flags); set_bit(EFI_64BIT, &efi.flags); } if (efi_enabled(EFI_BOOT)) efi_memblock_x86_reserve_range(); #endif x86_init.oem.arch_setup(); iomem_resource.end = (1ULL << boot_cpu_data.x86_phys_bits) - 1; setup_memory_map(); parse_setup_data(); copy_edd(); if (!boot_params.hdr.root_flags) root_mountflags &= ~MS_RDONLY; init_mm.start_code = (unsigned long) _text; init_mm.end_code = (unsigned long) _etext; init_mm.end_data = (unsigned long) _edata; init_mm.brk = _brk_end; mpx_mm_init(&init_mm); code_resource.start = __pa_symbol(_text); code_resource.end = __pa_symbol(_etext)-1; data_resource.start = __pa_symbol(_etext); data_resource.end = __pa_symbol(_edata)-1; bss_resource.start = __pa_symbol(__bss_start); bss_resource.end = __pa_symbol(__bss_stop)-1; #ifdef CONFIG_CMDLINE_BOOL #ifdef CONFIG_CMDLINE_OVERRIDE strlcpy(boot_command_line, builtin_cmdline, COMMAND_LINE_SIZE); #else if (builtin_cmdline[0]) { /* append boot loader cmdline to builtin */ strlcat(builtin_cmdline, " ", COMMAND_LINE_SIZE); strlcat(builtin_cmdline, boot_command_line, COMMAND_LINE_SIZE); strlcpy(boot_command_line, builtin_cmdline, COMMAND_LINE_SIZE); } #endif #endif strlcpy(command_line, boot_command_line, COMMAND_LINE_SIZE); *cmdline_p = command_line; /* * x86_configure_nx() is called before parse_early_param() to detect * whether hardware doesn't support NX (so that the early EHCI debug * console setup can safely call set_fixmap()). It may then be called * again from within noexec_setup() during parsing early parameters * to honor the respective command line option. */ x86_configure_nx(); parse_early_param(); x86_report_nx(); /* after early param, so could get panic from serial */ memblock_x86_reserve_range_setup_data(); if (acpi_mps_check()) { #ifdef CONFIG_X86_LOCAL_APIC disable_apic = 1; #endif setup_clear_cpu_cap(X86_FEATURE_APIC); } #ifdef CONFIG_PCI if (pci_early_dump_regs) early_dump_pci_devices(); #endif /* update the e820_saved too */ e820_reserve_setup_data(); finish_e820_parsing(); if (efi_enabled(EFI_BOOT)) efi_init(); dmi_scan_machine(); dmi_memdev_walk(); dmi_set_dump_stack_arch_desc(); /* * VMware detection requires dmi to be available, so this * needs to be done after dmi_scan_machine, for the BP. */ init_hypervisor_platform(); x86_init.resources.probe_roms(); /* after parse_early_param, so could debug it */ insert_resource(&iomem_resource, &code_resource); insert_resource(&iomem_resource, &data_resource); insert_resource(&iomem_resource, &bss_resource); e820_add_kernel_range(); trim_bios_range(); #ifdef CONFIG_X86_32 if (ppro_with_ram_bug()) { e820_update_range(0x70000000ULL, 0x40000ULL, E820_RAM, E820_RESERVED); sanitize_e820_map(e820.map, ARRAY_SIZE(e820.map), &e820.nr_map); printk(KERN_INFO "fixed physical RAM map:\n"); e820_print_map("bad_ppro"); } #else early_gart_iommu_check(); #endif /* * partially used pages are not usable - thus * we are rounding upwards: */ max_pfn = e820_end_of_ram_pfn(); /* update e820 for memory not covered by WB MTRRs */ mtrr_bp_init(); if (mtrr_trim_uncached_memory(max_pfn)) max_pfn = e820_end_of_ram_pfn(); max_possible_pfn = max_pfn; #ifdef CONFIG_X86_32 /* max_low_pfn get updated here */ find_low_pfn_range(); #else check_x2apic(); /* How many end-of-memory variables you have, grandma! */ /* need this before calling reserve_initrd */ if (max_pfn > (1UL<<(32 - PAGE_SHIFT))) max_low_pfn = e820_end_of_low_ram_pfn(); else max_low_pfn = max_pfn; high_memory = (void *)__va(max_pfn * PAGE_SIZE - 1) + 1; #endif /* * Find and reserve possible boot-time SMP configuration: */ find_smp_config(); reserve_ibft_region(); early_alloc_pgt_buf(); /* * Need to conclude brk, before memblock_x86_fill() * it could use memblock_find_in_range, could overlap with * brk area. */ reserve_brk(); cleanup_highmap(); memblock_set_current_limit(ISA_END_ADDRESS); memblock_x86_fill(); if (efi_enabled(EFI_BOOT)) { efi_fake_memmap(); efi_find_mirror(); } /* * The EFI specification says that boot service code won't be called * after ExitBootServices(). This is, in fact, a lie. */ if (efi_enabled(EFI_MEMMAP)) efi_reserve_boot_services(); /* preallocate 4k for mptable mpc */ early_reserve_e820_mpc_new(); #ifdef CONFIG_X86_CHECK_BIOS_CORRUPTION setup_bios_corruption_check(); #endif #ifdef CONFIG_X86_32 printk(KERN_DEBUG "initial memory mapped: [mem 0x00000000-%#010lx]\n", (max_pfn_mapped<<PAGE_SHIFT) - 1); #endif reserve_real_mode(); trim_platform_memory_ranges(); trim_low_memory_range(); init_mem_mapping(); early_trap_pf_init(); setup_real_mode(); memblock_set_current_limit(get_max_mapped()); /* * NOTE: On x86-32, only from this point on, fixmaps are ready for use. */ #ifdef CONFIG_PROVIDE_OHCI1394_DMA_INIT if (init_ohci1394_dma_early) init_ohci1394_dma_on_all_controllers(); #endif /* Allocate bigger log buffer */ setup_log_buf(1); #ifdef CONFIG_EFI_SECURE_BOOT_SECURELEVEL if (boot_params.secure_boot) { set_securelevel(1); } #endif reserve_initrd(); #if defined(CONFIG_ACPI) && defined(CONFIG_BLK_DEV_INITRD) acpi_initrd_override((void *)initrd_start, initrd_end - initrd_start); #endif vsmp_init(); io_delay_init(); /* * Parse the ACPI tables for possible boot-time SMP configuration. */ acpi_boot_table_init(); early_acpi_boot_init(); initmem_init(); dma_contiguous_reserve(max_pfn_mapped << PAGE_SHIFT); /* * Reserve memory for crash kernel after SRAT is parsed so that it * won't consume hotpluggable memory. */ reserve_crashkernel(); memblock_find_dma_reserve(); #ifdef CONFIG_KVM_GUEST kvmclock_init(); #endif x86_init.paging.pagetable_init(); kasan_init(); if (boot_cpu_data.cpuid_level >= 0) { /* A CPU has %cr4 if and only if it has CPUID */ mmu_cr4_features = __read_cr4(); if (trampoline_cr4_features) *trampoline_cr4_features = mmu_cr4_features; } #ifdef CONFIG_X86_32 /* sync back kernel address range */ clone_pgd_range(initial_page_table + KERNEL_PGD_BOUNDARY, swapper_pg_dir + KERNEL_PGD_BOUNDARY, KERNEL_PGD_PTRS); /* * sync back low identity map too. It is used for example * in the 32-bit EFI stub. */ clone_pgd_range(initial_page_table, swapper_pg_dir + KERNEL_PGD_BOUNDARY, min(KERNEL_PGD_PTRS, KERNEL_PGD_BOUNDARY)); #endif tboot_probe(); map_vsyscall(); generic_apic_probe(); early_quirks(); /* * Read APIC and some other early information from ACPI tables. */ acpi_boot_init(); sfi_init(); x86_dtb_init(); /* * get boot-time SMP configuration: */ if (smp_found_config) get_smp_config(); prefill_possible_map(); init_cpu_to_node(); init_apic_mappings(); io_apic_init_mappings(); kvm_guest_init(); e820_reserve_resources(); e820_mark_nosave_regions(max_low_pfn); x86_init.resources.reserve_resources(); e820_setup_gap(); #ifdef CONFIG_VT #if defined(CONFIG_VGA_CONSOLE) if (!efi_enabled(EFI_BOOT) || (efi_mem_type(0xa0000) != EFI_CONVENTIONAL_MEMORY)) conswitchp = &vga_con; #elif defined(CONFIG_DUMMY_CONSOLE) conswitchp = &dummy_con; #endif #endif x86_init.oem.banner(); x86_init.timers.wallclock_init(); mcheck_init(); arch_init_ideal_nops(); register_refined_jiffies(CLOCK_TICK_RATE); #ifdef CONFIG_EFI if (efi_enabled(EFI_BOOT)) efi_apply_memmap_quirks(); #endif } #ifdef CONFIG_X86_32 static struct resource video_ram_resource = { .name = "Video RAM area", .start = 0xa0000, .end = 0xbffff, .flags = IORESOURCE_BUSY | IORESOURCE_MEM }; void __init i386_reserve_resources(void) { request_resource(&iomem_resource, &video_ram_resource); reserve_standard_io_resources(); } #endif /* CONFIG_X86_32 */ static struct notifier_block kernel_offset_notifier = { .notifier_call = dump_kernel_offset }; static int __init register_kernel_offset_dumper(void) { atomic_notifier_chain_register(&panic_notifier_list, &kernel_offset_notifier); return 0; } __initcall(register_kernel_offset_dumper); void arch_show_smap(struct seq_file *m, struct vm_area_struct *vma) { if (!boot_cpu_has(X86_FEATURE_OSPKE)) return; seq_printf(m, "ProtectionKey: %8u\n", vma_pkey(vma)); }
./CrossVul/dataset_final_sorted/CWE-264/c/good_5018_0
crossvul-cpp_data_good_5861_3
/* * Glue code for the SHA512 Secure Hash Algorithm assembly implementation * using NEON instructions. * * Copyright © 2014 Jussi Kivilinna <jussi.kivilinna@iki.fi> * * This file is based on sha512_ssse3_glue.c: * Copyright (C) 2013 Intel Corporation * Author: Tim Chen <tim.c.chen@linux.intel.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 <crypto/internal/hash.h> #include <linux/init.h> #include <linux/module.h> #include <linux/mm.h> #include <linux/cryptohash.h> #include <linux/types.h> #include <linux/string.h> #include <crypto/sha.h> #include <asm/byteorder.h> #include <asm/simd.h> #include <asm/neon.h> static const u64 sha512_k[] = { 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL }; asmlinkage void sha512_transform_neon(u64 *digest, const void *data, const u64 k[], unsigned int num_blks); static int sha512_neon_init(struct shash_desc *desc) { struct sha512_state *sctx = shash_desc_ctx(desc); sctx->state[0] = SHA512_H0; sctx->state[1] = SHA512_H1; sctx->state[2] = SHA512_H2; sctx->state[3] = SHA512_H3; sctx->state[4] = SHA512_H4; sctx->state[5] = SHA512_H5; sctx->state[6] = SHA512_H6; sctx->state[7] = SHA512_H7; sctx->count[0] = sctx->count[1] = 0; return 0; } static int __sha512_neon_update(struct shash_desc *desc, const u8 *data, unsigned int len, unsigned int partial) { struct sha512_state *sctx = shash_desc_ctx(desc); unsigned int done = 0; sctx->count[0] += len; if (sctx->count[0] < len) sctx->count[1]++; if (partial) { done = SHA512_BLOCK_SIZE - partial; memcpy(sctx->buf + partial, data, done); sha512_transform_neon(sctx->state, sctx->buf, sha512_k, 1); } if (len - done >= SHA512_BLOCK_SIZE) { const unsigned int rounds = (len - done) / SHA512_BLOCK_SIZE; sha512_transform_neon(sctx->state, data + done, sha512_k, rounds); done += rounds * SHA512_BLOCK_SIZE; } memcpy(sctx->buf, data + done, len - done); return 0; } static int sha512_neon_update(struct shash_desc *desc, const u8 *data, unsigned int len) { struct sha512_state *sctx = shash_desc_ctx(desc); unsigned int partial = sctx->count[0] % SHA512_BLOCK_SIZE; int res; /* Handle the fast case right here */ if (partial + len < SHA512_BLOCK_SIZE) { sctx->count[0] += len; if (sctx->count[0] < len) sctx->count[1]++; memcpy(sctx->buf + partial, data, len); return 0; } if (!may_use_simd()) { res = crypto_sha512_update(desc, data, len); } else { kernel_neon_begin(); res = __sha512_neon_update(desc, data, len, partial); kernel_neon_end(); } return res; } /* Add padding and return the message digest. */ static int sha512_neon_final(struct shash_desc *desc, u8 *out) { struct sha512_state *sctx = shash_desc_ctx(desc); unsigned int i, index, padlen; __be64 *dst = (__be64 *)out; __be64 bits[2]; static const u8 padding[SHA512_BLOCK_SIZE] = { 0x80, }; /* save number of bits */ bits[1] = cpu_to_be64(sctx->count[0] << 3); bits[0] = cpu_to_be64(sctx->count[1] << 3 | sctx->count[0] >> 61); /* Pad out to 112 mod 128 and append length */ index = sctx->count[0] & 0x7f; padlen = (index < 112) ? (112 - index) : ((128+112) - index); if (!may_use_simd()) { crypto_sha512_update(desc, padding, padlen); crypto_sha512_update(desc, (const u8 *)&bits, sizeof(bits)); } else { kernel_neon_begin(); /* We need to fill a whole block for __sha512_neon_update() */ if (padlen <= 112) { sctx->count[0] += padlen; if (sctx->count[0] < padlen) sctx->count[1]++; memcpy(sctx->buf + index, padding, padlen); } else { __sha512_neon_update(desc, padding, padlen, index); } __sha512_neon_update(desc, (const u8 *)&bits, sizeof(bits), 112); kernel_neon_end(); } /* Store state in digest */ for (i = 0; i < 8; i++) dst[i] = cpu_to_be64(sctx->state[i]); /* Wipe context */ memset(sctx, 0, sizeof(*sctx)); return 0; } static int sha512_neon_export(struct shash_desc *desc, void *out) { struct sha512_state *sctx = shash_desc_ctx(desc); memcpy(out, sctx, sizeof(*sctx)); return 0; } static int sha512_neon_import(struct shash_desc *desc, const void *in) { struct sha512_state *sctx = shash_desc_ctx(desc); memcpy(sctx, in, sizeof(*sctx)); return 0; } static int sha384_neon_init(struct shash_desc *desc) { struct sha512_state *sctx = shash_desc_ctx(desc); sctx->state[0] = SHA384_H0; sctx->state[1] = SHA384_H1; sctx->state[2] = SHA384_H2; sctx->state[3] = SHA384_H3; sctx->state[4] = SHA384_H4; sctx->state[5] = SHA384_H5; sctx->state[6] = SHA384_H6; sctx->state[7] = SHA384_H7; sctx->count[0] = sctx->count[1] = 0; return 0; } static int sha384_neon_final(struct shash_desc *desc, u8 *hash) { u8 D[SHA512_DIGEST_SIZE]; sha512_neon_final(desc, D); memcpy(hash, D, SHA384_DIGEST_SIZE); memset(D, 0, SHA512_DIGEST_SIZE); return 0; } static struct shash_alg algs[] = { { .digestsize = SHA512_DIGEST_SIZE, .init = sha512_neon_init, .update = sha512_neon_update, .final = sha512_neon_final, .export = sha512_neon_export, .import = sha512_neon_import, .descsize = sizeof(struct sha512_state), .statesize = sizeof(struct sha512_state), .base = { .cra_name = "sha512", .cra_driver_name = "sha512-neon", .cra_priority = 250, .cra_flags = CRYPTO_ALG_TYPE_SHASH, .cra_blocksize = SHA512_BLOCK_SIZE, .cra_module = THIS_MODULE, } }, { .digestsize = SHA384_DIGEST_SIZE, .init = sha384_neon_init, .update = sha512_neon_update, .final = sha384_neon_final, .export = sha512_neon_export, .import = sha512_neon_import, .descsize = sizeof(struct sha512_state), .statesize = sizeof(struct sha512_state), .base = { .cra_name = "sha384", .cra_driver_name = "sha384-neon", .cra_priority = 250, .cra_flags = CRYPTO_ALG_TYPE_SHASH, .cra_blocksize = SHA384_BLOCK_SIZE, .cra_module = THIS_MODULE, } } }; static int __init sha512_neon_mod_init(void) { if (!cpu_has_neon()) return -ENODEV; return crypto_register_shashes(algs, ARRAY_SIZE(algs)); } static void __exit sha512_neon_mod_fini(void) { crypto_unregister_shashes(algs, ARRAY_SIZE(algs)); } module_init(sha512_neon_mod_init); module_exit(sha512_neon_mod_fini); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("SHA512 Secure Hash Algorithm, NEON accelerated"); MODULE_ALIAS_CRYPTO("sha512"); MODULE_ALIAS_CRYPTO("sha384");
./CrossVul/dataset_final_sorted/CWE-264/c/good_5861_3
crossvul-cpp_data_good_3438_3
/* * Linux NET3: IP/IP protocol decoder. * * Authors: * Sam Lantinga (slouken@cs.ucdavis.edu) 02/01/95 * * Fixes: * Alan Cox : Merged and made usable non modular (its so tiny its silly as * a module taking up 2 pages). * Alan Cox : Fixed bug with 1.3.18 and IPIP not working (now needs to set skb->h.iph) * to keep ip_forward happy. * Alan Cox : More fixes for 1.3.21, and firewall fix. Maybe this will work soon 8). * Kai Schulte : Fixed #defines for IP_FIREWALL->FIREWALL * David Woodhouse : Perform some basic ICMP handling. * IPIP Routing without decapsulation. * Carlos Picoto : GRE over IP support * Alexey Kuznetsov: Reworked. Really, now it is truncated version of ipv4/ip_gre.c. * I do not want to merge them together. * * 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. * */ /* tunnel.c: an IP tunnel driver The purpose of this driver is to provide an IP tunnel through which you can tunnel network traffic transparently across subnets. This was written by looking at Nick Holloway's dummy driver Thanks for the great code! -Sam Lantinga (slouken@cs.ucdavis.edu) 02/01/95 Minor tweaks: Cleaned up the code a little and added some pre-1.3.0 tweaks. dev->hard_header/hard_header_len changed to use no headers. Comments/bracketing tweaked. Made the tunnels use dev->name not tunnel: when error reporting. Added tx_dropped stat -Alan Cox (alan@lxorguk.ukuu.org.uk) 21 March 95 Reworked: Changed to tunnel to destination gateway in addition to the tunnel's pointopoint address Almost completely rewritten Note: There is currently no firewall or ICMP handling done. -Sam Lantinga (slouken@cs.ucdavis.edu) 02/13/96 */ /* Things I wish I had known when writing the tunnel driver: When the tunnel_xmit() function is called, the skb contains the packet to be sent (plus a great deal of extra info), and dev contains the tunnel device that _we_ are. When we are passed a packet, we are expected to fill in the source address with our source IP address. What is the proper way to allocate, copy and free a buffer? After you allocate it, it is a "0 length" chunk of memory starting at zero. If you want to add headers to the buffer later, you'll have to call "skb_reserve(skb, amount)" with the amount of memory you want reserved. Then, you call "skb_put(skb, amount)" with the amount of space you want in the buffer. skb_put() returns a pointer to the top (#0) of that buffer. skb->len is set to the amount of space you have "allocated" with skb_put(). You can then write up to skb->len bytes to that buffer. If you need more, you can call skb_put() again with the additional amount of space you need. You can find out how much more space you can allocate by calling "skb_tailroom(skb)". Now, to add header space, call "skb_push(skb, header_len)". This creates space at the beginning of the buffer and returns a pointer to this new space. If later you need to strip a header from a buffer, call "skb_pull(skb, header_len)". skb_headroom() will return how much space is left at the top of the buffer (before the main data). Remember, this headroom space must be reserved before the skb_put() function is called. */ /* This version of net/ipv4/ipip.c is cloned of net/ipv4/ip_gre.c For comments look at net/ipv4/ip_gre.c --ANK */ #include <linux/capability.h> #include <linux/module.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/slab.h> #include <asm/uaccess.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/in.h> #include <linux/tcp.h> #include <linux/udp.h> #include <linux/if_arp.h> #include <linux/mroute.h> #include <linux/init.h> #include <linux/netfilter_ipv4.h> #include <linux/if_ether.h> #include <net/sock.h> #include <net/ip.h> #include <net/icmp.h> #include <net/ipip.h> #include <net/inet_ecn.h> #include <net/xfrm.h> #include <net/net_namespace.h> #include <net/netns/generic.h> #define HASH_SIZE 16 #define HASH(addr) (((__force u32)addr^((__force u32)addr>>4))&0xF) static int ipip_net_id __read_mostly; struct ipip_net { struct ip_tunnel __rcu *tunnels_r_l[HASH_SIZE]; struct ip_tunnel __rcu *tunnels_r[HASH_SIZE]; struct ip_tunnel __rcu *tunnels_l[HASH_SIZE]; struct ip_tunnel __rcu *tunnels_wc[1]; struct ip_tunnel __rcu **tunnels[4]; struct net_device *fb_tunnel_dev; }; static int ipip_tunnel_init(struct net_device *dev); static void ipip_tunnel_setup(struct net_device *dev); static void ipip_dev_free(struct net_device *dev); /* * Locking : hash tables are protected by RCU and RTNL */ #define for_each_ip_tunnel_rcu(start) \ for (t = rcu_dereference(start); t; t = rcu_dereference(t->next)) /* often modified stats are per cpu, other are shared (netdev->stats) */ struct pcpu_tstats { unsigned long rx_packets; unsigned long rx_bytes; unsigned long tx_packets; unsigned long tx_bytes; }; static struct net_device_stats *ipip_get_stats(struct net_device *dev) { struct pcpu_tstats sum = { 0 }; int i; for_each_possible_cpu(i) { const struct pcpu_tstats *tstats = per_cpu_ptr(dev->tstats, i); sum.rx_packets += tstats->rx_packets; sum.rx_bytes += tstats->rx_bytes; sum.tx_packets += tstats->tx_packets; sum.tx_bytes += tstats->tx_bytes; } dev->stats.rx_packets = sum.rx_packets; dev->stats.rx_bytes = sum.rx_bytes; dev->stats.tx_packets = sum.tx_packets; dev->stats.tx_bytes = sum.tx_bytes; return &dev->stats; } static struct ip_tunnel * ipip_tunnel_lookup(struct net *net, __be32 remote, __be32 local) { unsigned int h0 = HASH(remote); unsigned int h1 = HASH(local); struct ip_tunnel *t; struct ipip_net *ipn = net_generic(net, ipip_net_id); for_each_ip_tunnel_rcu(ipn->tunnels_r_l[h0 ^ h1]) if (local == t->parms.iph.saddr && remote == t->parms.iph.daddr && (t->dev->flags&IFF_UP)) return t; for_each_ip_tunnel_rcu(ipn->tunnels_r[h0]) if (remote == t->parms.iph.daddr && (t->dev->flags&IFF_UP)) return t; for_each_ip_tunnel_rcu(ipn->tunnels_l[h1]) if (local == t->parms.iph.saddr && (t->dev->flags&IFF_UP)) return t; t = rcu_dereference(ipn->tunnels_wc[0]); if (t && (t->dev->flags&IFF_UP)) return t; return NULL; } static struct ip_tunnel __rcu **__ipip_bucket(struct ipip_net *ipn, struct ip_tunnel_parm *parms) { __be32 remote = parms->iph.daddr; __be32 local = parms->iph.saddr; unsigned int h = 0; int prio = 0; if (remote) { prio |= 2; h ^= HASH(remote); } if (local) { prio |= 1; h ^= HASH(local); } return &ipn->tunnels[prio][h]; } static inline struct ip_tunnel __rcu **ipip_bucket(struct ipip_net *ipn, struct ip_tunnel *t) { return __ipip_bucket(ipn, &t->parms); } static void ipip_tunnel_unlink(struct ipip_net *ipn, struct ip_tunnel *t) { struct ip_tunnel __rcu **tp; struct ip_tunnel *iter; for (tp = ipip_bucket(ipn, t); (iter = rtnl_dereference(*tp)) != NULL; tp = &iter->next) { if (t == iter) { rcu_assign_pointer(*tp, t->next); break; } } } static void ipip_tunnel_link(struct ipip_net *ipn, struct ip_tunnel *t) { struct ip_tunnel __rcu **tp = ipip_bucket(ipn, t); rcu_assign_pointer(t->next, rtnl_dereference(*tp)); rcu_assign_pointer(*tp, t); } static struct ip_tunnel * ipip_tunnel_locate(struct net *net, struct ip_tunnel_parm *parms, int create) { __be32 remote = parms->iph.daddr; __be32 local = parms->iph.saddr; struct ip_tunnel *t, *nt; struct ip_tunnel __rcu **tp; struct net_device *dev; char name[IFNAMSIZ]; struct ipip_net *ipn = net_generic(net, ipip_net_id); for (tp = __ipip_bucket(ipn, parms); (t = rtnl_dereference(*tp)) != NULL; tp = &t->next) { if (local == t->parms.iph.saddr && remote == t->parms.iph.daddr) return t; } if (!create) return NULL; if (parms->name[0]) strlcpy(name, parms->name, IFNAMSIZ); else strcpy(name, "tunl%d"); dev = alloc_netdev(sizeof(*t), name, ipip_tunnel_setup); if (dev == NULL) return NULL; dev_net_set(dev, net); if (strchr(name, '%')) { if (dev_alloc_name(dev, name) < 0) goto failed_free; } nt = netdev_priv(dev); nt->parms = *parms; if (ipip_tunnel_init(dev) < 0) goto failed_free; if (register_netdevice(dev) < 0) goto failed_free; dev_hold(dev); ipip_tunnel_link(ipn, nt); return nt; failed_free: ipip_dev_free(dev); return NULL; } /* called with RTNL */ static void ipip_tunnel_uninit(struct net_device *dev) { struct net *net = dev_net(dev); struct ipip_net *ipn = net_generic(net, ipip_net_id); if (dev == ipn->fb_tunnel_dev) rcu_assign_pointer(ipn->tunnels_wc[0], NULL); else ipip_tunnel_unlink(ipn, netdev_priv(dev)); dev_put(dev); } static int ipip_err(struct sk_buff *skb, u32 info) { /* All the routers (except for Linux) return only 8 bytes of packet payload. It means, that precise relaying of ICMP in the real Internet is absolutely infeasible. */ struct iphdr *iph = (struct iphdr *)skb->data; const int type = icmp_hdr(skb)->type; const int code = icmp_hdr(skb)->code; struct ip_tunnel *t; int err; switch (type) { default: case ICMP_PARAMETERPROB: return 0; case ICMP_DEST_UNREACH: switch (code) { case ICMP_SR_FAILED: case ICMP_PORT_UNREACH: /* Impossible event. */ return 0; case ICMP_FRAG_NEEDED: /* Soft state for pmtu is maintained by IP core. */ return 0; default: /* All others are translated to HOST_UNREACH. rfc2003 contains "deep thoughts" about NET_UNREACH, I believe they are just ether pollution. --ANK */ break; } break; case ICMP_TIME_EXCEEDED: if (code != ICMP_EXC_TTL) return 0; break; } err = -ENOENT; rcu_read_lock(); t = ipip_tunnel_lookup(dev_net(skb->dev), iph->daddr, iph->saddr); if (t == NULL || t->parms.iph.daddr == 0) goto out; err = 0; if (t->parms.iph.ttl == 0 && type == ICMP_TIME_EXCEEDED) goto out; if (time_before(jiffies, t->err_time + IPTUNNEL_ERR_TIMEO)) t->err_count++; else t->err_count = 1; t->err_time = jiffies; out: rcu_read_unlock(); return err; } static inline void ipip_ecn_decapsulate(const struct iphdr *outer_iph, struct sk_buff *skb) { struct iphdr *inner_iph = ip_hdr(skb); if (INET_ECN_is_ce(outer_iph->tos)) IP_ECN_set_ce(inner_iph); } static int ipip_rcv(struct sk_buff *skb) { struct ip_tunnel *tunnel; const struct iphdr *iph = ip_hdr(skb); rcu_read_lock(); tunnel = ipip_tunnel_lookup(dev_net(skb->dev), iph->saddr, iph->daddr); if (tunnel != NULL) { struct pcpu_tstats *tstats; if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) { rcu_read_unlock(); kfree_skb(skb); return 0; } secpath_reset(skb); skb->mac_header = skb->network_header; skb_reset_network_header(skb); skb->protocol = htons(ETH_P_IP); skb->pkt_type = PACKET_HOST; tstats = this_cpu_ptr(tunnel->dev->tstats); tstats->rx_packets++; tstats->rx_bytes += skb->len; __skb_tunnel_rx(skb, tunnel->dev); ipip_ecn_decapsulate(iph, skb); netif_rx(skb); rcu_read_unlock(); return 0; } rcu_read_unlock(); return -1; } /* * This function assumes it is being called from dev_queue_xmit() * and that skb is filled properly by that function. */ static netdev_tx_t ipip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); struct pcpu_tstats *tstats; struct iphdr *tiph = &tunnel->parms.iph; u8 tos = tunnel->parms.iph.tos; __be16 df = tiph->frag_off; struct rtable *rt; /* Route to the other host */ struct net_device *tdev; /* Device to other host */ struct iphdr *old_iph = ip_hdr(skb); struct iphdr *iph; /* Our new IP header */ unsigned int max_headroom; /* The extra header space needed */ __be32 dst = tiph->daddr; int mtu; if (skb->protocol != htons(ETH_P_IP)) goto tx_error; if (tos & 1) tos = old_iph->tos; if (!dst) { /* NBMA tunnel */ if ((rt = skb_rtable(skb)) == NULL) { dev->stats.tx_fifo_errors++; goto tx_error; } if ((dst = rt->rt_gateway) == 0) goto tx_error_icmp; } { struct flowi fl = { .oif = tunnel->parms.link, .fl4_dst = dst, .fl4_src= tiph->saddr, .fl4_tos = RT_TOS(tos), .proto = IPPROTO_IPIP }; if (ip_route_output_key(dev_net(dev), &rt, &fl)) { dev->stats.tx_carrier_errors++; goto tx_error_icmp; } } tdev = rt->dst.dev; if (tdev == dev) { ip_rt_put(rt); dev->stats.collisions++; goto tx_error; } df |= old_iph->frag_off & htons(IP_DF); if (df) { mtu = dst_mtu(&rt->dst) - sizeof(struct iphdr); if (mtu < 68) { dev->stats.collisions++; ip_rt_put(rt); goto tx_error; } if (skb_dst(skb)) skb_dst(skb)->ops->update_pmtu(skb_dst(skb), mtu); if ((old_iph->frag_off & htons(IP_DF)) && mtu < ntohs(old_iph->tot_len)) { icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED, htonl(mtu)); ip_rt_put(rt); goto tx_error; } } if (tunnel->err_count > 0) { if (time_before(jiffies, tunnel->err_time + IPTUNNEL_ERR_TIMEO)) { tunnel->err_count--; dst_link_failure(skb); } else tunnel->err_count = 0; } /* * Okay, now see if we can stuff it in the buffer as-is. */ max_headroom = (LL_RESERVED_SPACE(tdev)+sizeof(struct iphdr)); if (skb_headroom(skb) < max_headroom || skb_shared(skb) || (skb_cloned(skb) && !skb_clone_writable(skb, 0))) { struct sk_buff *new_skb = skb_realloc_headroom(skb, max_headroom); if (!new_skb) { ip_rt_put(rt); dev->stats.tx_dropped++; dev_kfree_skb(skb); return NETDEV_TX_OK; } if (skb->sk) skb_set_owner_w(new_skb, skb->sk); dev_kfree_skb(skb); skb = new_skb; old_iph = ip_hdr(skb); } skb->transport_header = skb->network_header; skb_push(skb, sizeof(struct iphdr)); skb_reset_network_header(skb); memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt)); IPCB(skb)->flags &= ~(IPSKB_XFRM_TUNNEL_SIZE | IPSKB_XFRM_TRANSFORMED | IPSKB_REROUTED); skb_dst_drop(skb); skb_dst_set(skb, &rt->dst); /* * Push down and install the IPIP header. */ iph = ip_hdr(skb); iph->version = 4; iph->ihl = sizeof(struct iphdr)>>2; iph->frag_off = df; iph->protocol = IPPROTO_IPIP; iph->tos = INET_ECN_encapsulate(tos, old_iph->tos); iph->daddr = rt->rt_dst; iph->saddr = rt->rt_src; if ((iph->ttl = tiph->ttl) == 0) iph->ttl = old_iph->ttl; nf_reset(skb); tstats = this_cpu_ptr(dev->tstats); __IPTUNNEL_XMIT(tstats, &dev->stats); return NETDEV_TX_OK; tx_error_icmp: dst_link_failure(skb); tx_error: dev->stats.tx_errors++; dev_kfree_skb(skb); return NETDEV_TX_OK; } static void ipip_tunnel_bind_dev(struct net_device *dev) { struct net_device *tdev = NULL; struct ip_tunnel *tunnel; struct iphdr *iph; tunnel = netdev_priv(dev); iph = &tunnel->parms.iph; if (iph->daddr) { struct flowi fl = { .oif = tunnel->parms.link, .fl4_dst = iph->daddr, .fl4_src = iph->saddr, .fl4_tos = RT_TOS(iph->tos), .proto = IPPROTO_IPIP }; struct rtable *rt; if (!ip_route_output_key(dev_net(dev), &rt, &fl)) { tdev = rt->dst.dev; ip_rt_put(rt); } dev->flags |= IFF_POINTOPOINT; } if (!tdev && tunnel->parms.link) tdev = __dev_get_by_index(dev_net(dev), tunnel->parms.link); if (tdev) { dev->hard_header_len = tdev->hard_header_len + sizeof(struct iphdr); dev->mtu = tdev->mtu - sizeof(struct iphdr); } dev->iflink = tunnel->parms.link; } static int ipip_tunnel_ioctl (struct net_device *dev, struct ifreq *ifr, int cmd) { int err = 0; struct ip_tunnel_parm p; struct ip_tunnel *t; struct net *net = dev_net(dev); struct ipip_net *ipn = net_generic(net, ipip_net_id); switch (cmd) { case SIOCGETTUNNEL: t = NULL; if (dev == ipn->fb_tunnel_dev) { if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p))) { err = -EFAULT; break; } t = ipip_tunnel_locate(net, &p, 0); } if (t == NULL) t = netdev_priv(dev); memcpy(&p, &t->parms, sizeof(p)); if (copy_to_user(ifr->ifr_ifru.ifru_data, &p, sizeof(p))) err = -EFAULT; break; case SIOCADDTUNNEL: case SIOCCHGTUNNEL: err = -EPERM; if (!capable(CAP_NET_ADMIN)) goto done; err = -EFAULT; if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p))) goto done; err = -EINVAL; if (p.iph.version != 4 || p.iph.protocol != IPPROTO_IPIP || p.iph.ihl != 5 || (p.iph.frag_off&htons(~IP_DF))) goto done; if (p.iph.ttl) p.iph.frag_off |= htons(IP_DF); t = ipip_tunnel_locate(net, &p, cmd == SIOCADDTUNNEL); if (dev != ipn->fb_tunnel_dev && cmd == SIOCCHGTUNNEL) { if (t != NULL) { if (t->dev != dev) { err = -EEXIST; break; } } else { if (((dev->flags&IFF_POINTOPOINT) && !p.iph.daddr) || (!(dev->flags&IFF_POINTOPOINT) && p.iph.daddr)) { err = -EINVAL; break; } t = netdev_priv(dev); ipip_tunnel_unlink(ipn, t); synchronize_net(); t->parms.iph.saddr = p.iph.saddr; t->parms.iph.daddr = p.iph.daddr; memcpy(dev->dev_addr, &p.iph.saddr, 4); memcpy(dev->broadcast, &p.iph.daddr, 4); ipip_tunnel_link(ipn, t); netdev_state_change(dev); } } if (t) { err = 0; if (cmd == SIOCCHGTUNNEL) { t->parms.iph.ttl = p.iph.ttl; t->parms.iph.tos = p.iph.tos; t->parms.iph.frag_off = p.iph.frag_off; if (t->parms.link != p.link) { t->parms.link = p.link; ipip_tunnel_bind_dev(dev); netdev_state_change(dev); } } if (copy_to_user(ifr->ifr_ifru.ifru_data, &t->parms, sizeof(p))) err = -EFAULT; } else err = (cmd == SIOCADDTUNNEL ? -ENOBUFS : -ENOENT); break; case SIOCDELTUNNEL: err = -EPERM; if (!capable(CAP_NET_ADMIN)) goto done; if (dev == ipn->fb_tunnel_dev) { err = -EFAULT; if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p))) goto done; err = -ENOENT; if ((t = ipip_tunnel_locate(net, &p, 0)) == NULL) goto done; err = -EPERM; if (t->dev == ipn->fb_tunnel_dev) goto done; dev = t->dev; } unregister_netdevice(dev); err = 0; break; default: err = -EINVAL; } done: return err; } static int ipip_tunnel_change_mtu(struct net_device *dev, int new_mtu) { if (new_mtu < 68 || new_mtu > 0xFFF8 - sizeof(struct iphdr)) return -EINVAL; dev->mtu = new_mtu; return 0; } static const struct net_device_ops ipip_netdev_ops = { .ndo_uninit = ipip_tunnel_uninit, .ndo_start_xmit = ipip_tunnel_xmit, .ndo_do_ioctl = ipip_tunnel_ioctl, .ndo_change_mtu = ipip_tunnel_change_mtu, .ndo_get_stats = ipip_get_stats, }; static void ipip_dev_free(struct net_device *dev) { free_percpu(dev->tstats); free_netdev(dev); } static void ipip_tunnel_setup(struct net_device *dev) { dev->netdev_ops = &ipip_netdev_ops; dev->destructor = ipip_dev_free; dev->type = ARPHRD_TUNNEL; dev->hard_header_len = LL_MAX_HEADER + sizeof(struct iphdr); dev->mtu = ETH_DATA_LEN - sizeof(struct iphdr); dev->flags = IFF_NOARP; dev->iflink = 0; dev->addr_len = 4; dev->features |= NETIF_F_NETNS_LOCAL; dev->features |= NETIF_F_LLTX; dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; } static int ipip_tunnel_init(struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); tunnel->dev = dev; strcpy(tunnel->parms.name, dev->name); memcpy(dev->dev_addr, &tunnel->parms.iph.saddr, 4); memcpy(dev->broadcast, &tunnel->parms.iph.daddr, 4); ipip_tunnel_bind_dev(dev); dev->tstats = alloc_percpu(struct pcpu_tstats); if (!dev->tstats) return -ENOMEM; return 0; } static int __net_init ipip_fb_tunnel_init(struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); struct iphdr *iph = &tunnel->parms.iph; struct ipip_net *ipn = net_generic(dev_net(dev), ipip_net_id); tunnel->dev = dev; strcpy(tunnel->parms.name, dev->name); iph->version = 4; iph->protocol = IPPROTO_IPIP; iph->ihl = 5; dev->tstats = alloc_percpu(struct pcpu_tstats); if (!dev->tstats) return -ENOMEM; dev_hold(dev); rcu_assign_pointer(ipn->tunnels_wc[0], tunnel); return 0; } static struct xfrm_tunnel ipip_handler __read_mostly = { .handler = ipip_rcv, .err_handler = ipip_err, .priority = 1, }; static const char banner[] __initconst = KERN_INFO "IPv4 over IPv4 tunneling driver\n"; static void ipip_destroy_tunnels(struct ipip_net *ipn, struct list_head *head) { int prio; for (prio = 1; prio < 4; prio++) { int h; for (h = 0; h < HASH_SIZE; h++) { struct ip_tunnel *t; t = rtnl_dereference(ipn->tunnels[prio][h]); while (t != NULL) { unregister_netdevice_queue(t->dev, head); t = rtnl_dereference(t->next); } } } } static int __net_init ipip_init_net(struct net *net) { struct ipip_net *ipn = net_generic(net, ipip_net_id); int err; ipn->tunnels[0] = ipn->tunnels_wc; ipn->tunnels[1] = ipn->tunnels_l; ipn->tunnels[2] = ipn->tunnels_r; ipn->tunnels[3] = ipn->tunnels_r_l; ipn->fb_tunnel_dev = alloc_netdev(sizeof(struct ip_tunnel), "tunl0", ipip_tunnel_setup); if (!ipn->fb_tunnel_dev) { err = -ENOMEM; goto err_alloc_dev; } dev_net_set(ipn->fb_tunnel_dev, net); err = ipip_fb_tunnel_init(ipn->fb_tunnel_dev); if (err) goto err_reg_dev; if ((err = register_netdev(ipn->fb_tunnel_dev))) goto err_reg_dev; return 0; err_reg_dev: ipip_dev_free(ipn->fb_tunnel_dev); err_alloc_dev: /* nothing */ return err; } static void __net_exit ipip_exit_net(struct net *net) { struct ipip_net *ipn = net_generic(net, ipip_net_id); LIST_HEAD(list); rtnl_lock(); ipip_destroy_tunnels(ipn, &list); unregister_netdevice_queue(ipn->fb_tunnel_dev, &list); unregister_netdevice_many(&list); rtnl_unlock(); } static struct pernet_operations ipip_net_ops = { .init = ipip_init_net, .exit = ipip_exit_net, .id = &ipip_net_id, .size = sizeof(struct ipip_net), }; static int __init ipip_init(void) { int err; printk(banner); err = register_pernet_device(&ipip_net_ops); if (err < 0) return err; err = xfrm4_tunnel_register(&ipip_handler, AF_INET); if (err < 0) { unregister_pernet_device(&ipip_net_ops); printk(KERN_INFO "ipip init: can't register tunnel\n"); } return err; } static void __exit ipip_fini(void) { if (xfrm4_tunnel_deregister(&ipip_handler, AF_INET)) printk(KERN_INFO "ipip close: can't deregister tunnel\n"); unregister_pernet_device(&ipip_net_ops); } module_init(ipip_init); module_exit(ipip_fini); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETDEV("tunl0");
./CrossVul/dataset_final_sorted/CWE-264/c/good_3438_3
crossvul-cpp_data_bad_5861_37
/* * Glue Code for SSE2 assembler versions of Serpent Cipher * * Copyright (c) 2011 Jussi Kivilinna <jussi.kivilinna@mbnet.fi> * * Glue code based on aesni-intel_glue.c by: * Copyright (C) 2008, Intel Corp. * Author: Huang Ying <ying.huang@intel.com> * * CBC & ECB parts based on code (crypto/cbc.c,ecb.c) by: * Copyright (c) 2006 Herbert Xu <herbert@gondor.apana.org.au> * CTR part based on code (crypto/ctr.c) by: * (C) Copyright IBM Corp. 2007 - Joy Latten <latten@us.ibm.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. * * 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/module.h> #include <linux/hardirq.h> #include <linux/types.h> #include <linux/crypto.h> #include <linux/err.h> #include <crypto/ablk_helper.h> #include <crypto/algapi.h> #include <crypto/serpent.h> #include <crypto/cryptd.h> #include <crypto/b128ops.h> #include <crypto/ctr.h> #include <crypto/lrw.h> #include <crypto/xts.h> #include <asm/crypto/serpent-sse2.h> #include <asm/crypto/glue_helper.h> static void serpent_decrypt_cbc_xway(void *ctx, u128 *dst, const u128 *src) { u128 ivs[SERPENT_PARALLEL_BLOCKS - 1]; unsigned int j; for (j = 0; j < SERPENT_PARALLEL_BLOCKS - 1; j++) ivs[j] = src[j]; serpent_dec_blk_xway(ctx, (u8 *)dst, (u8 *)src); for (j = 0; j < SERPENT_PARALLEL_BLOCKS - 1; j++) u128_xor(dst + (j + 1), dst + (j + 1), ivs + j); } static void serpent_crypt_ctr(void *ctx, u128 *dst, const u128 *src, le128 *iv) { be128 ctrblk; le128_to_be128(&ctrblk, iv); le128_inc(iv); __serpent_encrypt(ctx, (u8 *)&ctrblk, (u8 *)&ctrblk); u128_xor(dst, src, (u128 *)&ctrblk); } static void serpent_crypt_ctr_xway(void *ctx, u128 *dst, const u128 *src, le128 *iv) { be128 ctrblks[SERPENT_PARALLEL_BLOCKS]; unsigned int i; for (i = 0; i < SERPENT_PARALLEL_BLOCKS; i++) { if (dst != src) dst[i] = src[i]; le128_to_be128(&ctrblks[i], iv); le128_inc(iv); } serpent_enc_blk_xway_xor(ctx, (u8 *)dst, (u8 *)ctrblks); } static const struct common_glue_ctx serpent_enc = { .num_funcs = 2, .fpu_blocks_limit = SERPENT_PARALLEL_BLOCKS, .funcs = { { .num_blocks = SERPENT_PARALLEL_BLOCKS, .fn_u = { .ecb = GLUE_FUNC_CAST(serpent_enc_blk_xway) } }, { .num_blocks = 1, .fn_u = { .ecb = GLUE_FUNC_CAST(__serpent_encrypt) } } } }; static const struct common_glue_ctx serpent_ctr = { .num_funcs = 2, .fpu_blocks_limit = SERPENT_PARALLEL_BLOCKS, .funcs = { { .num_blocks = SERPENT_PARALLEL_BLOCKS, .fn_u = { .ctr = GLUE_CTR_FUNC_CAST(serpent_crypt_ctr_xway) } }, { .num_blocks = 1, .fn_u = { .ctr = GLUE_CTR_FUNC_CAST(serpent_crypt_ctr) } } } }; static const struct common_glue_ctx serpent_dec = { .num_funcs = 2, .fpu_blocks_limit = SERPENT_PARALLEL_BLOCKS, .funcs = { { .num_blocks = SERPENT_PARALLEL_BLOCKS, .fn_u = { .ecb = GLUE_FUNC_CAST(serpent_dec_blk_xway) } }, { .num_blocks = 1, .fn_u = { .ecb = GLUE_FUNC_CAST(__serpent_decrypt) } } } }; static const struct common_glue_ctx serpent_dec_cbc = { .num_funcs = 2, .fpu_blocks_limit = SERPENT_PARALLEL_BLOCKS, .funcs = { { .num_blocks = SERPENT_PARALLEL_BLOCKS, .fn_u = { .cbc = GLUE_CBC_FUNC_CAST(serpent_decrypt_cbc_xway) } }, { .num_blocks = 1, .fn_u = { .cbc = GLUE_CBC_FUNC_CAST(__serpent_decrypt) } } } }; static int ecb_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_ecb_crypt_128bit(&serpent_enc, desc, dst, src, nbytes); } static int ecb_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_ecb_crypt_128bit(&serpent_dec, desc, dst, src, nbytes); } static int cbc_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_cbc_encrypt_128bit(GLUE_FUNC_CAST(__serpent_encrypt), desc, dst, src, nbytes); } static int cbc_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_cbc_decrypt_128bit(&serpent_dec_cbc, desc, dst, src, nbytes); } static int ctr_crypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_ctr_crypt_128bit(&serpent_ctr, desc, dst, src, nbytes); } static inline bool serpent_fpu_begin(bool fpu_enabled, unsigned int nbytes) { return glue_fpu_begin(SERPENT_BLOCK_SIZE, SERPENT_PARALLEL_BLOCKS, NULL, fpu_enabled, nbytes); } static inline void serpent_fpu_end(bool fpu_enabled) { glue_fpu_end(fpu_enabled); } struct crypt_priv { struct serpent_ctx *ctx; bool fpu_enabled; }; static void encrypt_callback(void *priv, u8 *srcdst, unsigned int nbytes) { const unsigned int bsize = SERPENT_BLOCK_SIZE; struct crypt_priv *ctx = priv; int i; ctx->fpu_enabled = serpent_fpu_begin(ctx->fpu_enabled, nbytes); if (nbytes == bsize * SERPENT_PARALLEL_BLOCKS) { serpent_enc_blk_xway(ctx->ctx, srcdst, srcdst); return; } for (i = 0; i < nbytes / bsize; i++, srcdst += bsize) __serpent_encrypt(ctx->ctx, srcdst, srcdst); } static void decrypt_callback(void *priv, u8 *srcdst, unsigned int nbytes) { const unsigned int bsize = SERPENT_BLOCK_SIZE; struct crypt_priv *ctx = priv; int i; ctx->fpu_enabled = serpent_fpu_begin(ctx->fpu_enabled, nbytes); if (nbytes == bsize * SERPENT_PARALLEL_BLOCKS) { serpent_dec_blk_xway(ctx->ctx, srcdst, srcdst); return; } for (i = 0; i < nbytes / bsize; i++, srcdst += bsize) __serpent_decrypt(ctx->ctx, srcdst, srcdst); } struct serpent_lrw_ctx { struct lrw_table_ctx lrw_table; struct serpent_ctx serpent_ctx; }; static int lrw_serpent_setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen) { struct serpent_lrw_ctx *ctx = crypto_tfm_ctx(tfm); int err; err = __serpent_setkey(&ctx->serpent_ctx, key, keylen - SERPENT_BLOCK_SIZE); if (err) return err; return lrw_init_table(&ctx->lrw_table, key + keylen - SERPENT_BLOCK_SIZE); } static int lrw_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct serpent_lrw_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); be128 buf[SERPENT_PARALLEL_BLOCKS]; struct crypt_priv crypt_ctx = { .ctx = &ctx->serpent_ctx, .fpu_enabled = false, }; struct lrw_crypt_req req = { .tbuf = buf, .tbuflen = sizeof(buf), .table_ctx = &ctx->lrw_table, .crypt_ctx = &crypt_ctx, .crypt_fn = encrypt_callback, }; int ret; desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP; ret = lrw_crypt(desc, dst, src, nbytes, &req); serpent_fpu_end(crypt_ctx.fpu_enabled); return ret; } static int lrw_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct serpent_lrw_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); be128 buf[SERPENT_PARALLEL_BLOCKS]; struct crypt_priv crypt_ctx = { .ctx = &ctx->serpent_ctx, .fpu_enabled = false, }; struct lrw_crypt_req req = { .tbuf = buf, .tbuflen = sizeof(buf), .table_ctx = &ctx->lrw_table, .crypt_ctx = &crypt_ctx, .crypt_fn = decrypt_callback, }; int ret; desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP; ret = lrw_crypt(desc, dst, src, nbytes, &req); serpent_fpu_end(crypt_ctx.fpu_enabled); return ret; } static void lrw_exit_tfm(struct crypto_tfm *tfm) { struct serpent_lrw_ctx *ctx = crypto_tfm_ctx(tfm); lrw_free_table(&ctx->lrw_table); } struct serpent_xts_ctx { struct serpent_ctx tweak_ctx; struct serpent_ctx crypt_ctx; }; static int xts_serpent_setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen) { struct serpent_xts_ctx *ctx = crypto_tfm_ctx(tfm); u32 *flags = &tfm->crt_flags; int err; /* key consists of keys of equal size concatenated, therefore * the length must be even */ if (keylen % 2) { *flags |= CRYPTO_TFM_RES_BAD_KEY_LEN; return -EINVAL; } /* first half of xts-key is for crypt */ err = __serpent_setkey(&ctx->crypt_ctx, key, keylen / 2); if (err) return err; /* second half of xts-key is for tweak */ return __serpent_setkey(&ctx->tweak_ctx, key + keylen / 2, keylen / 2); } static int xts_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct serpent_xts_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); be128 buf[SERPENT_PARALLEL_BLOCKS]; struct crypt_priv crypt_ctx = { .ctx = &ctx->crypt_ctx, .fpu_enabled = false, }; struct xts_crypt_req req = { .tbuf = buf, .tbuflen = sizeof(buf), .tweak_ctx = &ctx->tweak_ctx, .tweak_fn = XTS_TWEAK_CAST(__serpent_encrypt), .crypt_ctx = &crypt_ctx, .crypt_fn = encrypt_callback, }; int ret; desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP; ret = xts_crypt(desc, dst, src, nbytes, &req); serpent_fpu_end(crypt_ctx.fpu_enabled); return ret; } static int xts_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct serpent_xts_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); be128 buf[SERPENT_PARALLEL_BLOCKS]; struct crypt_priv crypt_ctx = { .ctx = &ctx->crypt_ctx, .fpu_enabled = false, }; struct xts_crypt_req req = { .tbuf = buf, .tbuflen = sizeof(buf), .tweak_ctx = &ctx->tweak_ctx, .tweak_fn = XTS_TWEAK_CAST(__serpent_encrypt), .crypt_ctx = &crypt_ctx, .crypt_fn = decrypt_callback, }; int ret; desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP; ret = xts_crypt(desc, dst, src, nbytes, &req); serpent_fpu_end(crypt_ctx.fpu_enabled); return ret; } static struct crypto_alg serpent_algs[10] = { { .cra_name = "__ecb-serpent-sse2", .cra_driver_name = "__driver-ecb-serpent-sse2", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct serpent_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .setkey = serpent_setkey, .encrypt = ecb_encrypt, .decrypt = ecb_decrypt, }, }, }, { .cra_name = "__cbc-serpent-sse2", .cra_driver_name = "__driver-cbc-serpent-sse2", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct serpent_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .setkey = serpent_setkey, .encrypt = cbc_encrypt, .decrypt = cbc_decrypt, }, }, }, { .cra_name = "__ctr-serpent-sse2", .cra_driver_name = "__driver-ctr-serpent-sse2", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = 1, .cra_ctxsize = sizeof(struct serpent_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = serpent_setkey, .encrypt = ctr_crypt, .decrypt = ctr_crypt, }, }, }, { .cra_name = "__lrw-serpent-sse2", .cra_driver_name = "__driver-lrw-serpent-sse2", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct serpent_lrw_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_exit = lrw_exit_tfm, .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE + SERPENT_BLOCK_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE + SERPENT_BLOCK_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = lrw_serpent_setkey, .encrypt = lrw_encrypt, .decrypt = lrw_decrypt, }, }, }, { .cra_name = "__xts-serpent-sse2", .cra_driver_name = "__driver-xts-serpent-sse2", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct serpent_xts_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE * 2, .max_keysize = SERPENT_MAX_KEY_SIZE * 2, .ivsize = SERPENT_BLOCK_SIZE, .setkey = xts_serpent_setkey, .encrypt = xts_encrypt, .decrypt = xts_decrypt, }, }, }, { .cra_name = "ecb(serpent)", .cra_driver_name = "ecb-serpent-sse2", .cra_priority = 400, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .setkey = ablk_set_key, .encrypt = ablk_encrypt, .decrypt = ablk_decrypt, }, }, }, { .cra_name = "cbc(serpent)", .cra_driver_name = "cbc-serpent-sse2", .cra_priority = 400, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = ablk_set_key, .encrypt = __ablk_encrypt, .decrypt = ablk_decrypt, }, }, }, { .cra_name = "ctr(serpent)", .cra_driver_name = "ctr-serpent-sse2", .cra_priority = 400, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = 1, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = ablk_set_key, .encrypt = ablk_encrypt, .decrypt = ablk_encrypt, .geniv = "chainiv", }, }, }, { .cra_name = "lrw(serpent)", .cra_driver_name = "lrw-serpent-sse2", .cra_priority = 400, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE + SERPENT_BLOCK_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE + SERPENT_BLOCK_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = ablk_set_key, .encrypt = ablk_encrypt, .decrypt = ablk_decrypt, }, }, }, { .cra_name = "xts(serpent)", .cra_driver_name = "xts-serpent-sse2", .cra_priority = 400, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE * 2, .max_keysize = SERPENT_MAX_KEY_SIZE * 2, .ivsize = SERPENT_BLOCK_SIZE, .setkey = ablk_set_key, .encrypt = ablk_encrypt, .decrypt = ablk_decrypt, }, }, } }; static int __init serpent_sse2_init(void) { if (!cpu_has_xmm2) { printk(KERN_INFO "SSE2 instructions are not detected.\n"); return -ENODEV; } return crypto_register_algs(serpent_algs, ARRAY_SIZE(serpent_algs)); } static void __exit serpent_sse2_exit(void) { crypto_unregister_algs(serpent_algs, ARRAY_SIZE(serpent_algs)); } module_init(serpent_sse2_init); module_exit(serpent_sse2_exit); MODULE_DESCRIPTION("Serpent Cipher Algorithm, SSE2 optimized"); MODULE_LICENSE("GPL"); MODULE_ALIAS("serpent");
./CrossVul/dataset_final_sorted/CWE-264/c/bad_5861_37
crossvul-cpp_data_good_2182_1
/* * Copyright (C) 2012 Daiki Ueno <ueno@unixuser.org> * Copyright (C) 2012 Red Hat, 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/>. */ #include <libfep/private.h> #include <sys/socket.h> #include <sys/un.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <stddef.h> /* offsetof */ #ifndef _LIBC char *program_name = "libfep"; #endif /** * SECTION:client * @short_description: Client connection to FEP server */ struct _FepClient { int control; FepEventFilter filter; void *filter_data; bool filter_running; FepList *messages; }; static const FepAttribute empty_attr = { .type = FEP_ATTR_TYPE_NONE, .value = 0, }; /** * fep_client_open: * @address: (allow-none): socket address of the FEP server * * Connect to the FEP server running at @address. If @address is * %NULL, it gets the address from the environment variable * `LIBFEP_CONTROL_SOCK`. * * Returns: a new #FepClient. */ FepClient * fep_client_open (const char *address) { FepClient *client; struct sockaddr_un sun; ssize_t sun_len; int retval; if (!address) address = getenv ("LIBFEP_CONTROL_SOCK"); if (!address) return NULL; if (strlen (address) + 1 >= sizeof(sun.sun_path)) { fep_log (FEP_LOG_LEVEL_WARNING, "unix domain socket path too long: %d + 1 >= %d", strlen (address), sizeof (sun.sun_path)); free (address); return NULL; } client = xzalloc (sizeof(FepClient)); client->filter_running = false; client->messages = NULL; memset (&sun, 0, sizeof(struct sockaddr_un)); sun.sun_family = AF_UNIX; memcpy (sun.sun_path, address, strlen (address)); sun_len = sizeof (struct sockaddr_un); client->control = socket (AF_UNIX, SOCK_STREAM, 0); if (client->control < 0) { free (client); return NULL; } retval = connect (client->control, (const struct sockaddr *) &sun, sun_len); if (retval < 0) { close (client->control); free (client); return NULL; } return client; } /** * fep_client_set_cursor_text: * @client: a #FepClient * @text: a cursor text * @attr: a #FepAttribute * * Request to display @text at the cursor position on the terminal. */ void fep_client_set_cursor_text (FepClient *client, const char *text, FepAttribute *attr) { FepControlMessage message; message.command = FEP_CONTROL_SET_CURSOR_TEXT; _fep_control_message_alloc_args (&message, 2); _fep_control_message_write_string_arg (&message, 0, text, strlen (text) + 1); _fep_control_message_write_attribute_arg (&message, 1, attr ? attr : &empty_attr); if (client->filter_running) client->messages = _fep_append_control_message (client->messages, &message); else _fep_write_control_message (client->control, &message); _fep_control_message_free_args (&message); } /** * fep_client_set_status_text: * @client: a #FepClient * @text: a status text * @attr: a #FepAttribute * * Request to display @text at the bottom of the terminal. */ void fep_client_set_status_text (FepClient *client, const char *text, FepAttribute *attr) { FepControlMessage message; message.command = FEP_CONTROL_SET_STATUS_TEXT; _fep_control_message_alloc_args (&message, 2); _fep_control_message_write_string_arg (&message, 0, text, strlen (text) + 1); _fep_control_message_write_attribute_arg (&message, 1, attr ? attr : &empty_attr); if (client->filter_running) client->messages = _fep_append_control_message (client->messages, &message); else _fep_write_control_message (client->control, &message); _fep_control_message_free_args (&message); } /** * fep_client_send_text: * @client: a #FepClient * @text: text to be sent * * Request to send @text to the child process of the FEP server. * @text will be converted from UTF-8 to the local encoding in the * server. */ void fep_client_send_text (FepClient *client, const char *text) { FepControlMessage message; message.command = FEP_CONTROL_SEND_TEXT; _fep_control_message_alloc_args (&message, 1); _fep_control_message_write_string_arg (&message, 0, text, strlen (text) + 1); if (client->filter_running) client->messages = _fep_append_control_message (client->messages, &message); else _fep_write_control_message (client->control, &message); _fep_control_message_free_args (&message); } /** * fep_client_send_data: * @client: a #FepClient * @data: data to be sent * @length: length of @data * * Request to send @data to the child process of the FEP server. */ void fep_client_send_data (FepClient *client, const char *data, size_t length) { FepControlMessage message; message.command = FEP_CONTROL_SEND_DATA; _fep_control_message_alloc_args (&message, 1); _fep_control_message_write_string_arg (&message, 0, data, length); if (client->filter_running) client->messages = _fep_append_control_message (client->messages, &message); else _fep_write_control_message (client->control, &message); _fep_control_message_free_args (&message); } /** * fep_client_forward_key_event: * @client: a #FepClient * @keyval: keysym value * @modifiers: modifiers * * Request to send key event to the child process of the FEP server. */ void fep_client_forward_key_event (FepClient *client, unsigned int keyval, FepModifierType modifiers) { FepControlMessage message; message.command = FEP_CONTROL_FORWARD_KEY_EVENT; _fep_control_message_alloc_args (&message, 2); _fep_control_message_write_uint32_arg (&message, 0, keyval); _fep_control_message_write_uint32_arg (&message, 1, modifiers); if (client->filter_running) client->messages = _fep_append_control_message (client->messages, &message); else _fep_write_control_message (client->control, &message); _fep_control_message_free_args (&message); } /** * fep_client_set_event_filter: * @client: a #FepClient * @filter: a filter function * @data: user supplied data * * Set a key event filter which will be called when client receives * key events. */ void fep_client_set_event_filter (FepClient *client, FepEventFilter filter, void *data) { client->filter = filter; client->filter_data = data; } /** * fep_client_get_poll_fd: * @client: a #FepClient * * Get the file descriptor of the control socket which can be used by poll(). * * Returns: a file descriptor */ int fep_client_get_poll_fd (FepClient *client) { return client->control; } static void command_key_event (FepClient *client, FepControlMessage *request, FepControlMessage *response) { FepEventKey event; int retval; uint32_t intval; retval = _fep_control_message_read_uint32_arg (request, 0, &intval); if (retval < 0) { fep_log (FEP_LOG_LEVEL_WARNING, "can't read keyval"); goto out; } event.keyval = intval; retval = _fep_control_message_read_uint32_arg (request, 1, &intval); if (retval < 0) { fep_log (FEP_LOG_LEVEL_WARNING, "can't read modifiers"); goto out; } event.modifiers = intval; out: response->command = FEP_CONTROL_RESPONSE; _fep_control_message_alloc_args (response, 2); _fep_control_message_write_uint8_arg (response, 0, FEP_CONTROL_KEY_EVENT); intval = retval; if (retval == 0 && client->filter) { event.event.type = FEP_KEY_PRESS; event.source = request->args[2].str; event.source_length = request->args[2].len; intval = client->filter ((FepEvent *) &event, client->filter_data); _fep_control_message_write_uint32_arg (response, 1, intval); } /* If key is not handled, send back the original input to the server. */ if (intval == 0) fep_client_send_data (client, request->args[2].str, request->args[2].len); } static void command_resize_event (FepClient *client, FepControlMessage *request, FepControlMessage *response) { FepEventResize event; int retval; uint32_t intval; retval = _fep_control_message_read_uint32_arg (request, 0, &intval); if (retval < 0) { fep_log (FEP_LOG_LEVEL_WARNING, "can't read keyval"); goto out; } event.cols = intval; retval = _fep_control_message_read_uint32_arg (request, 1, &intval); if (retval < 0) { fep_log (FEP_LOG_LEVEL_WARNING, "can't read modifiers"); goto out; } event.rows = intval; out: response->command = FEP_CONTROL_RESPONSE; _fep_control_message_alloc_args (response, 2); _fep_control_message_write_uint8_arg (response, 0, FEP_CONTROL_RESIZE_EVENT); intval = retval; if (retval == 0 && client->filter) { event.event.type = FEP_RESIZED; intval = client->filter ((FepEvent *) &event, client->filter_data); _fep_control_message_write_uint32_arg (response, 1, intval); } } /** * fep_client_dispatch: * @client: a #FepClient * * Dispatch a request from server. * * Returns: 0 on success, -1 on failure. */ int fep_client_dispatch (FepClient *client) { static const struct { FepControlCommand command; void (*handler) (FepClient *client, FepControlMessage *request, FepControlMessage *response); } handlers[] = { { FEP_CONTROL_KEY_EVENT, command_key_event }, { FEP_CONTROL_RESIZE_EVENT, command_resize_event }, }; FepControlMessage request, response; int retval; int i; retval = _fep_read_control_message (client->control, &request); if (retval < 0) return -1; for (i = 0; i < SIZEOF (handlers) && handlers[i].command != request.command; i++) ; if (i == SIZEOF (handlers)) { _fep_control_message_free_args (&request); fep_log (FEP_LOG_LEVEL_WARNING, "no handler defined for %d", request.command); return -1; } client->filter_running = true; handlers[i].handler (client, &request, &response); _fep_control_message_free_args (&request); _fep_write_control_message (client->control, &response); _fep_control_message_free_args (&response); client->filter_running = false; /* flush queued messages during handler is executed */ while (client->messages) { FepList *_head = client->messages; FepControlMessage *_message = _head->data; client->messages = _head->next; _fep_write_control_message (client->control, _message); _fep_control_message_free (_message); free (_head); } return retval; } /** * fep_client_close: * @client: a FepClient * * Close the control socket and release the memory allocated for @client. */ void fep_client_close (FepClient *client) { close (client->control); free (client); }
./CrossVul/dataset_final_sorted/CWE-264/c/good_2182_1
crossvul-cpp_data_bad_1661_4
/* * setpwnam.c -- edit an entry in a password database. * * (c) 1994 Salvatore Valente <svalente@mit.edu> * This file is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * Edited 11/10/96 (DD/MM/YY ;-) by Nicolai Langfeldt (janl@math.uio.no) * to read /etc/passwd directly so that passwd, chsh and chfn can work on * machines that run NIS (previously YP). Changes will not be made to * usernames starting with +. * * This file is distributed with no warranty. * * Usage: * 1) get a struct passwd * from getpwnam(). * You should assume a struct passwd has an infinite number of fields, so * you should not try to create one from scratch. * 2) edit the fields you want to edit. * 3) call setpwnam() with the edited struct passwd. * * A _normal user_ program should never directly manipulate etc/passwd but * /use getpwnam() and (family, as well as) setpwnam(). * * But, setpwnam was made to _edit_ the password file. For use by chfn, * chsh and passwd. _I_ _HAVE_ to read and write /etc/passwd directly. Let * those who say nay be forever silent and think about how getpwnam (and * family) works on a machine running YP. * * Added checks for failure of malloc() and removed error reporting to * stderr, this is a library function and should not print on the screen, * but return appropriate error codes. * 27-Jan-97 - poe@daimi.aau.dk * * Thanks to "two guys named Ian". * * $Author: poer $ * $Revision: 1.13 $ * $Date: 1997/06/23 08:26:29 $ */ #undef DEBUG #include <errno.h> #include <fcntl.h> #include <paths.h> #include <pwd.h> #include <shadow.h> #include <signal.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "c.h" #include "fileutils.h" #include "closestream.h" #include "setpwnam.h" static void pw_init(void); /* * setpwnam () -- * takes a struct passwd in which every field is filled in and valid. * If the given username exists in the passwd file, the entry is * replaced with the given entry. */ int setpwnam(struct passwd *pwd) { FILE *fp = NULL, *pwf = NULL; int save_errno; int found; int namelen; int buflen = 256; int contlen, rc; char *linebuf = NULL; char *tmpname = NULL; char *atomic_dir = "/etc"; pw_init(); if ((fp = xfmkstemp(&tmpname, atomic_dir)) == NULL) return -1; /* ptmp should be owned by root.root or root.wheel */ if (fchown(fileno(fp), (uid_t) 0, (gid_t) 0) < 0) goto fail; /* acquire exclusive lock */ if (lckpwdf() < 0) goto fail; pwf = fopen(PASSWD_FILE, "r"); if (!pwf) goto fail; namelen = strlen(pwd->pw_name); linebuf = malloc(buflen); if (!linebuf) goto fail; /* parse the passwd file */ found = false; /* Do you wonder why I don't use getpwent? Read comments at top of * file */ while (fgets(linebuf, buflen, pwf) != NULL) { contlen = strlen(linebuf); while (linebuf[contlen - 1] != '\n' && !feof(pwf)) { char *tmp; /* Extend input buffer if it failed getting the whole line, * so now we double the buffer size */ buflen *= 2; tmp = realloc(linebuf, buflen); if (tmp == NULL) goto fail; linebuf = tmp; /* And fill the rest of the buffer */ if (fgets(&linebuf[contlen], buflen / 2, pwf) == NULL) break; contlen = strlen(linebuf); /* That was a lot of work for nothing. Gimme perl! */ } /* Is this the username we were sent to change? */ if (!found && linebuf[namelen] == ':' && !strncmp(linebuf, pwd->pw_name, namelen)) { /* Yes! So go forth in the name of the Lord and * change it! */ if (putpwent(pwd, fp) < 0) goto fail; found = true; continue; } /* Nothing in particular happened, copy input to output */ fputs(linebuf, fp); } /* xfmkstemp is too restrictive by default for passwd file */ if (fchmod(fileno(fp), 0644) < 0) goto fail; rc = close_stream(fp); fp = NULL; if (rc != 0) goto fail; fclose(pwf); /* I don't think I want to know if this failed */ pwf = NULL; if (!found) { errno = ENOENT; /* give me something better */ goto fail; } /* we don't care if we can't remove the backup file */ unlink(PASSWD_FILE ".OLD"); /* we don't care if we can't create the backup file */ ignore_result(link(PASSWD_FILE, PASSWD_FILE ".OLD")); /* we DO care if we can't rename to the passwd file */ if (rename(tmpname, PASSWD_FILE) < 0) goto fail; /* finally: success */ ulckpwdf(); return 0; fail: save_errno = errno; ulckpwdf(); if (fp != NULL) fclose(fp); if (tmpname != NULL) unlink(tmpname); free(tmpname); if (pwf != NULL) fclose(pwf); free(linebuf); errno = save_errno; return -1; } /* Set up the limits so that we're not foiled */ static void pw_init(void) { struct rlimit rlim; /* Unlimited resource limits. */ rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY; setrlimit(RLIMIT_CPU, &rlim); setrlimit(RLIMIT_FSIZE, &rlim); setrlimit(RLIMIT_STACK, &rlim); setrlimit(RLIMIT_DATA, &rlim); setrlimit(RLIMIT_RSS, &rlim); #ifndef DEBUG /* Don't drop core (not really necessary, but GP's). */ rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); #endif /* Turn off signals. */ signal(SIGALRM, SIG_IGN); signal(SIGHUP, SIG_IGN); signal(SIGINT, SIG_IGN); signal(SIGPIPE, SIG_IGN); signal(SIGQUIT, SIG_IGN); signal(SIGTERM, SIG_IGN); signal(SIGTSTP, SIG_IGN); signal(SIGTTOU, SIG_IGN); /* Create with exact permissions. */ umask(0); }
./CrossVul/dataset_final_sorted/CWE-264/c/bad_1661_4
crossvul-cpp_data_good_2190_3
/* * Copyright (c) 2000-2005 Silicon Graphics, Inc. * 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. * * This program is distributed in the hope that it would 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 the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "xfs.h" #include "xfs_fs.h" #include "xfs_shared.h" #include "xfs_format.h" #include "xfs_log_format.h" #include "xfs_trans_resv.h" #include "xfs_sb.h" #include "xfs_ag.h" #include "xfs_mount.h" #include "xfs_inode.h" #include "xfs_ioctl.h" #include "xfs_alloc.h" #include "xfs_rtalloc.h" #include "xfs_itable.h" #include "xfs_error.h" #include "xfs_attr.h" #include "xfs_bmap.h" #include "xfs_bmap_util.h" #include "xfs_fsops.h" #include "xfs_discard.h" #include "xfs_quota.h" #include "xfs_export.h" #include "xfs_trace.h" #include "xfs_icache.h" #include "xfs_symlink.h" #include "xfs_dinode.h" #include "xfs_trans.h" #include <linux/capability.h> #include <linux/dcache.h> #include <linux/mount.h> #include <linux/namei.h> #include <linux/pagemap.h> #include <linux/slab.h> #include <linux/exportfs.h> /* * xfs_find_handle maps from userspace xfs_fsop_handlereq structure to * a file or fs handle. * * XFS_IOC_PATH_TO_FSHANDLE * returns fs handle for a mount point or path within that mount point * XFS_IOC_FD_TO_HANDLE * returns full handle for a FD opened in user space * XFS_IOC_PATH_TO_HANDLE * returns full handle for a path */ int xfs_find_handle( unsigned int cmd, xfs_fsop_handlereq_t *hreq) { int hsize; xfs_handle_t handle; struct inode *inode; struct fd f = {NULL}; struct path path; int error; struct xfs_inode *ip; if (cmd == XFS_IOC_FD_TO_HANDLE) { f = fdget(hreq->fd); if (!f.file) return -EBADF; inode = file_inode(f.file); } else { error = user_lpath((const char __user *)hreq->path, &path); if (error) return error; inode = path.dentry->d_inode; } ip = XFS_I(inode); /* * We can only generate handles for inodes residing on a XFS filesystem, * and only for regular files, directories or symbolic links. */ error = -EINVAL; if (inode->i_sb->s_magic != XFS_SB_MAGIC) goto out_put; error = -EBADF; if (!S_ISREG(inode->i_mode) && !S_ISDIR(inode->i_mode) && !S_ISLNK(inode->i_mode)) goto out_put; memcpy(&handle.ha_fsid, ip->i_mount->m_fixedfsid, sizeof(xfs_fsid_t)); if (cmd == XFS_IOC_PATH_TO_FSHANDLE) { /* * This handle only contains an fsid, zero the rest. */ memset(&handle.ha_fid, 0, sizeof(handle.ha_fid)); hsize = sizeof(xfs_fsid_t); } else { handle.ha_fid.fid_len = sizeof(xfs_fid_t) - sizeof(handle.ha_fid.fid_len); handle.ha_fid.fid_pad = 0; handle.ha_fid.fid_gen = ip->i_d.di_gen; handle.ha_fid.fid_ino = ip->i_ino; hsize = XFS_HSIZE(handle); } error = -EFAULT; if (copy_to_user(hreq->ohandle, &handle, hsize) || copy_to_user(hreq->ohandlen, &hsize, sizeof(__s32))) goto out_put; error = 0; out_put: if (cmd == XFS_IOC_FD_TO_HANDLE) fdput(f); else path_put(&path); return error; } /* * No need to do permission checks on the various pathname components * as the handle operations are privileged. */ STATIC int xfs_handle_acceptable( void *context, struct dentry *dentry) { return 1; } /* * Convert userspace handle data into a dentry. */ struct dentry * xfs_handle_to_dentry( struct file *parfilp, void __user *uhandle, u32 hlen) { xfs_handle_t handle; struct xfs_fid64 fid; /* * Only allow handle opens under a directory. */ if (!S_ISDIR(file_inode(parfilp)->i_mode)) return ERR_PTR(-ENOTDIR); if (hlen != sizeof(xfs_handle_t)) return ERR_PTR(-EINVAL); if (copy_from_user(&handle, uhandle, hlen)) return ERR_PTR(-EFAULT); if (handle.ha_fid.fid_len != sizeof(handle.ha_fid) - sizeof(handle.ha_fid.fid_len)) return ERR_PTR(-EINVAL); memset(&fid, 0, sizeof(struct fid)); fid.ino = handle.ha_fid.fid_ino; fid.gen = handle.ha_fid.fid_gen; return exportfs_decode_fh(parfilp->f_path.mnt, (struct fid *)&fid, 3, FILEID_INO32_GEN | XFS_FILEID_TYPE_64FLAG, xfs_handle_acceptable, NULL); } STATIC struct dentry * xfs_handlereq_to_dentry( struct file *parfilp, xfs_fsop_handlereq_t *hreq) { return xfs_handle_to_dentry(parfilp, hreq->ihandle, hreq->ihandlen); } int xfs_open_by_handle( struct file *parfilp, xfs_fsop_handlereq_t *hreq) { const struct cred *cred = current_cred(); int error; int fd; int permflag; struct file *filp; struct inode *inode; struct dentry *dentry; fmode_t fmode; struct path path; if (!capable(CAP_SYS_ADMIN)) return -XFS_ERROR(EPERM); dentry = xfs_handlereq_to_dentry(parfilp, hreq); if (IS_ERR(dentry)) return PTR_ERR(dentry); inode = dentry->d_inode; /* Restrict xfs_open_by_handle to directories & regular files. */ if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode))) { error = -XFS_ERROR(EPERM); goto out_dput; } #if BITS_PER_LONG != 32 hreq->oflags |= O_LARGEFILE; #endif permflag = hreq->oflags; fmode = OPEN_FMODE(permflag); if ((!(permflag & O_APPEND) || (permflag & O_TRUNC)) && (fmode & FMODE_WRITE) && IS_APPEND(inode)) { error = -XFS_ERROR(EPERM); goto out_dput; } if ((fmode & FMODE_WRITE) && IS_IMMUTABLE(inode)) { error = -XFS_ERROR(EACCES); goto out_dput; } /* Can't write directories. */ if (S_ISDIR(inode->i_mode) && (fmode & FMODE_WRITE)) { error = -XFS_ERROR(EISDIR); goto out_dput; } fd = get_unused_fd_flags(0); if (fd < 0) { error = fd; goto out_dput; } path.mnt = parfilp->f_path.mnt; path.dentry = dentry; filp = dentry_open(&path, hreq->oflags, cred); dput(dentry); if (IS_ERR(filp)) { put_unused_fd(fd); return PTR_ERR(filp); } if (S_ISREG(inode->i_mode)) { filp->f_flags |= O_NOATIME; filp->f_mode |= FMODE_NOCMTIME; } fd_install(fd, filp); return fd; out_dput: dput(dentry); return error; } int xfs_readlink_by_handle( struct file *parfilp, xfs_fsop_handlereq_t *hreq) { struct dentry *dentry; __u32 olen; void *link; int error; if (!capable(CAP_SYS_ADMIN)) return -XFS_ERROR(EPERM); dentry = xfs_handlereq_to_dentry(parfilp, hreq); if (IS_ERR(dentry)) return PTR_ERR(dentry); /* Restrict this handle operation to symlinks only. */ if (!S_ISLNK(dentry->d_inode->i_mode)) { error = -XFS_ERROR(EINVAL); goto out_dput; } if (copy_from_user(&olen, hreq->ohandlen, sizeof(__u32))) { error = -XFS_ERROR(EFAULT); goto out_dput; } link = kmalloc(MAXPATHLEN+1, GFP_KERNEL); if (!link) { error = -XFS_ERROR(ENOMEM); goto out_dput; } error = -xfs_readlink(XFS_I(dentry->d_inode), link); if (error) goto out_kfree; error = readlink_copy(hreq->ohandle, olen, link); if (error) goto out_kfree; out_kfree: kfree(link); out_dput: dput(dentry); return error; } int xfs_set_dmattrs( xfs_inode_t *ip, u_int evmask, u_int16_t state) { xfs_mount_t *mp = ip->i_mount; xfs_trans_t *tp; int error; if (!capable(CAP_SYS_ADMIN)) return XFS_ERROR(EPERM); if (XFS_FORCED_SHUTDOWN(mp)) return XFS_ERROR(EIO); tp = xfs_trans_alloc(mp, XFS_TRANS_SET_DMATTRS); error = xfs_trans_reserve(tp, &M_RES(mp)->tr_ichange, 0, 0); if (error) { xfs_trans_cancel(tp, 0); return error; } xfs_ilock(ip, XFS_ILOCK_EXCL); xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL); ip->i_d.di_dmevmask = evmask; ip->i_d.di_dmstate = state; xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE); error = xfs_trans_commit(tp, 0); return error; } STATIC int xfs_fssetdm_by_handle( struct file *parfilp, void __user *arg) { int error; struct fsdmidata fsd; xfs_fsop_setdm_handlereq_t dmhreq; struct dentry *dentry; if (!capable(CAP_MKNOD)) return -XFS_ERROR(EPERM); if (copy_from_user(&dmhreq, arg, sizeof(xfs_fsop_setdm_handlereq_t))) return -XFS_ERROR(EFAULT); error = mnt_want_write_file(parfilp); if (error) return error; dentry = xfs_handlereq_to_dentry(parfilp, &dmhreq.hreq); if (IS_ERR(dentry)) { mnt_drop_write_file(parfilp); return PTR_ERR(dentry); } if (IS_IMMUTABLE(dentry->d_inode) || IS_APPEND(dentry->d_inode)) { error = -XFS_ERROR(EPERM); goto out; } if (copy_from_user(&fsd, dmhreq.data, sizeof(fsd))) { error = -XFS_ERROR(EFAULT); goto out; } error = -xfs_set_dmattrs(XFS_I(dentry->d_inode), fsd.fsd_dmevmask, fsd.fsd_dmstate); out: mnt_drop_write_file(parfilp); dput(dentry); return error; } STATIC int xfs_attrlist_by_handle( struct file *parfilp, void __user *arg) { int error = -ENOMEM; attrlist_cursor_kern_t *cursor; xfs_fsop_attrlist_handlereq_t al_hreq; struct dentry *dentry; char *kbuf; if (!capable(CAP_SYS_ADMIN)) return -XFS_ERROR(EPERM); if (copy_from_user(&al_hreq, arg, sizeof(xfs_fsop_attrlist_handlereq_t))) return -XFS_ERROR(EFAULT); if (al_hreq.buflen < sizeof(struct attrlist) || al_hreq.buflen > XATTR_LIST_MAX) return -XFS_ERROR(EINVAL); /* * Reject flags, only allow namespaces. */ if (al_hreq.flags & ~(ATTR_ROOT | ATTR_SECURE)) return -XFS_ERROR(EINVAL); dentry = xfs_handlereq_to_dentry(parfilp, &al_hreq.hreq); if (IS_ERR(dentry)) return PTR_ERR(dentry); kbuf = kmem_zalloc_large(al_hreq.buflen, KM_SLEEP); if (!kbuf) goto out_dput; cursor = (attrlist_cursor_kern_t *)&al_hreq.pos; error = -xfs_attr_list(XFS_I(dentry->d_inode), kbuf, al_hreq.buflen, al_hreq.flags, cursor); if (error) goto out_kfree; if (copy_to_user(al_hreq.buffer, kbuf, al_hreq.buflen)) error = -EFAULT; out_kfree: kmem_free(kbuf); out_dput: dput(dentry); return error; } int xfs_attrmulti_attr_get( struct inode *inode, unsigned char *name, unsigned char __user *ubuf, __uint32_t *len, __uint32_t flags) { unsigned char *kbuf; int error = EFAULT; if (*len > XATTR_SIZE_MAX) return EINVAL; kbuf = kmem_zalloc_large(*len, KM_SLEEP); if (!kbuf) return ENOMEM; error = xfs_attr_get(XFS_I(inode), name, kbuf, (int *)len, flags); if (error) goto out_kfree; if (copy_to_user(ubuf, kbuf, *len)) error = EFAULT; out_kfree: kmem_free(kbuf); return error; } int xfs_attrmulti_attr_set( struct inode *inode, unsigned char *name, const unsigned char __user *ubuf, __uint32_t len, __uint32_t flags) { unsigned char *kbuf; int error = EFAULT; if (IS_IMMUTABLE(inode) || IS_APPEND(inode)) return EPERM; if (len > XATTR_SIZE_MAX) return EINVAL; kbuf = memdup_user(ubuf, len); if (IS_ERR(kbuf)) return PTR_ERR(kbuf); error = xfs_attr_set(XFS_I(inode), name, kbuf, len, flags); return error; } int xfs_attrmulti_attr_remove( struct inode *inode, unsigned char *name, __uint32_t flags) { if (IS_IMMUTABLE(inode) || IS_APPEND(inode)) return EPERM; return xfs_attr_remove(XFS_I(inode), name, flags); } STATIC int xfs_attrmulti_by_handle( struct file *parfilp, void __user *arg) { int error; xfs_attr_multiop_t *ops; xfs_fsop_attrmulti_handlereq_t am_hreq; struct dentry *dentry; unsigned int i, size; unsigned char *attr_name; if (!capable(CAP_SYS_ADMIN)) return -XFS_ERROR(EPERM); if (copy_from_user(&am_hreq, arg, sizeof(xfs_fsop_attrmulti_handlereq_t))) return -XFS_ERROR(EFAULT); /* overflow check */ if (am_hreq.opcount >= INT_MAX / sizeof(xfs_attr_multiop_t)) return -E2BIG; dentry = xfs_handlereq_to_dentry(parfilp, &am_hreq.hreq); if (IS_ERR(dentry)) return PTR_ERR(dentry); error = E2BIG; size = am_hreq.opcount * sizeof(xfs_attr_multiop_t); if (!size || size > 16 * PAGE_SIZE) goto out_dput; ops = memdup_user(am_hreq.ops, size); if (IS_ERR(ops)) { error = PTR_ERR(ops); goto out_dput; } attr_name = kmalloc(MAXNAMELEN, GFP_KERNEL); if (!attr_name) goto out_kfree_ops; error = 0; for (i = 0; i < am_hreq.opcount; i++) { ops[i].am_error = strncpy_from_user((char *)attr_name, ops[i].am_attrname, MAXNAMELEN); if (ops[i].am_error == 0 || ops[i].am_error == MAXNAMELEN) error = -ERANGE; if (ops[i].am_error < 0) break; switch (ops[i].am_opcode) { case ATTR_OP_GET: ops[i].am_error = xfs_attrmulti_attr_get( dentry->d_inode, attr_name, ops[i].am_attrvalue, &ops[i].am_length, ops[i].am_flags); break; case ATTR_OP_SET: ops[i].am_error = mnt_want_write_file(parfilp); if (ops[i].am_error) break; ops[i].am_error = xfs_attrmulti_attr_set( dentry->d_inode, attr_name, ops[i].am_attrvalue, ops[i].am_length, ops[i].am_flags); mnt_drop_write_file(parfilp); break; case ATTR_OP_REMOVE: ops[i].am_error = mnt_want_write_file(parfilp); if (ops[i].am_error) break; ops[i].am_error = xfs_attrmulti_attr_remove( dentry->d_inode, attr_name, ops[i].am_flags); mnt_drop_write_file(parfilp); break; default: ops[i].am_error = EINVAL; } } if (copy_to_user(am_hreq.ops, ops, size)) error = XFS_ERROR(EFAULT); kfree(attr_name); out_kfree_ops: kfree(ops); out_dput: dput(dentry); return -error; } int xfs_ioc_space( struct xfs_inode *ip, struct inode *inode, struct file *filp, int ioflags, unsigned int cmd, xfs_flock64_t *bf) { struct xfs_mount *mp = ip->i_mount; struct xfs_trans *tp; struct iattr iattr; bool setprealloc = false; bool clrprealloc = false; int error; /* * Only allow the sys admin to reserve space unless * unwritten extents are enabled. */ if (!xfs_sb_version_hasextflgbit(&ip->i_mount->m_sb) && !capable(CAP_SYS_ADMIN)) return -XFS_ERROR(EPERM); if (inode->i_flags & (S_IMMUTABLE|S_APPEND)) return -XFS_ERROR(EPERM); if (!(filp->f_mode & FMODE_WRITE)) return -XFS_ERROR(EBADF); if (!S_ISREG(inode->i_mode)) return -XFS_ERROR(EINVAL); error = mnt_want_write_file(filp); if (error) return error; xfs_ilock(ip, XFS_IOLOCK_EXCL); switch (bf->l_whence) { case 0: /*SEEK_SET*/ break; case 1: /*SEEK_CUR*/ bf->l_start += filp->f_pos; break; case 2: /*SEEK_END*/ bf->l_start += XFS_ISIZE(ip); break; default: error = XFS_ERROR(EINVAL); goto out_unlock; } /* * length of <= 0 for resv/unresv/zero is invalid. length for * alloc/free is ignored completely and we have no idea what userspace * might have set it to, so set it to zero to allow range * checks to pass. */ switch (cmd) { case XFS_IOC_ZERO_RANGE: case XFS_IOC_RESVSP: case XFS_IOC_RESVSP64: case XFS_IOC_UNRESVSP: case XFS_IOC_UNRESVSP64: if (bf->l_len <= 0) { error = XFS_ERROR(EINVAL); goto out_unlock; } break; default: bf->l_len = 0; break; } if (bf->l_start < 0 || bf->l_start > mp->m_super->s_maxbytes || bf->l_start + bf->l_len < 0 || bf->l_start + bf->l_len >= mp->m_super->s_maxbytes) { error = XFS_ERROR(EINVAL); goto out_unlock; } switch (cmd) { case XFS_IOC_ZERO_RANGE: error = xfs_zero_file_space(ip, bf->l_start, bf->l_len); if (!error) setprealloc = true; break; case XFS_IOC_RESVSP: case XFS_IOC_RESVSP64: error = xfs_alloc_file_space(ip, bf->l_start, bf->l_len, XFS_BMAPI_PREALLOC); if (!error) setprealloc = true; break; case XFS_IOC_UNRESVSP: case XFS_IOC_UNRESVSP64: error = xfs_free_file_space(ip, bf->l_start, bf->l_len); break; case XFS_IOC_ALLOCSP: case XFS_IOC_ALLOCSP64: case XFS_IOC_FREESP: case XFS_IOC_FREESP64: if (bf->l_start > XFS_ISIZE(ip)) { error = xfs_alloc_file_space(ip, XFS_ISIZE(ip), bf->l_start - XFS_ISIZE(ip), 0); if (error) goto out_unlock; } iattr.ia_valid = ATTR_SIZE; iattr.ia_size = bf->l_start; error = xfs_setattr_size(ip, &iattr); if (!error) clrprealloc = true; break; default: ASSERT(0); error = XFS_ERROR(EINVAL); } if (error) goto out_unlock; tp = xfs_trans_alloc(mp, XFS_TRANS_WRITEID); error = xfs_trans_reserve(tp, &M_RES(mp)->tr_writeid, 0, 0); if (error) { xfs_trans_cancel(tp, 0); goto out_unlock; } xfs_ilock(ip, XFS_ILOCK_EXCL); xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL); if (!(ioflags & IO_INVIS)) { ip->i_d.di_mode &= ~S_ISUID; if (ip->i_d.di_mode & S_IXGRP) ip->i_d.di_mode &= ~S_ISGID; xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG); } if (setprealloc) ip->i_d.di_flags |= XFS_DIFLAG_PREALLOC; else if (clrprealloc) ip->i_d.di_flags &= ~XFS_DIFLAG_PREALLOC; xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE); if (filp->f_flags & O_DSYNC) xfs_trans_set_sync(tp); error = xfs_trans_commit(tp, 0); out_unlock: xfs_iunlock(ip, XFS_IOLOCK_EXCL); mnt_drop_write_file(filp); return -error; } STATIC int xfs_ioc_bulkstat( xfs_mount_t *mp, unsigned int cmd, void __user *arg) { xfs_fsop_bulkreq_t bulkreq; int count; /* # of records returned */ xfs_ino_t inlast; /* last inode number */ int done; int error; /* done = 1 if there are more stats to get and if bulkstat */ /* should be called again (unused here, but used in dmapi) */ if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (XFS_FORCED_SHUTDOWN(mp)) return -XFS_ERROR(EIO); if (copy_from_user(&bulkreq, arg, sizeof(xfs_fsop_bulkreq_t))) return -XFS_ERROR(EFAULT); if (copy_from_user(&inlast, bulkreq.lastip, sizeof(__s64))) return -XFS_ERROR(EFAULT); if ((count = bulkreq.icount) <= 0) return -XFS_ERROR(EINVAL); if (bulkreq.ubuffer == NULL) return -XFS_ERROR(EINVAL); if (cmd == XFS_IOC_FSINUMBERS) error = xfs_inumbers(mp, &inlast, &count, bulkreq.ubuffer, xfs_inumbers_fmt); else if (cmd == XFS_IOC_FSBULKSTAT_SINGLE) error = xfs_bulkstat_single(mp, &inlast, bulkreq.ubuffer, &done); else /* XFS_IOC_FSBULKSTAT */ error = xfs_bulkstat(mp, &inlast, &count, xfs_bulkstat_one, sizeof(xfs_bstat_t), bulkreq.ubuffer, &done); if (error) return -error; if (bulkreq.ocount != NULL) { if (copy_to_user(bulkreq.lastip, &inlast, sizeof(xfs_ino_t))) return -XFS_ERROR(EFAULT); if (copy_to_user(bulkreq.ocount, &count, sizeof(count))) return -XFS_ERROR(EFAULT); } return 0; } STATIC int xfs_ioc_fsgeometry_v1( xfs_mount_t *mp, void __user *arg) { xfs_fsop_geom_t fsgeo; int error; error = xfs_fs_geometry(mp, &fsgeo, 3); if (error) return -error; /* * Caller should have passed an argument of type * xfs_fsop_geom_v1_t. This is a proper subset of the * xfs_fsop_geom_t that xfs_fs_geometry() fills in. */ if (copy_to_user(arg, &fsgeo, sizeof(xfs_fsop_geom_v1_t))) return -XFS_ERROR(EFAULT); return 0; } STATIC int xfs_ioc_fsgeometry( xfs_mount_t *mp, void __user *arg) { xfs_fsop_geom_t fsgeo; int error; error = xfs_fs_geometry(mp, &fsgeo, 4); if (error) return -error; if (copy_to_user(arg, &fsgeo, sizeof(fsgeo))) return -XFS_ERROR(EFAULT); return 0; } /* * Linux extended inode flags interface. */ STATIC unsigned int xfs_merge_ioc_xflags( unsigned int flags, unsigned int start) { unsigned int xflags = start; if (flags & FS_IMMUTABLE_FL) xflags |= XFS_XFLAG_IMMUTABLE; else xflags &= ~XFS_XFLAG_IMMUTABLE; if (flags & FS_APPEND_FL) xflags |= XFS_XFLAG_APPEND; else xflags &= ~XFS_XFLAG_APPEND; if (flags & FS_SYNC_FL) xflags |= XFS_XFLAG_SYNC; else xflags &= ~XFS_XFLAG_SYNC; if (flags & FS_NOATIME_FL) xflags |= XFS_XFLAG_NOATIME; else xflags &= ~XFS_XFLAG_NOATIME; if (flags & FS_NODUMP_FL) xflags |= XFS_XFLAG_NODUMP; else xflags &= ~XFS_XFLAG_NODUMP; return xflags; } STATIC unsigned int xfs_di2lxflags( __uint16_t di_flags) { unsigned int flags = 0; if (di_flags & XFS_DIFLAG_IMMUTABLE) flags |= FS_IMMUTABLE_FL; if (di_flags & XFS_DIFLAG_APPEND) flags |= FS_APPEND_FL; if (di_flags & XFS_DIFLAG_SYNC) flags |= FS_SYNC_FL; if (di_flags & XFS_DIFLAG_NOATIME) flags |= FS_NOATIME_FL; if (di_flags & XFS_DIFLAG_NODUMP) flags |= FS_NODUMP_FL; return flags; } STATIC int xfs_ioc_fsgetxattr( xfs_inode_t *ip, int attr, void __user *arg) { struct fsxattr fa; memset(&fa, 0, sizeof(struct fsxattr)); xfs_ilock(ip, XFS_ILOCK_SHARED); fa.fsx_xflags = xfs_ip2xflags(ip); fa.fsx_extsize = ip->i_d.di_extsize << ip->i_mount->m_sb.sb_blocklog; fa.fsx_projid = xfs_get_projid(ip); if (attr) { if (ip->i_afp) { if (ip->i_afp->if_flags & XFS_IFEXTENTS) fa.fsx_nextents = ip->i_afp->if_bytes / sizeof(xfs_bmbt_rec_t); else fa.fsx_nextents = ip->i_d.di_anextents; } else fa.fsx_nextents = 0; } else { if (ip->i_df.if_flags & XFS_IFEXTENTS) fa.fsx_nextents = ip->i_df.if_bytes / sizeof(xfs_bmbt_rec_t); else fa.fsx_nextents = ip->i_d.di_nextents; } xfs_iunlock(ip, XFS_ILOCK_SHARED); if (copy_to_user(arg, &fa, sizeof(fa))) return -EFAULT; return 0; } STATIC void xfs_set_diflags( struct xfs_inode *ip, unsigned int xflags) { unsigned int di_flags; /* can't set PREALLOC this way, just preserve it */ di_flags = (ip->i_d.di_flags & XFS_DIFLAG_PREALLOC); if (xflags & XFS_XFLAG_IMMUTABLE) di_flags |= XFS_DIFLAG_IMMUTABLE; if (xflags & XFS_XFLAG_APPEND) di_flags |= XFS_DIFLAG_APPEND; if (xflags & XFS_XFLAG_SYNC) di_flags |= XFS_DIFLAG_SYNC; if (xflags & XFS_XFLAG_NOATIME) di_flags |= XFS_DIFLAG_NOATIME; if (xflags & XFS_XFLAG_NODUMP) di_flags |= XFS_DIFLAG_NODUMP; if (xflags & XFS_XFLAG_PROJINHERIT) di_flags |= XFS_DIFLAG_PROJINHERIT; if (xflags & XFS_XFLAG_NODEFRAG) di_flags |= XFS_DIFLAG_NODEFRAG; if (xflags & XFS_XFLAG_FILESTREAM) di_flags |= XFS_DIFLAG_FILESTREAM; if (S_ISDIR(ip->i_d.di_mode)) { if (xflags & XFS_XFLAG_RTINHERIT) di_flags |= XFS_DIFLAG_RTINHERIT; if (xflags & XFS_XFLAG_NOSYMLINKS) di_flags |= XFS_DIFLAG_NOSYMLINKS; if (xflags & XFS_XFLAG_EXTSZINHERIT) di_flags |= XFS_DIFLAG_EXTSZINHERIT; } else if (S_ISREG(ip->i_d.di_mode)) { if (xflags & XFS_XFLAG_REALTIME) di_flags |= XFS_DIFLAG_REALTIME; if (xflags & XFS_XFLAG_EXTSIZE) di_flags |= XFS_DIFLAG_EXTSIZE; } ip->i_d.di_flags = di_flags; } STATIC void xfs_diflags_to_linux( struct xfs_inode *ip) { struct inode *inode = VFS_I(ip); unsigned int xflags = xfs_ip2xflags(ip); if (xflags & XFS_XFLAG_IMMUTABLE) inode->i_flags |= S_IMMUTABLE; else inode->i_flags &= ~S_IMMUTABLE; if (xflags & XFS_XFLAG_APPEND) inode->i_flags |= S_APPEND; else inode->i_flags &= ~S_APPEND; if (xflags & XFS_XFLAG_SYNC) inode->i_flags |= S_SYNC; else inode->i_flags &= ~S_SYNC; if (xflags & XFS_XFLAG_NOATIME) inode->i_flags |= S_NOATIME; else inode->i_flags &= ~S_NOATIME; } #define FSX_PROJID 1 #define FSX_EXTSIZE 2 #define FSX_XFLAGS 4 #define FSX_NONBLOCK 8 STATIC int xfs_ioctl_setattr( xfs_inode_t *ip, struct fsxattr *fa, int mask) { struct xfs_mount *mp = ip->i_mount; struct xfs_trans *tp; unsigned int lock_flags = 0; struct xfs_dquot *udqp = NULL; struct xfs_dquot *pdqp = NULL; struct xfs_dquot *olddquot = NULL; int code; trace_xfs_ioctl_setattr(ip); if (mp->m_flags & XFS_MOUNT_RDONLY) return XFS_ERROR(EROFS); if (XFS_FORCED_SHUTDOWN(mp)) return XFS_ERROR(EIO); /* * Disallow 32bit project ids when projid32bit feature is not enabled. */ if ((mask & FSX_PROJID) && (fa->fsx_projid > (__uint16_t)-1) && !xfs_sb_version_hasprojid32bit(&ip->i_mount->m_sb)) return XFS_ERROR(EINVAL); /* * If disk quotas is on, we make sure that the dquots do exist on disk, * before we start any other transactions. Trying to do this later * is messy. We don't care to take a readlock to look at the ids * in inode here, because we can't hold it across the trans_reserve. * If the IDs do change before we take the ilock, we're covered * because the i_*dquot fields will get updated anyway. */ if (XFS_IS_QUOTA_ON(mp) && (mask & FSX_PROJID)) { code = xfs_qm_vop_dqalloc(ip, ip->i_d.di_uid, ip->i_d.di_gid, fa->fsx_projid, XFS_QMOPT_PQUOTA, &udqp, NULL, &pdqp); if (code) return code; } /* * For the other attributes, we acquire the inode lock and * first do an error checking pass. */ tp = xfs_trans_alloc(mp, XFS_TRANS_SETATTR_NOT_SIZE); code = xfs_trans_reserve(tp, &M_RES(mp)->tr_ichange, 0, 0); if (code) goto error_return; lock_flags = XFS_ILOCK_EXCL; xfs_ilock(ip, lock_flags); /* * CAP_FOWNER overrides the following restrictions: * * The user ID of the calling process must be equal * to the file owner ID, except in cases where the * CAP_FSETID capability is applicable. */ if (!inode_owner_or_capable(VFS_I(ip))) { code = XFS_ERROR(EPERM); goto error_return; } /* * Do a quota reservation only if projid is actually going to change. * Only allow changing of projid from init_user_ns since it is a * non user namespace aware identifier. */ if (mask & FSX_PROJID) { if (current_user_ns() != &init_user_ns) { code = XFS_ERROR(EINVAL); goto error_return; } if (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_PQUOTA_ON(mp) && xfs_get_projid(ip) != fa->fsx_projid) { ASSERT(tp); code = xfs_qm_vop_chown_reserve(tp, ip, udqp, NULL, pdqp, capable(CAP_FOWNER) ? XFS_QMOPT_FORCE_RES : 0); if (code) /* out of quota */ goto error_return; } } if (mask & FSX_EXTSIZE) { /* * Can't change extent size if any extents are allocated. */ if (ip->i_d.di_nextents && ((ip->i_d.di_extsize << mp->m_sb.sb_blocklog) != fa->fsx_extsize)) { code = XFS_ERROR(EINVAL); /* EFBIG? */ goto error_return; } /* * Extent size must be a multiple of the appropriate block * size, if set at all. It must also be smaller than the * maximum extent size supported by the filesystem. * * Also, for non-realtime files, limit the extent size hint to * half the size of the AGs in the filesystem so alignment * doesn't result in extents larger than an AG. */ if (fa->fsx_extsize != 0) { xfs_extlen_t size; xfs_fsblock_t extsize_fsb; extsize_fsb = XFS_B_TO_FSB(mp, fa->fsx_extsize); if (extsize_fsb > MAXEXTLEN) { code = XFS_ERROR(EINVAL); goto error_return; } if (XFS_IS_REALTIME_INODE(ip) || ((mask & FSX_XFLAGS) && (fa->fsx_xflags & XFS_XFLAG_REALTIME))) { size = mp->m_sb.sb_rextsize << mp->m_sb.sb_blocklog; } else { size = mp->m_sb.sb_blocksize; if (extsize_fsb > mp->m_sb.sb_agblocks / 2) { code = XFS_ERROR(EINVAL); goto error_return; } } if (fa->fsx_extsize % size) { code = XFS_ERROR(EINVAL); goto error_return; } } } if (mask & FSX_XFLAGS) { /* * Can't change realtime flag if any extents are allocated. */ if ((ip->i_d.di_nextents || ip->i_delayed_blks) && (XFS_IS_REALTIME_INODE(ip)) != (fa->fsx_xflags & XFS_XFLAG_REALTIME)) { code = XFS_ERROR(EINVAL); /* EFBIG? */ goto error_return; } /* * If realtime flag is set then must have realtime data. */ if ((fa->fsx_xflags & XFS_XFLAG_REALTIME)) { if ((mp->m_sb.sb_rblocks == 0) || (mp->m_sb.sb_rextsize == 0) || (ip->i_d.di_extsize % mp->m_sb.sb_rextsize)) { code = XFS_ERROR(EINVAL); goto error_return; } } /* * Can't modify an immutable/append-only file unless * we have appropriate permission. */ if ((ip->i_d.di_flags & (XFS_DIFLAG_IMMUTABLE|XFS_DIFLAG_APPEND) || (fa->fsx_xflags & (XFS_XFLAG_IMMUTABLE | XFS_XFLAG_APPEND))) && !capable(CAP_LINUX_IMMUTABLE)) { code = XFS_ERROR(EPERM); goto error_return; } } xfs_trans_ijoin(tp, ip, 0); /* * Change file ownership. Must be the owner or privileged. */ if (mask & FSX_PROJID) { /* * CAP_FSETID overrides the following restrictions: * * The set-user-ID and set-group-ID bits of a file will be * cleared upon successful return from chown() */ if ((ip->i_d.di_mode & (S_ISUID|S_ISGID)) && !capable_wrt_inode_uidgid(VFS_I(ip), CAP_FSETID)) ip->i_d.di_mode &= ~(S_ISUID|S_ISGID); /* * Change the ownerships and register quota modifications * in the transaction. */ if (xfs_get_projid(ip) != fa->fsx_projid) { if (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_PQUOTA_ON(mp)) { olddquot = xfs_qm_vop_chown(tp, ip, &ip->i_pdquot, pdqp); } xfs_set_projid(ip, fa->fsx_projid); /* * We may have to rev the inode as well as * the superblock version number since projids didn't * exist before DINODE_VERSION_2 and SB_VERSION_NLINK. */ if (ip->i_d.di_version == 1) xfs_bump_ino_vers2(tp, ip); } } if (mask & FSX_EXTSIZE) ip->i_d.di_extsize = fa->fsx_extsize >> mp->m_sb.sb_blocklog; if (mask & FSX_XFLAGS) { xfs_set_diflags(ip, fa->fsx_xflags); xfs_diflags_to_linux(ip); } xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_CHG); xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE); XFS_STATS_INC(xs_ig_attrchg); /* * If this is a synchronous mount, make sure that the * transaction goes to disk before returning to the user. * This is slightly sub-optimal in that truncates require * two sync transactions instead of one for wsync filesystems. * One for the truncate and one for the timestamps since we * don't want to change the timestamps unless we're sure the * truncate worked. Truncates are less than 1% of the laddis * mix so this probably isn't worth the trouble to optimize. */ if (mp->m_flags & XFS_MOUNT_WSYNC) xfs_trans_set_sync(tp); code = xfs_trans_commit(tp, 0); xfs_iunlock(ip, lock_flags); /* * Release any dquot(s) the inode had kept before chown. */ xfs_qm_dqrele(olddquot); xfs_qm_dqrele(udqp); xfs_qm_dqrele(pdqp); return code; error_return: xfs_qm_dqrele(udqp); xfs_qm_dqrele(pdqp); xfs_trans_cancel(tp, 0); if (lock_flags) xfs_iunlock(ip, lock_flags); return code; } STATIC int xfs_ioc_fssetxattr( xfs_inode_t *ip, struct file *filp, void __user *arg) { struct fsxattr fa; unsigned int mask; int error; if (copy_from_user(&fa, arg, sizeof(fa))) return -EFAULT; mask = FSX_XFLAGS | FSX_EXTSIZE | FSX_PROJID; if (filp->f_flags & (O_NDELAY|O_NONBLOCK)) mask |= FSX_NONBLOCK; error = mnt_want_write_file(filp); if (error) return error; error = xfs_ioctl_setattr(ip, &fa, mask); mnt_drop_write_file(filp); return -error; } STATIC int xfs_ioc_getxflags( xfs_inode_t *ip, void __user *arg) { unsigned int flags; flags = xfs_di2lxflags(ip->i_d.di_flags); if (copy_to_user(arg, &flags, sizeof(flags))) return -EFAULT; return 0; } STATIC int xfs_ioc_setxflags( xfs_inode_t *ip, struct file *filp, void __user *arg) { struct fsxattr fa; unsigned int flags; unsigned int mask; int error; if (copy_from_user(&flags, arg, sizeof(flags))) return -EFAULT; if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \ FS_NOATIME_FL | FS_NODUMP_FL | \ FS_SYNC_FL)) return -EOPNOTSUPP; mask = FSX_XFLAGS; if (filp->f_flags & (O_NDELAY|O_NONBLOCK)) mask |= FSX_NONBLOCK; fa.fsx_xflags = xfs_merge_ioc_xflags(flags, xfs_ip2xflags(ip)); error = mnt_want_write_file(filp); if (error) return error; error = xfs_ioctl_setattr(ip, &fa, mask); mnt_drop_write_file(filp); return -error; } STATIC int xfs_getbmap_format(void **ap, struct getbmapx *bmv, int *full) { struct getbmap __user *base = *ap; /* copy only getbmap portion (not getbmapx) */ if (copy_to_user(base, bmv, sizeof(struct getbmap))) return XFS_ERROR(EFAULT); *ap += sizeof(struct getbmap); return 0; } STATIC int xfs_ioc_getbmap( struct xfs_inode *ip, int ioflags, unsigned int cmd, void __user *arg) { struct getbmapx bmx; int error; if (copy_from_user(&bmx, arg, sizeof(struct getbmapx))) return -XFS_ERROR(EFAULT); if (bmx.bmv_count < 2) return -XFS_ERROR(EINVAL); bmx.bmv_iflags = (cmd == XFS_IOC_GETBMAPA ? BMV_IF_ATTRFORK : 0); if (ioflags & IO_INVIS) bmx.bmv_iflags |= BMV_IF_NO_DMAPI_READ; error = xfs_getbmap(ip, &bmx, xfs_getbmap_format, (struct getbmap *)arg+1); if (error) return -error; /* copy back header - only size of getbmap */ if (copy_to_user(arg, &bmx, sizeof(struct getbmap))) return -XFS_ERROR(EFAULT); return 0; } STATIC int xfs_getbmapx_format(void **ap, struct getbmapx *bmv, int *full) { struct getbmapx __user *base = *ap; if (copy_to_user(base, bmv, sizeof(struct getbmapx))) return XFS_ERROR(EFAULT); *ap += sizeof(struct getbmapx); return 0; } STATIC int xfs_ioc_getbmapx( struct xfs_inode *ip, void __user *arg) { struct getbmapx bmx; int error; if (copy_from_user(&bmx, arg, sizeof(bmx))) return -XFS_ERROR(EFAULT); if (bmx.bmv_count < 2) return -XFS_ERROR(EINVAL); if (bmx.bmv_iflags & (~BMV_IF_VALID)) return -XFS_ERROR(EINVAL); error = xfs_getbmap(ip, &bmx, xfs_getbmapx_format, (struct getbmapx *)arg+1); if (error) return -error; /* copy back header */ if (copy_to_user(arg, &bmx, sizeof(struct getbmapx))) return -XFS_ERROR(EFAULT); return 0; } int xfs_ioc_swapext( xfs_swapext_t *sxp) { xfs_inode_t *ip, *tip; struct fd f, tmp; int error = 0; /* Pull information for the target fd */ f = fdget((int)sxp->sx_fdtarget); if (!f.file) { error = XFS_ERROR(EINVAL); goto out; } if (!(f.file->f_mode & FMODE_WRITE) || !(f.file->f_mode & FMODE_READ) || (f.file->f_flags & O_APPEND)) { error = XFS_ERROR(EBADF); goto out_put_file; } tmp = fdget((int)sxp->sx_fdtmp); if (!tmp.file) { error = XFS_ERROR(EINVAL); goto out_put_file; } if (!(tmp.file->f_mode & FMODE_WRITE) || !(tmp.file->f_mode & FMODE_READ) || (tmp.file->f_flags & O_APPEND)) { error = XFS_ERROR(EBADF); goto out_put_tmp_file; } if (IS_SWAPFILE(file_inode(f.file)) || IS_SWAPFILE(file_inode(tmp.file))) { error = XFS_ERROR(EINVAL); goto out_put_tmp_file; } ip = XFS_I(file_inode(f.file)); tip = XFS_I(file_inode(tmp.file)); if (ip->i_mount != tip->i_mount) { error = XFS_ERROR(EINVAL); goto out_put_tmp_file; } if (ip->i_ino == tip->i_ino) { error = XFS_ERROR(EINVAL); goto out_put_tmp_file; } if (XFS_FORCED_SHUTDOWN(ip->i_mount)) { error = XFS_ERROR(EIO); goto out_put_tmp_file; } error = xfs_swap_extents(ip, tip, sxp); out_put_tmp_file: fdput(tmp); out_put_file: fdput(f); out: return error; } /* * Note: some of the ioctl's return positive numbers as a * byte count indicating success, such as readlink_by_handle. * So we don't "sign flip" like most other routines. This means * true errors need to be returned as a negative value. */ long xfs_file_ioctl( struct file *filp, unsigned int cmd, unsigned long p) { struct inode *inode = file_inode(filp); struct xfs_inode *ip = XFS_I(inode); struct xfs_mount *mp = ip->i_mount; void __user *arg = (void __user *)p; int ioflags = 0; int error; if (filp->f_mode & FMODE_NOCMTIME) ioflags |= IO_INVIS; trace_xfs_file_ioctl(ip); switch (cmd) { case FITRIM: return xfs_ioc_trim(mp, arg); case XFS_IOC_ALLOCSP: case XFS_IOC_FREESP: case XFS_IOC_RESVSP: case XFS_IOC_UNRESVSP: case XFS_IOC_ALLOCSP64: case XFS_IOC_FREESP64: case XFS_IOC_RESVSP64: case XFS_IOC_UNRESVSP64: case XFS_IOC_ZERO_RANGE: { xfs_flock64_t bf; if (copy_from_user(&bf, arg, sizeof(bf))) return -XFS_ERROR(EFAULT); return xfs_ioc_space(ip, inode, filp, ioflags, cmd, &bf); } case XFS_IOC_DIOINFO: { struct dioattr da; xfs_buftarg_t *target = XFS_IS_REALTIME_INODE(ip) ? mp->m_rtdev_targp : mp->m_ddev_targp; da.d_mem = da.d_miniosz = target->bt_logical_sectorsize; da.d_maxiosz = INT_MAX & ~(da.d_miniosz - 1); if (copy_to_user(arg, &da, sizeof(da))) return -XFS_ERROR(EFAULT); return 0; } case XFS_IOC_FSBULKSTAT_SINGLE: case XFS_IOC_FSBULKSTAT: case XFS_IOC_FSINUMBERS: return xfs_ioc_bulkstat(mp, cmd, arg); case XFS_IOC_FSGEOMETRY_V1: return xfs_ioc_fsgeometry_v1(mp, arg); case XFS_IOC_FSGEOMETRY: return xfs_ioc_fsgeometry(mp, arg); case XFS_IOC_GETVERSION: return put_user(inode->i_generation, (int __user *)arg); case XFS_IOC_FSGETXATTR: return xfs_ioc_fsgetxattr(ip, 0, arg); case XFS_IOC_FSGETXATTRA: return xfs_ioc_fsgetxattr(ip, 1, arg); case XFS_IOC_FSSETXATTR: return xfs_ioc_fssetxattr(ip, filp, arg); case XFS_IOC_GETXFLAGS: return xfs_ioc_getxflags(ip, arg); case XFS_IOC_SETXFLAGS: return xfs_ioc_setxflags(ip, filp, arg); case XFS_IOC_FSSETDM: { struct fsdmidata dmi; if (copy_from_user(&dmi, arg, sizeof(dmi))) return -XFS_ERROR(EFAULT); error = mnt_want_write_file(filp); if (error) return error; error = xfs_set_dmattrs(ip, dmi.fsd_dmevmask, dmi.fsd_dmstate); mnt_drop_write_file(filp); return -error; } case XFS_IOC_GETBMAP: case XFS_IOC_GETBMAPA: return xfs_ioc_getbmap(ip, ioflags, cmd, arg); case XFS_IOC_GETBMAPX: return xfs_ioc_getbmapx(ip, arg); case XFS_IOC_FD_TO_HANDLE: case XFS_IOC_PATH_TO_HANDLE: case XFS_IOC_PATH_TO_FSHANDLE: { xfs_fsop_handlereq_t hreq; if (copy_from_user(&hreq, arg, sizeof(hreq))) return -XFS_ERROR(EFAULT); return xfs_find_handle(cmd, &hreq); } case XFS_IOC_OPEN_BY_HANDLE: { xfs_fsop_handlereq_t hreq; if (copy_from_user(&hreq, arg, sizeof(xfs_fsop_handlereq_t))) return -XFS_ERROR(EFAULT); return xfs_open_by_handle(filp, &hreq); } case XFS_IOC_FSSETDM_BY_HANDLE: return xfs_fssetdm_by_handle(filp, arg); case XFS_IOC_READLINK_BY_HANDLE: { xfs_fsop_handlereq_t hreq; if (copy_from_user(&hreq, arg, sizeof(xfs_fsop_handlereq_t))) return -XFS_ERROR(EFAULT); return xfs_readlink_by_handle(filp, &hreq); } case XFS_IOC_ATTRLIST_BY_HANDLE: return xfs_attrlist_by_handle(filp, arg); case XFS_IOC_ATTRMULTI_BY_HANDLE: return xfs_attrmulti_by_handle(filp, arg); case XFS_IOC_SWAPEXT: { struct xfs_swapext sxp; if (copy_from_user(&sxp, arg, sizeof(xfs_swapext_t))) return -XFS_ERROR(EFAULT); error = mnt_want_write_file(filp); if (error) return error; error = xfs_ioc_swapext(&sxp); mnt_drop_write_file(filp); return -error; } case XFS_IOC_FSCOUNTS: { xfs_fsop_counts_t out; error = xfs_fs_counts(mp, &out); if (error) return -error; if (copy_to_user(arg, &out, sizeof(out))) return -XFS_ERROR(EFAULT); return 0; } case XFS_IOC_SET_RESBLKS: { xfs_fsop_resblks_t inout; __uint64_t in; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (mp->m_flags & XFS_MOUNT_RDONLY) return -XFS_ERROR(EROFS); if (copy_from_user(&inout, arg, sizeof(inout))) return -XFS_ERROR(EFAULT); error = mnt_want_write_file(filp); if (error) return error; /* input parameter is passed in resblks field of structure */ in = inout.resblks; error = xfs_reserve_blocks(mp, &in, &inout); mnt_drop_write_file(filp); if (error) return -error; if (copy_to_user(arg, &inout, sizeof(inout))) return -XFS_ERROR(EFAULT); return 0; } case XFS_IOC_GET_RESBLKS: { xfs_fsop_resblks_t out; if (!capable(CAP_SYS_ADMIN)) return -EPERM; error = xfs_reserve_blocks(mp, NULL, &out); if (error) return -error; if (copy_to_user(arg, &out, sizeof(out))) return -XFS_ERROR(EFAULT); return 0; } case XFS_IOC_FSGROWFSDATA: { xfs_growfs_data_t in; if (copy_from_user(&in, arg, sizeof(in))) return -XFS_ERROR(EFAULT); error = mnt_want_write_file(filp); if (error) return error; error = xfs_growfs_data(mp, &in); mnt_drop_write_file(filp); return -error; } case XFS_IOC_FSGROWFSLOG: { xfs_growfs_log_t in; if (copy_from_user(&in, arg, sizeof(in))) return -XFS_ERROR(EFAULT); error = mnt_want_write_file(filp); if (error) return error; error = xfs_growfs_log(mp, &in); mnt_drop_write_file(filp); return -error; } case XFS_IOC_FSGROWFSRT: { xfs_growfs_rt_t in; if (copy_from_user(&in, arg, sizeof(in))) return -XFS_ERROR(EFAULT); error = mnt_want_write_file(filp); if (error) return error; error = xfs_growfs_rt(mp, &in); mnt_drop_write_file(filp); return -error; } case XFS_IOC_GOINGDOWN: { __uint32_t in; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (get_user(in, (__uint32_t __user *)arg)) return -XFS_ERROR(EFAULT); error = xfs_fs_goingdown(mp, in); return -error; } case XFS_IOC_ERROR_INJECTION: { xfs_error_injection_t in; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (copy_from_user(&in, arg, sizeof(in))) return -XFS_ERROR(EFAULT); error = xfs_errortag_add(in.errtag, mp); return -error; } case XFS_IOC_ERROR_CLEARALL: if (!capable(CAP_SYS_ADMIN)) return -EPERM; error = xfs_errortag_clearall(mp, 1); return -error; case XFS_IOC_FREE_EOFBLOCKS: { struct xfs_fs_eofblocks eofb; struct xfs_eofblocks keofb; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (mp->m_flags & XFS_MOUNT_RDONLY) return -XFS_ERROR(EROFS); if (copy_from_user(&eofb, arg, sizeof(eofb))) return -XFS_ERROR(EFAULT); error = xfs_fs_eofblocks_from_user(&eofb, &keofb); if (error) return -error; return -xfs_icache_free_eofblocks(mp, &keofb); } default: return -ENOTTY; } }
./CrossVul/dataset_final_sorted/CWE-264/c/good_2190_3
crossvul-cpp_data_bad_1661_1
/* * Copyright (C) 2012 Sami Kerola <kerolasa@iki.fi> */ #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> #include <sys/time.h> #include <sys/resource.h> #include "c.h" #include "fileutils.h" #include "pathnames.h" /* Create open temporary file in safe way. Please notice that the * file permissions are -rw------- by default. */ int xmkstemp(char **tmpname, char *dir) { char *localtmp; char *tmpenv; mode_t old_mode; int fd, rc; /* Some use cases must be capable of being moved atomically * with rename(2), which is the reason why dir is here. */ if (dir != NULL) tmpenv = dir; else tmpenv = getenv("TMPDIR"); if (tmpenv) rc = asprintf(&localtmp, "%s/%s.XXXXXX", tmpenv, program_invocation_short_name); else rc = asprintf(&localtmp, "%s/%s.XXXXXX", _PATH_TMP, program_invocation_short_name); if (rc < 0) return -1; old_mode = umask(077); fd = mkostemp(localtmp, O_RDWR|O_CREAT|O_EXCL|O_CLOEXEC); umask(old_mode); if (fd == -1) { free(localtmp); localtmp = NULL; } *tmpname = localtmp; return fd; } int dup_fd_cloexec(int oldfd, int lowfd) { int fd, flags, errno_save; #ifdef F_DUPFD_CLOEXEC fd = fcntl(oldfd, F_DUPFD_CLOEXEC, lowfd); if (fd >= 0) return fd; #endif fd = dup(oldfd); if (fd < 0) return fd; flags = fcntl(fd, F_GETFD); if (flags < 0) goto unwind; if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0) goto unwind; return fd; unwind: errno_save = errno; close(fd); errno = errno_save; return -1; } /* * portable getdtablesize() */ int get_fd_tabsize(void) { int m; #if defined(HAVE_GETDTABLESIZE) m = getdtablesize(); #elif defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE) struct rlimit rl; getrlimit(RLIMIT_NOFILE, &rl); m = rl.rlim_cur; #elif defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX) m = sysconf(_SC_OPEN_MAX); #else m = OPEN_MAX; #endif return m; } #ifdef TEST_PROGRAM int main(void) { FILE *f; char *tmpname; f = xfmkstemp(&tmpname, NULL); unlink(tmpname); free(tmpname); fclose(f); return EXIT_FAILURE; } #endif int mkdir_p(const char *path, mode_t mode) { char *p, *dir; int rc = 0; if (!path || !*path) return -EINVAL; dir = p = strdup(path); if (!dir) return -ENOMEM; if (*p == '/') p++; while (p && *p) { char *e = strchr(p, '/'); if (e) *e = '\0'; if (*p) { rc = mkdir(dir, mode); if (rc && errno != EEXIST) break; rc = 0; } if (!e) break; *e = '/'; p = e + 1; } free(dir); return rc; } /* returns basename and keeps dirname in the @path, if @path is "/" (root) * then returns empty string */ char *stripoff_last_component(char *path) { char *p = path ? strrchr(path, '/') : NULL; if (!p) return NULL; *p = '\0'; return p + 1; }
./CrossVul/dataset_final_sorted/CWE-264/c/bad_1661_1
crossvul-cpp_data_bad_2399_14
/* * Cryptographic API. * * HMAC: Keyed-Hashing for Message Authentication (RFC2104). * * Copyright (c) 2002 James Morris <jmorris@intercode.com.au> * Copyright (c) 2006 Herbert Xu <herbert@gondor.apana.org.au> * * The HMAC implementation is derived from USAGI. * Copyright (c) 2002 Kazunori Miyazawa <miyazawa@linux-ipv6.org> / USAGI * * 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/internal/hash.h> #include <crypto/scatterwalk.h> #include <linux/err.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/scatterlist.h> #include <linux/string.h> struct hmac_ctx { struct crypto_shash *hash; }; static inline void *align_ptr(void *p, unsigned int align) { return (void *)ALIGN((unsigned long)p, align); } static inline struct hmac_ctx *hmac_ctx(struct crypto_shash *tfm) { return align_ptr(crypto_shash_ctx_aligned(tfm) + crypto_shash_statesize(tfm) * 2, crypto_tfm_ctx_alignment()); } static int hmac_setkey(struct crypto_shash *parent, const u8 *inkey, unsigned int keylen) { int bs = crypto_shash_blocksize(parent); int ds = crypto_shash_digestsize(parent); int ss = crypto_shash_statesize(parent); char *ipad = crypto_shash_ctx_aligned(parent); char *opad = ipad + ss; struct hmac_ctx *ctx = align_ptr(opad + ss, crypto_tfm_ctx_alignment()); struct crypto_shash *hash = ctx->hash; SHASH_DESC_ON_STACK(shash, hash); unsigned int i; shash->tfm = hash; shash->flags = crypto_shash_get_flags(parent) & CRYPTO_TFM_REQ_MAY_SLEEP; if (keylen > bs) { int err; err = crypto_shash_digest(shash, inkey, keylen, ipad); if (err) return err; keylen = ds; } else memcpy(ipad, inkey, keylen); memset(ipad + keylen, 0, bs - keylen); memcpy(opad, ipad, bs); for (i = 0; i < bs; i++) { ipad[i] ^= 0x36; opad[i] ^= 0x5c; } return crypto_shash_init(shash) ?: crypto_shash_update(shash, ipad, bs) ?: crypto_shash_export(shash, ipad) ?: crypto_shash_init(shash) ?: crypto_shash_update(shash, opad, bs) ?: crypto_shash_export(shash, opad); } static int hmac_export(struct shash_desc *pdesc, void *out) { struct shash_desc *desc = shash_desc_ctx(pdesc); desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_export(desc, out); } static int hmac_import(struct shash_desc *pdesc, const void *in) { struct shash_desc *desc = shash_desc_ctx(pdesc); struct hmac_ctx *ctx = hmac_ctx(pdesc->tfm); desc->tfm = ctx->hash; desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_import(desc, in); } static int hmac_init(struct shash_desc *pdesc) { return hmac_import(pdesc, crypto_shash_ctx_aligned(pdesc->tfm)); } static int hmac_update(struct shash_desc *pdesc, const u8 *data, unsigned int nbytes) { struct shash_desc *desc = shash_desc_ctx(pdesc); desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_update(desc, data, nbytes); } static int hmac_final(struct shash_desc *pdesc, u8 *out) { struct crypto_shash *parent = pdesc->tfm; int ds = crypto_shash_digestsize(parent); int ss = crypto_shash_statesize(parent); char *opad = crypto_shash_ctx_aligned(parent) + ss; struct shash_desc *desc = shash_desc_ctx(pdesc); desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_final(desc, out) ?: crypto_shash_import(desc, opad) ?: crypto_shash_finup(desc, out, ds, out); } static int hmac_finup(struct shash_desc *pdesc, const u8 *data, unsigned int nbytes, u8 *out) { struct crypto_shash *parent = pdesc->tfm; int ds = crypto_shash_digestsize(parent); int ss = crypto_shash_statesize(parent); char *opad = crypto_shash_ctx_aligned(parent) + ss; struct shash_desc *desc = shash_desc_ctx(pdesc); desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_finup(desc, data, nbytes, out) ?: crypto_shash_import(desc, opad) ?: crypto_shash_finup(desc, out, ds, out); } static int hmac_init_tfm(struct crypto_tfm *tfm) { struct crypto_shash *parent = __crypto_shash_cast(tfm); struct crypto_shash *hash; struct crypto_instance *inst = (void *)tfm->__crt_alg; struct crypto_shash_spawn *spawn = crypto_instance_ctx(inst); struct hmac_ctx *ctx = hmac_ctx(parent); hash = crypto_spawn_shash(spawn); if (IS_ERR(hash)) return PTR_ERR(hash); parent->descsize = sizeof(struct shash_desc) + crypto_shash_descsize(hash); ctx->hash = hash; return 0; } static void hmac_exit_tfm(struct crypto_tfm *tfm) { struct hmac_ctx *ctx = hmac_ctx(__crypto_shash_cast(tfm)); crypto_free_shash(ctx->hash); } static int hmac_create(struct crypto_template *tmpl, struct rtattr **tb) { struct shash_instance *inst; struct crypto_alg *alg; struct shash_alg *salg; int err; int ds; int ss; err = crypto_check_attr_type(tb, CRYPTO_ALG_TYPE_SHASH); if (err) return err; salg = shash_attr_alg(tb[1], 0, 0); if (IS_ERR(salg)) return PTR_ERR(salg); err = -EINVAL; ds = salg->digestsize; ss = salg->statesize; alg = &salg->base; if (ds > alg->cra_blocksize || ss < alg->cra_blocksize) goto out_put_alg; inst = shash_alloc_instance("hmac", alg); err = PTR_ERR(inst); if (IS_ERR(inst)) goto out_put_alg; err = crypto_init_shash_spawn(shash_instance_ctx(inst), salg, shash_crypto_instance(inst)); if (err) goto out_free_inst; inst->alg.base.cra_priority = alg->cra_priority; inst->alg.base.cra_blocksize = alg->cra_blocksize; inst->alg.base.cra_alignmask = alg->cra_alignmask; ss = ALIGN(ss, alg->cra_alignmask + 1); inst->alg.digestsize = ds; inst->alg.statesize = ss; inst->alg.base.cra_ctxsize = sizeof(struct hmac_ctx) + ALIGN(ss * 2, crypto_tfm_ctx_alignment()); inst->alg.base.cra_init = hmac_init_tfm; inst->alg.base.cra_exit = hmac_exit_tfm; inst->alg.init = hmac_init; inst->alg.update = hmac_update; inst->alg.final = hmac_final; inst->alg.finup = hmac_finup; inst->alg.export = hmac_export; inst->alg.import = hmac_import; inst->alg.setkey = hmac_setkey; err = shash_register_instance(tmpl, inst); if (err) { out_free_inst: shash_free_instance(shash_crypto_instance(inst)); } out_put_alg: crypto_mod_put(alg); return err; } static struct crypto_template hmac_tmpl = { .name = "hmac", .create = hmac_create, .free = shash_free_instance, .module = THIS_MODULE, }; static int __init hmac_module_init(void) { return crypto_register_template(&hmac_tmpl); } static void __exit hmac_module_exit(void) { crypto_unregister_template(&hmac_tmpl); } module_init(hmac_module_init); module_exit(hmac_module_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("HMAC hash algorithm");
./CrossVul/dataset_final_sorted/CWE-264/c/bad_2399_14
crossvul-cpp_data_bad_5676_1
/* * linux/fs/exec.c * * Copyright (C) 1991, 1992 Linus Torvalds */ /* * #!-checking implemented by tytso. */ /* * Demand-loading implemented 01.12.91 - no need to read anything but * the header into memory. The inode of the executable is put into * "current->executable", and page faults do the actual loading. Clean. * * Once more I can proudly say that linux stood up to being changed: it * was less than 2 hours work to get demand-loading completely implemented. * * Demand loading changed July 1993 by Eric Youngdale. Use mmap instead, * current->executable is only used by the procfs. This allows a dispatch * table to check for several different types of binary formats. We keep * trying until we recognize the file or we run out of supported binary * formats. */ #include <linux/slab.h> #include <linux/file.h> #include <linux/fdtable.h> #include <linux/mm.h> #include <linux/stat.h> #include <linux/fcntl.h> #include <linux/swap.h> #include <linux/string.h> #include <linux/init.h> #include <linux/pagemap.h> #include <linux/perf_event.h> #include <linux/highmem.h> #include <linux/spinlock.h> #include <linux/key.h> #include <linux/personality.h> #include <linux/binfmts.h> #include <linux/utsname.h> #include <linux/pid_namespace.h> #include <linux/module.h> #include <linux/namei.h> #include <linux/mount.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/tsacct_kern.h> #include <linux/cn_proc.h> #include <linux/audit.h> #include <linux/tracehook.h> #include <linux/kmod.h> #include <linux/fsnotify.h> #include <linux/fs_struct.h> #include <linux/pipe_fs_i.h> #include <linux/oom.h> #include <linux/compat.h> #include <asm/uaccess.h> #include <asm/mmu_context.h> #include <asm/tlb.h> #include <trace/events/task.h> #include "internal.h" #include "coredump.h" #include <trace/events/sched.h> int suid_dumpable = 0; static LIST_HEAD(formats); static DEFINE_RWLOCK(binfmt_lock); void __register_binfmt(struct linux_binfmt * fmt, int insert) { BUG_ON(!fmt); if (WARN_ON(!fmt->load_binary)) return; write_lock(&binfmt_lock); insert ? list_add(&fmt->lh, &formats) : list_add_tail(&fmt->lh, &formats); write_unlock(&binfmt_lock); } EXPORT_SYMBOL(__register_binfmt); void unregister_binfmt(struct linux_binfmt * fmt) { write_lock(&binfmt_lock); list_del(&fmt->lh); write_unlock(&binfmt_lock); } EXPORT_SYMBOL(unregister_binfmt); static inline void put_binfmt(struct linux_binfmt * fmt) { module_put(fmt->module); } /* * Note that a shared library must be both readable and executable due to * security reasons. * * Also note that we take the address to load from from the file itself. */ SYSCALL_DEFINE1(uselib, const char __user *, library) { struct file *file; struct filename *tmp = getname(library); int error = PTR_ERR(tmp); static const struct open_flags uselib_flags = { .open_flag = O_LARGEFILE | O_RDONLY | __FMODE_EXEC, .acc_mode = MAY_READ | MAY_EXEC | MAY_OPEN, .intent = LOOKUP_OPEN, .lookup_flags = LOOKUP_FOLLOW, }; if (IS_ERR(tmp)) goto out; file = do_filp_open(AT_FDCWD, tmp, &uselib_flags); putname(tmp); error = PTR_ERR(file); if (IS_ERR(file)) goto out; error = -EINVAL; if (!S_ISREG(file_inode(file)->i_mode)) goto exit; error = -EACCES; if (file->f_path.mnt->mnt_flags & MNT_NOEXEC) goto exit; fsnotify_open(file); error = -ENOEXEC; if(file->f_op) { struct linux_binfmt * fmt; read_lock(&binfmt_lock); list_for_each_entry(fmt, &formats, lh) { if (!fmt->load_shlib) continue; if (!try_module_get(fmt->module)) continue; read_unlock(&binfmt_lock); error = fmt->load_shlib(file); read_lock(&binfmt_lock); put_binfmt(fmt); if (error != -ENOEXEC) break; } read_unlock(&binfmt_lock); } exit: fput(file); out: return error; } #ifdef CONFIG_MMU /* * The nascent bprm->mm is not visible until exec_mmap() but it can * use a lot of memory, account these pages in current->mm temporary * for oom_badness()->get_mm_rss(). Once exec succeeds or fails, we * change the counter back via acct_arg_size(0). */ static void acct_arg_size(struct linux_binprm *bprm, unsigned long pages) { struct mm_struct *mm = current->mm; long diff = (long)(pages - bprm->vma_pages); if (!mm || !diff) return; bprm->vma_pages = pages; add_mm_counter(mm, MM_ANONPAGES, diff); } static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos, int write) { struct page *page; int ret; #ifdef CONFIG_STACK_GROWSUP if (write) { ret = expand_downwards(bprm->vma, pos); if (ret < 0) return NULL; } #endif ret = get_user_pages(current, bprm->mm, pos, 1, write, 1, &page, NULL); if (ret <= 0) return NULL; if (write) { unsigned long size = bprm->vma->vm_end - bprm->vma->vm_start; struct rlimit *rlim; acct_arg_size(bprm, size / PAGE_SIZE); /* * We've historically supported up to 32 pages (ARG_MAX) * of argument strings even with small stacks */ if (size <= ARG_MAX) return page; /* * Limit to 1/4-th the stack size for the argv+env strings. * This ensures that: * - the remaining binfmt code will not run out of stack space, * - the program will have a reasonable amount of stack left * to work from. */ rlim = current->signal->rlim; if (size > ACCESS_ONCE(rlim[RLIMIT_STACK].rlim_cur) / 4) { put_page(page); return NULL; } } return page; } static void put_arg_page(struct page *page) { put_page(page); } static void free_arg_page(struct linux_binprm *bprm, int i) { } static void free_arg_pages(struct linux_binprm *bprm) { } static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos, struct page *page) { flush_cache_page(bprm->vma, pos, page_to_pfn(page)); } static int __bprm_mm_init(struct linux_binprm *bprm) { int err; struct vm_area_struct *vma = NULL; struct mm_struct *mm = bprm->mm; bprm->vma = vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL); if (!vma) return -ENOMEM; down_write(&mm->mmap_sem); vma->vm_mm = mm; /* * Place the stack at the largest stack address the architecture * supports. Later, we'll move this to an appropriate place. We don't * use STACK_TOP because that can depend on attributes which aren't * configured yet. */ BUILD_BUG_ON(VM_STACK_FLAGS & VM_STACK_INCOMPLETE_SETUP); vma->vm_end = STACK_TOP_MAX; vma->vm_start = vma->vm_end - PAGE_SIZE; vma->vm_flags = VM_SOFTDIRTY | VM_STACK_FLAGS | VM_STACK_INCOMPLETE_SETUP; vma->vm_page_prot = vm_get_page_prot(vma->vm_flags); INIT_LIST_HEAD(&vma->anon_vma_chain); err = insert_vm_struct(mm, vma); if (err) goto err; mm->stack_vm = mm->total_vm = 1; up_write(&mm->mmap_sem); bprm->p = vma->vm_end - sizeof(void *); return 0; err: up_write(&mm->mmap_sem); bprm->vma = NULL; kmem_cache_free(vm_area_cachep, vma); return err; } static bool valid_arg_len(struct linux_binprm *bprm, long len) { return len <= MAX_ARG_STRLEN; } #else static inline void acct_arg_size(struct linux_binprm *bprm, unsigned long pages) { } static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos, int write) { struct page *page; page = bprm->page[pos / PAGE_SIZE]; if (!page && write) { page = alloc_page(GFP_HIGHUSER|__GFP_ZERO); if (!page) return NULL; bprm->page[pos / PAGE_SIZE] = page; } return page; } static void put_arg_page(struct page *page) { } static void free_arg_page(struct linux_binprm *bprm, int i) { if (bprm->page[i]) { __free_page(bprm->page[i]); bprm->page[i] = NULL; } } static void free_arg_pages(struct linux_binprm *bprm) { int i; for (i = 0; i < MAX_ARG_PAGES; i++) free_arg_page(bprm, i); } static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos, struct page *page) { } static int __bprm_mm_init(struct linux_binprm *bprm) { bprm->p = PAGE_SIZE * MAX_ARG_PAGES - sizeof(void *); return 0; } static bool valid_arg_len(struct linux_binprm *bprm, long len) { return len <= bprm->p; } #endif /* CONFIG_MMU */ /* * Create a new mm_struct and populate it with a temporary stack * vm_area_struct. We don't have enough context at this point to set the stack * flags, permissions, and offset, so we use temporary values. We'll update * them later in setup_arg_pages(). */ static int bprm_mm_init(struct linux_binprm *bprm) { int err; struct mm_struct *mm = NULL; bprm->mm = mm = mm_alloc(); err = -ENOMEM; if (!mm) goto err; err = init_new_context(current, mm); if (err) goto err; err = __bprm_mm_init(bprm); if (err) goto err; return 0; err: if (mm) { bprm->mm = NULL; mmdrop(mm); } return err; } struct user_arg_ptr { #ifdef CONFIG_COMPAT bool is_compat; #endif union { const char __user *const __user *native; #ifdef CONFIG_COMPAT const compat_uptr_t __user *compat; #endif } ptr; }; static const char __user *get_user_arg_ptr(struct user_arg_ptr argv, int nr) { const char __user *native; #ifdef CONFIG_COMPAT if (unlikely(argv.is_compat)) { compat_uptr_t compat; if (get_user(compat, argv.ptr.compat + nr)) return ERR_PTR(-EFAULT); return compat_ptr(compat); } #endif if (get_user(native, argv.ptr.native + nr)) return ERR_PTR(-EFAULT); return native; } /* * count() counts the number of strings in array ARGV. */ static int count(struct user_arg_ptr argv, int max) { int i = 0; if (argv.ptr.native != NULL) { for (;;) { const char __user *p = get_user_arg_ptr(argv, i); if (!p) break; if (IS_ERR(p)) return -EFAULT; if (i >= max) return -E2BIG; ++i; if (fatal_signal_pending(current)) return -ERESTARTNOHAND; cond_resched(); } } return i; } /* * 'copy_strings()' copies argument/environment strings from the old * processes's memory to the new process's stack. The call to get_user_pages() * ensures the destination page is created and not swapped out. */ static int copy_strings(int argc, struct user_arg_ptr argv, struct linux_binprm *bprm) { struct page *kmapped_page = NULL; char *kaddr = NULL; unsigned long kpos = 0; int ret; while (argc-- > 0) { const char __user *str; int len; unsigned long pos; ret = -EFAULT; str = get_user_arg_ptr(argv, argc); if (IS_ERR(str)) goto out; len = strnlen_user(str, MAX_ARG_STRLEN); if (!len) goto out; ret = -E2BIG; if (!valid_arg_len(bprm, len)) goto out; /* We're going to work our way backwords. */ pos = bprm->p; str += len; bprm->p -= len; while (len > 0) { int offset, bytes_to_copy; if (fatal_signal_pending(current)) { ret = -ERESTARTNOHAND; goto out; } cond_resched(); offset = pos % PAGE_SIZE; if (offset == 0) offset = PAGE_SIZE; bytes_to_copy = offset; if (bytes_to_copy > len) bytes_to_copy = len; offset -= bytes_to_copy; pos -= bytes_to_copy; str -= bytes_to_copy; len -= bytes_to_copy; if (!kmapped_page || kpos != (pos & PAGE_MASK)) { struct page *page; page = get_arg_page(bprm, pos, 1); if (!page) { ret = -E2BIG; goto out; } if (kmapped_page) { flush_kernel_dcache_page(kmapped_page); kunmap(kmapped_page); put_arg_page(kmapped_page); } kmapped_page = page; kaddr = kmap(kmapped_page); kpos = pos & PAGE_MASK; flush_arg_page(bprm, kpos, kmapped_page); } if (copy_from_user(kaddr+offset, str, bytes_to_copy)) { ret = -EFAULT; goto out; } } } ret = 0; out: if (kmapped_page) { flush_kernel_dcache_page(kmapped_page); kunmap(kmapped_page); put_arg_page(kmapped_page); } return ret; } /* * Like copy_strings, but get argv and its values from kernel memory. */ int copy_strings_kernel(int argc, const char *const *__argv, struct linux_binprm *bprm) { int r; mm_segment_t oldfs = get_fs(); struct user_arg_ptr argv = { .ptr.native = (const char __user *const __user *)__argv, }; set_fs(KERNEL_DS); r = copy_strings(argc, argv, bprm); set_fs(oldfs); return r; } EXPORT_SYMBOL(copy_strings_kernel); #ifdef CONFIG_MMU /* * During bprm_mm_init(), we create a temporary stack at STACK_TOP_MAX. Once * the binfmt code determines where the new stack should reside, we shift it to * its final location. The process proceeds as follows: * * 1) Use shift to calculate the new vma endpoints. * 2) Extend vma to cover both the old and new ranges. This ensures the * arguments passed to subsequent functions are consistent. * 3) Move vma's page tables to the new range. * 4) Free up any cleared pgd range. * 5) Shrink the vma to cover only the new range. */ static int shift_arg_pages(struct vm_area_struct *vma, unsigned long shift) { struct mm_struct *mm = vma->vm_mm; unsigned long old_start = vma->vm_start; unsigned long old_end = vma->vm_end; unsigned long length = old_end - old_start; unsigned long new_start = old_start - shift; unsigned long new_end = old_end - shift; struct mmu_gather tlb; BUG_ON(new_start > new_end); /* * ensure there are no vmas between where we want to go * and where we are */ if (vma != find_vma(mm, new_start)) return -EFAULT; /* * cover the whole range: [new_start, old_end) */ if (vma_adjust(vma, new_start, old_end, vma->vm_pgoff, NULL)) return -ENOMEM; /* * move the page tables downwards, on failure we rely on * process cleanup to remove whatever mess we made. */ if (length != move_page_tables(vma, old_start, vma, new_start, length, false)) return -ENOMEM; lru_add_drain(); tlb_gather_mmu(&tlb, mm, old_start, old_end); if (new_end > old_start) { /* * when the old and new regions overlap clear from new_end. */ free_pgd_range(&tlb, new_end, old_end, new_end, vma->vm_next ? vma->vm_next->vm_start : USER_PGTABLES_CEILING); } else { /* * otherwise, clean from old_start; this is done to not touch * the address space in [new_end, old_start) some architectures * have constraints on va-space that make this illegal (IA64) - * for the others its just a little faster. */ free_pgd_range(&tlb, old_start, old_end, new_end, vma->vm_next ? vma->vm_next->vm_start : USER_PGTABLES_CEILING); } tlb_finish_mmu(&tlb, old_start, old_end); /* * Shrink the vma to just the new range. Always succeeds. */ vma_adjust(vma, new_start, new_end, vma->vm_pgoff, NULL); return 0; } /* * Finalizes the stack vm_area_struct. The flags and permissions are updated, * the stack is optionally relocated, and some extra space is added. */ int setup_arg_pages(struct linux_binprm *bprm, unsigned long stack_top, int executable_stack) { unsigned long ret; unsigned long stack_shift; struct mm_struct *mm = current->mm; struct vm_area_struct *vma = bprm->vma; struct vm_area_struct *prev = NULL; unsigned long vm_flags; unsigned long stack_base; unsigned long stack_size; unsigned long stack_expand; unsigned long rlim_stack; #ifdef CONFIG_STACK_GROWSUP /* Limit stack size to 1GB */ stack_base = rlimit_max(RLIMIT_STACK); if (stack_base > (1 << 30)) stack_base = 1 << 30; /* Make sure we didn't let the argument array grow too large. */ if (vma->vm_end - vma->vm_start > stack_base) return -ENOMEM; stack_base = PAGE_ALIGN(stack_top - stack_base); stack_shift = vma->vm_start - stack_base; mm->arg_start = bprm->p - stack_shift; bprm->p = vma->vm_end - stack_shift; #else stack_top = arch_align_stack(stack_top); stack_top = PAGE_ALIGN(stack_top); if (unlikely(stack_top < mmap_min_addr) || unlikely(vma->vm_end - vma->vm_start >= stack_top - mmap_min_addr)) return -ENOMEM; stack_shift = vma->vm_end - stack_top; bprm->p -= stack_shift; mm->arg_start = bprm->p; #endif if (bprm->loader) bprm->loader -= stack_shift; bprm->exec -= stack_shift; down_write(&mm->mmap_sem); vm_flags = VM_STACK_FLAGS; /* * Adjust stack execute permissions; explicitly enable for * EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X and leave alone * (arch default) otherwise. */ if (unlikely(executable_stack == EXSTACK_ENABLE_X)) vm_flags |= VM_EXEC; else if (executable_stack == EXSTACK_DISABLE_X) vm_flags &= ~VM_EXEC; vm_flags |= mm->def_flags; vm_flags |= VM_STACK_INCOMPLETE_SETUP; ret = mprotect_fixup(vma, &prev, vma->vm_start, vma->vm_end, vm_flags); if (ret) goto out_unlock; BUG_ON(prev != vma); /* Move stack pages down in memory. */ if (stack_shift) { ret = shift_arg_pages(vma, stack_shift); if (ret) goto out_unlock; } /* mprotect_fixup is overkill to remove the temporary stack flags */ vma->vm_flags &= ~VM_STACK_INCOMPLETE_SETUP; stack_expand = 131072UL; /* randomly 32*4k (or 2*64k) pages */ stack_size = vma->vm_end - vma->vm_start; /* * Align this down to a page boundary as expand_stack * will align it up. */ rlim_stack = rlimit(RLIMIT_STACK) & PAGE_MASK; #ifdef CONFIG_STACK_GROWSUP if (stack_size + stack_expand > rlim_stack) stack_base = vma->vm_start + rlim_stack; else stack_base = vma->vm_end + stack_expand; #else if (stack_size + stack_expand > rlim_stack) stack_base = vma->vm_end - rlim_stack; else stack_base = vma->vm_start - stack_expand; #endif current->mm->start_stack = bprm->p; ret = expand_stack(vma, stack_base); if (ret) ret = -EFAULT; out_unlock: up_write(&mm->mmap_sem); return ret; } EXPORT_SYMBOL(setup_arg_pages); #endif /* CONFIG_MMU */ struct file *open_exec(const char *name) { struct file *file; int err; struct filename tmp = { .name = name }; static const struct open_flags open_exec_flags = { .open_flag = O_LARGEFILE | O_RDONLY | __FMODE_EXEC, .acc_mode = MAY_EXEC | MAY_OPEN, .intent = LOOKUP_OPEN, .lookup_flags = LOOKUP_FOLLOW, }; file = do_filp_open(AT_FDCWD, &tmp, &open_exec_flags); if (IS_ERR(file)) goto out; err = -EACCES; if (!S_ISREG(file_inode(file)->i_mode)) goto exit; if (file->f_path.mnt->mnt_flags & MNT_NOEXEC) goto exit; fsnotify_open(file); err = deny_write_access(file); if (err) goto exit; out: return file; exit: fput(file); return ERR_PTR(err); } EXPORT_SYMBOL(open_exec); int kernel_read(struct file *file, loff_t offset, char *addr, unsigned long count) { mm_segment_t old_fs; loff_t pos = offset; int result; old_fs = get_fs(); set_fs(get_ds()); /* The cast to a user pointer is valid due to the set_fs() */ result = vfs_read(file, (void __user *)addr, count, &pos); set_fs(old_fs); return result; } EXPORT_SYMBOL(kernel_read); ssize_t read_code(struct file *file, unsigned long addr, loff_t pos, size_t len) { ssize_t res = file->f_op->read(file, (void __user *)addr, len, &pos); if (res > 0) flush_icache_range(addr, addr + len); return res; } EXPORT_SYMBOL(read_code); static int exec_mmap(struct mm_struct *mm) { struct task_struct *tsk; struct mm_struct * old_mm, *active_mm; /* Notify parent that we're no longer interested in the old VM */ tsk = current; old_mm = current->mm; mm_release(tsk, old_mm); if (old_mm) { sync_mm_rss(old_mm); /* * Make sure that if there is a core dump in progress * for the old mm, we get out and die instead of going * through with the exec. We must hold mmap_sem around * checking core_state and changing tsk->mm. */ down_read(&old_mm->mmap_sem); if (unlikely(old_mm->core_state)) { up_read(&old_mm->mmap_sem); return -EINTR; } } task_lock(tsk); active_mm = tsk->active_mm; tsk->mm = mm; tsk->active_mm = mm; activate_mm(active_mm, mm); task_unlock(tsk); arch_pick_mmap_layout(mm); if (old_mm) { up_read(&old_mm->mmap_sem); BUG_ON(active_mm != old_mm); setmax_mm_hiwater_rss(&tsk->signal->maxrss, old_mm); mm_update_next_owner(old_mm); mmput(old_mm); return 0; } mmdrop(active_mm); return 0; } /* * This function makes sure the current process has its own signal table, * so that flush_signal_handlers can later reset the handlers without * disturbing other processes. (Other processes might share the signal * table via the CLONE_SIGHAND option to clone().) */ static int de_thread(struct task_struct *tsk) { struct signal_struct *sig = tsk->signal; struct sighand_struct *oldsighand = tsk->sighand; spinlock_t *lock = &oldsighand->siglock; if (thread_group_empty(tsk)) goto no_thread_group; /* * Kill all other threads in the thread group. */ spin_lock_irq(lock); if (signal_group_exit(sig)) { /* * Another group action in progress, just * return so that the signal is processed. */ spin_unlock_irq(lock); return -EAGAIN; } sig->group_exit_task = tsk; sig->notify_count = zap_other_threads(tsk); if (!thread_group_leader(tsk)) sig->notify_count--; while (sig->notify_count) { __set_current_state(TASK_KILLABLE); spin_unlock_irq(lock); schedule(); if (unlikely(__fatal_signal_pending(tsk))) goto killed; spin_lock_irq(lock); } spin_unlock_irq(lock); /* * At this point all other threads have exited, all we have to * do is to wait for the thread group leader to become inactive, * and to assume its PID: */ if (!thread_group_leader(tsk)) { struct task_struct *leader = tsk->group_leader; sig->notify_count = -1; /* for exit_notify() */ for (;;) { threadgroup_change_begin(tsk); write_lock_irq(&tasklist_lock); if (likely(leader->exit_state)) break; __set_current_state(TASK_KILLABLE); write_unlock_irq(&tasklist_lock); threadgroup_change_end(tsk); schedule(); if (unlikely(__fatal_signal_pending(tsk))) goto killed; } /* * The only record we have of the real-time age of a * process, regardless of execs it's done, is start_time. * All the past CPU time is accumulated in signal_struct * from sister threads now dead. But in this non-leader * exec, nothing survives from the original leader thread, * whose birth marks the true age of this process now. * When we take on its identity by switching to its PID, we * also take its birthdate (always earlier than our own). */ tsk->start_time = leader->start_time; tsk->real_start_time = leader->real_start_time; BUG_ON(!same_thread_group(leader, tsk)); BUG_ON(has_group_leader_pid(tsk)); /* * An exec() starts a new thread group with the * TGID of the previous thread group. Rehash the * two threads with a switched PID, and release * the former thread group leader: */ /* Become a process group leader with the old leader's pid. * The old leader becomes a thread of the this thread group. * Note: The old leader also uses this pid until release_task * is called. Odd but simple and correct. */ tsk->pid = leader->pid; change_pid(tsk, PIDTYPE_PID, task_pid(leader)); transfer_pid(leader, tsk, PIDTYPE_PGID); transfer_pid(leader, tsk, PIDTYPE_SID); list_replace_rcu(&leader->tasks, &tsk->tasks); list_replace_init(&leader->sibling, &tsk->sibling); tsk->group_leader = tsk; leader->group_leader = tsk; tsk->exit_signal = SIGCHLD; leader->exit_signal = -1; BUG_ON(leader->exit_state != EXIT_ZOMBIE); leader->exit_state = EXIT_DEAD; /* * We are going to release_task()->ptrace_unlink() silently, * the tracer can sleep in do_wait(). EXIT_DEAD guarantees * the tracer wont't block again waiting for this thread. */ if (unlikely(leader->ptrace)) __wake_up_parent(leader, leader->parent); write_unlock_irq(&tasklist_lock); threadgroup_change_end(tsk); release_task(leader); } sig->group_exit_task = NULL; sig->notify_count = 0; no_thread_group: /* we have changed execution domain */ tsk->exit_signal = SIGCHLD; exit_itimers(sig); flush_itimer_signals(); if (atomic_read(&oldsighand->count) != 1) { struct sighand_struct *newsighand; /* * This ->sighand is shared with the CLONE_SIGHAND * but not CLONE_THREAD task, switch to the new one. */ newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL); if (!newsighand) return -ENOMEM; atomic_set(&newsighand->count, 1); memcpy(newsighand->action, oldsighand->action, sizeof(newsighand->action)); write_lock_irq(&tasklist_lock); spin_lock(&oldsighand->siglock); rcu_assign_pointer(tsk->sighand, newsighand); spin_unlock(&oldsighand->siglock); write_unlock_irq(&tasklist_lock); __cleanup_sighand(oldsighand); } BUG_ON(!thread_group_leader(tsk)); return 0; killed: /* protects against exit_notify() and __exit_signal() */ read_lock(&tasklist_lock); sig->group_exit_task = NULL; sig->notify_count = 0; read_unlock(&tasklist_lock); return -EAGAIN; } char *get_task_comm(char *buf, struct task_struct *tsk) { /* buf must be at least sizeof(tsk->comm) in size */ task_lock(tsk); strncpy(buf, tsk->comm, sizeof(tsk->comm)); task_unlock(tsk); return buf; } EXPORT_SYMBOL_GPL(get_task_comm); /* * These functions flushes out all traces of the currently running executable * so that a new one can be started */ void set_task_comm(struct task_struct *tsk, char *buf) { task_lock(tsk); trace_task_rename(tsk, buf); strlcpy(tsk->comm, buf, sizeof(tsk->comm)); task_unlock(tsk); perf_event_comm(tsk); } static void filename_to_taskname(char *tcomm, const char *fn, unsigned int len) { int i, ch; /* Copies the binary name from after last slash */ for (i = 0; (ch = *(fn++)) != '\0';) { if (ch == '/') i = 0; /* overwrite what we wrote */ else if (i < len - 1) tcomm[i++] = ch; } tcomm[i] = '\0'; } int flush_old_exec(struct linux_binprm * bprm) { int retval; /* * Make sure we have a private signal table and that * we are unassociated from the previous thread group. */ retval = de_thread(current); if (retval) goto out; set_mm_exe_file(bprm->mm, bprm->file); filename_to_taskname(bprm->tcomm, bprm->filename, sizeof(bprm->tcomm)); /* * Release all of the old mmap stuff */ acct_arg_size(bprm, 0); retval = exec_mmap(bprm->mm); if (retval) goto out; bprm->mm = NULL; /* We're using it now */ set_fs(USER_DS); current->flags &= ~(PF_RANDOMIZE | PF_FORKNOEXEC | PF_KTHREAD | PF_NOFREEZE); flush_thread(); current->personality &= ~bprm->per_clear; return 0; out: return retval; } EXPORT_SYMBOL(flush_old_exec); void would_dump(struct linux_binprm *bprm, struct file *file) { if (inode_permission(file_inode(file), MAY_READ) < 0) bprm->interp_flags |= BINPRM_FLAGS_ENFORCE_NONDUMP; } EXPORT_SYMBOL(would_dump); void setup_new_exec(struct linux_binprm * bprm) { arch_pick_mmap_layout(current->mm); /* This is the point of no return */ current->sas_ss_sp = current->sas_ss_size = 0; if (uid_eq(current_euid(), current_uid()) && gid_eq(current_egid(), current_gid())) set_dumpable(current->mm, SUID_DUMP_USER); else set_dumpable(current->mm, suid_dumpable); set_task_comm(current, bprm->tcomm); /* Set the new mm task size. We have to do that late because it may * depend on TIF_32BIT which is only updated in flush_thread() on * some architectures like powerpc */ current->mm->task_size = TASK_SIZE; /* install the new credentials */ if (!uid_eq(bprm->cred->uid, current_euid()) || !gid_eq(bprm->cred->gid, current_egid())) { current->pdeath_signal = 0; } else { would_dump(bprm, bprm->file); if (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP) set_dumpable(current->mm, suid_dumpable); } /* An exec changes our domain. We are no longer part of the thread group */ current->self_exec_id++; flush_signal_handlers(current, 0); do_close_on_exec(current->files); } EXPORT_SYMBOL(setup_new_exec); /* * Prepare credentials and lock ->cred_guard_mutex. * install_exec_creds() commits the new creds and drops the lock. * Or, if exec fails before, free_bprm() should release ->cred and * and unlock. */ int prepare_bprm_creds(struct linux_binprm *bprm) { if (mutex_lock_interruptible(&current->signal->cred_guard_mutex)) return -ERESTARTNOINTR; bprm->cred = prepare_exec_creds(); if (likely(bprm->cred)) return 0; mutex_unlock(&current->signal->cred_guard_mutex); return -ENOMEM; } void free_bprm(struct linux_binprm *bprm) { free_arg_pages(bprm); if (bprm->cred) { mutex_unlock(&current->signal->cred_guard_mutex); abort_creds(bprm->cred); } /* If a binfmt changed the interp, free it. */ if (bprm->interp != bprm->filename) kfree(bprm->interp); kfree(bprm); } int bprm_change_interp(char *interp, struct linux_binprm *bprm) { /* If a binfmt changed the interp, free it first. */ if (bprm->interp != bprm->filename) kfree(bprm->interp); bprm->interp = kstrdup(interp, GFP_KERNEL); if (!bprm->interp) return -ENOMEM; return 0; } EXPORT_SYMBOL(bprm_change_interp); /* * install the new credentials for this executable */ void install_exec_creds(struct linux_binprm *bprm) { security_bprm_committing_creds(bprm); commit_creds(bprm->cred); bprm->cred = NULL; /* * Disable monitoring for regular users * when executing setuid binaries. Must * wait until new credentials are committed * by commit_creds() above */ if (get_dumpable(current->mm) != SUID_DUMP_USER) perf_event_exit_task(current); /* * cred_guard_mutex must be held at least to this point to prevent * ptrace_attach() from altering our determination of the task's * credentials; any time after this it may be unlocked. */ security_bprm_committed_creds(bprm); mutex_unlock(&current->signal->cred_guard_mutex); } EXPORT_SYMBOL(install_exec_creds); /* * determine how safe it is to execute the proposed program * - the caller must hold ->cred_guard_mutex to protect against * PTRACE_ATTACH */ static int check_unsafe_exec(struct linux_binprm *bprm) { struct task_struct *p = current, *t; unsigned n_fs; int res = 0; if (p->ptrace) { if (p->ptrace & PT_PTRACE_CAP) bprm->unsafe |= LSM_UNSAFE_PTRACE_CAP; else bprm->unsafe |= LSM_UNSAFE_PTRACE; } /* * This isn't strictly necessary, but it makes it harder for LSMs to * mess up. */ if (current->no_new_privs) bprm->unsafe |= LSM_UNSAFE_NO_NEW_PRIVS; n_fs = 1; spin_lock(&p->fs->lock); rcu_read_lock(); for (t = next_thread(p); t != p; t = next_thread(t)) { if (t->fs == p->fs) n_fs++; } rcu_read_unlock(); if (p->fs->users > n_fs) { bprm->unsafe |= LSM_UNSAFE_SHARE; } else { res = -EAGAIN; if (!p->fs->in_exec) { p->fs->in_exec = 1; res = 1; } } spin_unlock(&p->fs->lock); return res; } /* * Fill the binprm structure from the inode. * Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes * * This may be called multiple times for binary chains (scripts for example). */ int prepare_binprm(struct linux_binprm *bprm) { umode_t mode; struct inode * inode = file_inode(bprm->file); int retval; mode = inode->i_mode; if (bprm->file->f_op == NULL) return -EACCES; /* clear any previous set[ug]id data from a previous binary */ bprm->cred->euid = current_euid(); bprm->cred->egid = current_egid(); if (!(bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID) && !current->no_new_privs && kuid_has_mapping(bprm->cred->user_ns, inode->i_uid) && kgid_has_mapping(bprm->cred->user_ns, inode->i_gid)) { /* Set-uid? */ if (mode & S_ISUID) { bprm->per_clear |= PER_CLEAR_ON_SETID; bprm->cred->euid = inode->i_uid; } /* Set-gid? */ /* * If setgid is set but no group execute bit then this * is a candidate for mandatory locking, not a setgid * executable. */ if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) { bprm->per_clear |= PER_CLEAR_ON_SETID; bprm->cred->egid = inode->i_gid; } } /* fill in binprm security blob */ retval = security_bprm_set_creds(bprm); if (retval) return retval; bprm->cred_prepared = 1; memset(bprm->buf, 0, BINPRM_BUF_SIZE); return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE); } EXPORT_SYMBOL(prepare_binprm); /* * Arguments are '\0' separated strings found at the location bprm->p * points to; chop off the first by relocating brpm->p to right after * the first '\0' encountered. */ int remove_arg_zero(struct linux_binprm *bprm) { int ret = 0; unsigned long offset; char *kaddr; struct page *page; if (!bprm->argc) return 0; do { offset = bprm->p & ~PAGE_MASK; page = get_arg_page(bprm, bprm->p, 0); if (!page) { ret = -EFAULT; goto out; } kaddr = kmap_atomic(page); for (; offset < PAGE_SIZE && kaddr[offset]; offset++, bprm->p++) ; kunmap_atomic(kaddr); put_arg_page(page); if (offset == PAGE_SIZE) free_arg_page(bprm, (bprm->p >> PAGE_SHIFT) - 1); } while (offset == PAGE_SIZE); bprm->p++; bprm->argc--; ret = 0; out: return ret; } EXPORT_SYMBOL(remove_arg_zero); #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e)) /* * cycle the list of binary formats handler, until one recognizes the image */ int search_binary_handler(struct linux_binprm *bprm) { bool need_retry = IS_ENABLED(CONFIG_MODULES); struct linux_binfmt *fmt; int retval; /* This allows 4 levels of binfmt rewrites before failing hard. */ if (bprm->recursion_depth > 5) return -ELOOP; retval = security_bprm_check(bprm); if (retval) return retval; retval = audit_bprm(bprm); if (retval) return retval; retval = -ENOENT; retry: read_lock(&binfmt_lock); list_for_each_entry(fmt, &formats, lh) { if (!try_module_get(fmt->module)) continue; read_unlock(&binfmt_lock); bprm->recursion_depth++; retval = fmt->load_binary(bprm); bprm->recursion_depth--; if (retval >= 0 || retval != -ENOEXEC || bprm->mm == NULL || bprm->file == NULL) { put_binfmt(fmt); return retval; } read_lock(&binfmt_lock); put_binfmt(fmt); } read_unlock(&binfmt_lock); if (need_retry && retval == -ENOEXEC) { if (printable(bprm->buf[0]) && printable(bprm->buf[1]) && printable(bprm->buf[2]) && printable(bprm->buf[3])) return retval; if (request_module("binfmt-%04x", *(ushort *)(bprm->buf + 2)) < 0) return retval; need_retry = false; goto retry; } return retval; } EXPORT_SYMBOL(search_binary_handler); static int exec_binprm(struct linux_binprm *bprm) { pid_t old_pid, old_vpid; int ret; /* Need to fetch pid before load_binary changes it */ old_pid = current->pid; rcu_read_lock(); old_vpid = task_pid_nr_ns(current, task_active_pid_ns(current->parent)); rcu_read_unlock(); ret = search_binary_handler(bprm); if (ret >= 0) { trace_sched_process_exec(current, old_pid, bprm); ptrace_event(PTRACE_EVENT_EXEC, old_vpid); current->did_exec = 1; proc_exec_connector(current); if (bprm->file) { allow_write_access(bprm->file); fput(bprm->file); bprm->file = NULL; /* to catch use-after-free */ } } return ret; } /* * sys_execve() executes a new program. */ static int do_execve_common(const char *filename, struct user_arg_ptr argv, struct user_arg_ptr envp) { struct linux_binprm *bprm; struct file *file; struct files_struct *displaced; bool clear_in_exec; int retval; /* * We move the actual failure in case of RLIMIT_NPROC excess from * set*uid() to execve() because too many poorly written programs * don't check setuid() return code. Here we additionally recheck * whether NPROC limit is still exceeded. */ if ((current->flags & PF_NPROC_EXCEEDED) && atomic_read(&current_user()->processes) > rlimit(RLIMIT_NPROC)) { retval = -EAGAIN; goto out_ret; } /* We're below the limit (still or again), so we don't want to make * further execve() calls fail. */ current->flags &= ~PF_NPROC_EXCEEDED; retval = unshare_files(&displaced); if (retval) goto out_ret; retval = -ENOMEM; bprm = kzalloc(sizeof(*bprm), GFP_KERNEL); if (!bprm) goto out_files; retval = prepare_bprm_creds(bprm); if (retval) goto out_free; retval = check_unsafe_exec(bprm); if (retval < 0) goto out_free; clear_in_exec = retval; current->in_execve = 1; file = open_exec(filename); retval = PTR_ERR(file); if (IS_ERR(file)) goto out_unmark; sched_exec(); bprm->file = file; bprm->filename = filename; bprm->interp = filename; retval = bprm_mm_init(bprm); if (retval) goto out_file; bprm->argc = count(argv, MAX_ARG_STRINGS); if ((retval = bprm->argc) < 0) goto out; bprm->envc = count(envp, MAX_ARG_STRINGS); if ((retval = bprm->envc) < 0) goto out; retval = prepare_binprm(bprm); if (retval < 0) goto out; retval = copy_strings_kernel(1, &bprm->filename, bprm); if (retval < 0) goto out; bprm->exec = bprm->p; retval = copy_strings(bprm->envc, envp, bprm); if (retval < 0) goto out; retval = copy_strings(bprm->argc, argv, bprm); if (retval < 0) goto out; retval = exec_binprm(bprm); if (retval < 0) goto out; /* execve succeeded */ current->fs->in_exec = 0; current->in_execve = 0; acct_update_integrals(current); task_numa_free(current); free_bprm(bprm); if (displaced) put_files_struct(displaced); return retval; out: if (bprm->mm) { acct_arg_size(bprm, 0); mmput(bprm->mm); } out_file: if (bprm->file) { allow_write_access(bprm->file); fput(bprm->file); } out_unmark: if (clear_in_exec) current->fs->in_exec = 0; current->in_execve = 0; out_free: free_bprm(bprm); out_files: if (displaced) reset_files_struct(displaced); out_ret: return retval; } int do_execve(const char *filename, const char __user *const __user *__argv, const char __user *const __user *__envp) { struct user_arg_ptr argv = { .ptr.native = __argv }; struct user_arg_ptr envp = { .ptr.native = __envp }; return do_execve_common(filename, argv, envp); } #ifdef CONFIG_COMPAT static int compat_do_execve(const char *filename, const compat_uptr_t __user *__argv, const compat_uptr_t __user *__envp) { struct user_arg_ptr argv = { .is_compat = true, .ptr.compat = __argv, }; struct user_arg_ptr envp = { .is_compat = true, .ptr.compat = __envp, }; return do_execve_common(filename, argv, envp); } #endif void set_binfmt(struct linux_binfmt *new) { struct mm_struct *mm = current->mm; if (mm->binfmt) module_put(mm->binfmt->module); mm->binfmt = new; if (new) __module_get(new->module); } EXPORT_SYMBOL(set_binfmt); /* * set_dumpable converts traditional three-value dumpable to two flags and * stores them into mm->flags. It modifies lower two bits of mm->flags, but * these bits are not changed atomically. So get_dumpable can observe the * intermediate state. To avoid doing unexpected behavior, get get_dumpable * return either old dumpable or new one by paying attention to the order of * modifying the bits. * * dumpable | mm->flags (binary) * old new | initial interim final * ---------+----------------------- * 0 1 | 00 01 01 * 0 2 | 00 10(*) 11 * 1 0 | 01 00 00 * 1 2 | 01 11 11 * 2 0 | 11 10(*) 00 * 2 1 | 11 11 01 * * (*) get_dumpable regards interim value of 10 as 11. */ void set_dumpable(struct mm_struct *mm, int value) { switch (value) { case SUID_DUMP_DISABLE: clear_bit(MMF_DUMPABLE, &mm->flags); smp_wmb(); clear_bit(MMF_DUMP_SECURELY, &mm->flags); break; case SUID_DUMP_USER: set_bit(MMF_DUMPABLE, &mm->flags); smp_wmb(); clear_bit(MMF_DUMP_SECURELY, &mm->flags); break; case SUID_DUMP_ROOT: set_bit(MMF_DUMP_SECURELY, &mm->flags); smp_wmb(); set_bit(MMF_DUMPABLE, &mm->flags); break; } } int __get_dumpable(unsigned long mm_flags) { int ret; ret = mm_flags & MMF_DUMPABLE_MASK; return (ret > SUID_DUMP_USER) ? SUID_DUMP_ROOT : ret; } int get_dumpable(struct mm_struct *mm) { return __get_dumpable(mm->flags); } SYSCALL_DEFINE3(execve, const char __user *, filename, const char __user *const __user *, argv, const char __user *const __user *, envp) { struct filename *path = getname(filename); int error = PTR_ERR(path); if (!IS_ERR(path)) { error = do_execve(path->name, argv, envp); putname(path); } return error; } #ifdef CONFIG_COMPAT asmlinkage long compat_sys_execve(const char __user * filename, const compat_uptr_t __user * argv, const compat_uptr_t __user * envp) { struct filename *path = getname(filename); int error = PTR_ERR(path); if (!IS_ERR(path)) { error = compat_do_execve(path->name, argv, envp); putname(path); } return error; } #endif
./CrossVul/dataset_final_sorted/CWE-264/c/bad_5676_1
crossvul-cpp_data_good_5861_27
/* * Glue Code for the AVX assembler implemention of the Cast5 Cipher * * Copyright (C) 2012 Johannes Goetzfried * <Johannes.Goetzfried@informatik.stud.uni-erlangen.de> * * 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/module.h> #include <linux/hardirq.h> #include <linux/types.h> #include <linux/crypto.h> #include <linux/err.h> #include <crypto/ablk_helper.h> #include <crypto/algapi.h> #include <crypto/cast5.h> #include <crypto/cryptd.h> #include <crypto/ctr.h> #include <asm/xcr.h> #include <asm/xsave.h> #include <asm/crypto/glue_helper.h> #define CAST5_PARALLEL_BLOCKS 16 asmlinkage void cast5_ecb_enc_16way(struct cast5_ctx *ctx, u8 *dst, const u8 *src); asmlinkage void cast5_ecb_dec_16way(struct cast5_ctx *ctx, u8 *dst, const u8 *src); asmlinkage void cast5_cbc_dec_16way(struct cast5_ctx *ctx, u8 *dst, const u8 *src); asmlinkage void cast5_ctr_16way(struct cast5_ctx *ctx, u8 *dst, const u8 *src, __be64 *iv); static inline bool cast5_fpu_begin(bool fpu_enabled, unsigned int nbytes) { return glue_fpu_begin(CAST5_BLOCK_SIZE, CAST5_PARALLEL_BLOCKS, NULL, fpu_enabled, nbytes); } static inline void cast5_fpu_end(bool fpu_enabled) { return glue_fpu_end(fpu_enabled); } static int ecb_crypt(struct blkcipher_desc *desc, struct blkcipher_walk *walk, bool enc) { bool fpu_enabled = false; struct cast5_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); const unsigned int bsize = CAST5_BLOCK_SIZE; unsigned int nbytes; void (*fn)(struct cast5_ctx *ctx, u8 *dst, const u8 *src); int err; fn = (enc) ? cast5_ecb_enc_16way : cast5_ecb_dec_16way; err = blkcipher_walk_virt(desc, walk); desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP; while ((nbytes = walk->nbytes)) { u8 *wsrc = walk->src.virt.addr; u8 *wdst = walk->dst.virt.addr; fpu_enabled = cast5_fpu_begin(fpu_enabled, nbytes); /* Process multi-block batch */ if (nbytes >= bsize * CAST5_PARALLEL_BLOCKS) { do { fn(ctx, wdst, wsrc); wsrc += bsize * CAST5_PARALLEL_BLOCKS; wdst += bsize * CAST5_PARALLEL_BLOCKS; nbytes -= bsize * CAST5_PARALLEL_BLOCKS; } while (nbytes >= bsize * CAST5_PARALLEL_BLOCKS); if (nbytes < bsize) goto done; } fn = (enc) ? __cast5_encrypt : __cast5_decrypt; /* Handle leftovers */ do { fn(ctx, wdst, wsrc); wsrc += bsize; wdst += bsize; nbytes -= bsize; } while (nbytes >= bsize); done: err = blkcipher_walk_done(desc, walk, nbytes); } cast5_fpu_end(fpu_enabled); return err; } static int ecb_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct blkcipher_walk walk; blkcipher_walk_init(&walk, dst, src, nbytes); return ecb_crypt(desc, &walk, true); } static int ecb_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct blkcipher_walk walk; blkcipher_walk_init(&walk, dst, src, nbytes); return ecb_crypt(desc, &walk, false); } static unsigned int __cbc_encrypt(struct blkcipher_desc *desc, struct blkcipher_walk *walk) { struct cast5_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); const unsigned int bsize = CAST5_BLOCK_SIZE; unsigned int nbytes = walk->nbytes; u64 *src = (u64 *)walk->src.virt.addr; u64 *dst = (u64 *)walk->dst.virt.addr; u64 *iv = (u64 *)walk->iv; do { *dst = *src ^ *iv; __cast5_encrypt(ctx, (u8 *)dst, (u8 *)dst); iv = dst; src += 1; dst += 1; nbytes -= bsize; } while (nbytes >= bsize); *(u64 *)walk->iv = *iv; return nbytes; } static int cbc_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct blkcipher_walk walk; int err; blkcipher_walk_init(&walk, dst, src, nbytes); err = blkcipher_walk_virt(desc, &walk); while ((nbytes = walk.nbytes)) { nbytes = __cbc_encrypt(desc, &walk); err = blkcipher_walk_done(desc, &walk, nbytes); } return err; } static unsigned int __cbc_decrypt(struct blkcipher_desc *desc, struct blkcipher_walk *walk) { struct cast5_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); const unsigned int bsize = CAST5_BLOCK_SIZE; unsigned int nbytes = walk->nbytes; u64 *src = (u64 *)walk->src.virt.addr; u64 *dst = (u64 *)walk->dst.virt.addr; u64 last_iv; /* Start of the last block. */ src += nbytes / bsize - 1; dst += nbytes / bsize - 1; last_iv = *src; /* Process multi-block batch */ if (nbytes >= bsize * CAST5_PARALLEL_BLOCKS) { do { nbytes -= bsize * (CAST5_PARALLEL_BLOCKS - 1); src -= CAST5_PARALLEL_BLOCKS - 1; dst -= CAST5_PARALLEL_BLOCKS - 1; cast5_cbc_dec_16way(ctx, (u8 *)dst, (u8 *)src); nbytes -= bsize; if (nbytes < bsize) goto done; *dst ^= *(src - 1); src -= 1; dst -= 1; } while (nbytes >= bsize * CAST5_PARALLEL_BLOCKS); } /* Handle leftovers */ for (;;) { __cast5_decrypt(ctx, (u8 *)dst, (u8 *)src); nbytes -= bsize; if (nbytes < bsize) break; *dst ^= *(src - 1); src -= 1; dst -= 1; } done: *dst ^= *(u64 *)walk->iv; *(u64 *)walk->iv = last_iv; return nbytes; } static int cbc_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { bool fpu_enabled = false; struct blkcipher_walk walk; int err; blkcipher_walk_init(&walk, dst, src, nbytes); err = blkcipher_walk_virt(desc, &walk); desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP; while ((nbytes = walk.nbytes)) { fpu_enabled = cast5_fpu_begin(fpu_enabled, nbytes); nbytes = __cbc_decrypt(desc, &walk); err = blkcipher_walk_done(desc, &walk, nbytes); } cast5_fpu_end(fpu_enabled); return err; } static void ctr_crypt_final(struct blkcipher_desc *desc, struct blkcipher_walk *walk) { struct cast5_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); u8 *ctrblk = walk->iv; u8 keystream[CAST5_BLOCK_SIZE]; u8 *src = walk->src.virt.addr; u8 *dst = walk->dst.virt.addr; unsigned int nbytes = walk->nbytes; __cast5_encrypt(ctx, keystream, ctrblk); crypto_xor(keystream, src, nbytes); memcpy(dst, keystream, nbytes); crypto_inc(ctrblk, CAST5_BLOCK_SIZE); } static unsigned int __ctr_crypt(struct blkcipher_desc *desc, struct blkcipher_walk *walk) { struct cast5_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); const unsigned int bsize = CAST5_BLOCK_SIZE; unsigned int nbytes = walk->nbytes; u64 *src = (u64 *)walk->src.virt.addr; u64 *dst = (u64 *)walk->dst.virt.addr; /* Process multi-block batch */ if (nbytes >= bsize * CAST5_PARALLEL_BLOCKS) { do { cast5_ctr_16way(ctx, (u8 *)dst, (u8 *)src, (__be64 *)walk->iv); src += CAST5_PARALLEL_BLOCKS; dst += CAST5_PARALLEL_BLOCKS; nbytes -= bsize * CAST5_PARALLEL_BLOCKS; } while (nbytes >= bsize * CAST5_PARALLEL_BLOCKS); if (nbytes < bsize) goto done; } /* Handle leftovers */ do { u64 ctrblk; if (dst != src) *dst = *src; ctrblk = *(u64 *)walk->iv; be64_add_cpu((__be64 *)walk->iv, 1); __cast5_encrypt(ctx, (u8 *)&ctrblk, (u8 *)&ctrblk); *dst ^= ctrblk; src += 1; dst += 1; nbytes -= bsize; } while (nbytes >= bsize); done: return nbytes; } static int ctr_crypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { bool fpu_enabled = false; struct blkcipher_walk walk; int err; blkcipher_walk_init(&walk, dst, src, nbytes); err = blkcipher_walk_virt_block(desc, &walk, CAST5_BLOCK_SIZE); desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP; while ((nbytes = walk.nbytes) >= CAST5_BLOCK_SIZE) { fpu_enabled = cast5_fpu_begin(fpu_enabled, nbytes); nbytes = __ctr_crypt(desc, &walk); err = blkcipher_walk_done(desc, &walk, nbytes); } cast5_fpu_end(fpu_enabled); if (walk.nbytes) { ctr_crypt_final(desc, &walk); err = blkcipher_walk_done(desc, &walk, 0); } return err; } static struct crypto_alg cast5_algs[6] = { { .cra_name = "__ecb-cast5-avx", .cra_driver_name = "__driver-ecb-cast5-avx", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = CAST5_BLOCK_SIZE, .cra_ctxsize = sizeof(struct cast5_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = CAST5_MIN_KEY_SIZE, .max_keysize = CAST5_MAX_KEY_SIZE, .setkey = cast5_setkey, .encrypt = ecb_encrypt, .decrypt = ecb_decrypt, }, }, }, { .cra_name = "__cbc-cast5-avx", .cra_driver_name = "__driver-cbc-cast5-avx", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = CAST5_BLOCK_SIZE, .cra_ctxsize = sizeof(struct cast5_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = CAST5_MIN_KEY_SIZE, .max_keysize = CAST5_MAX_KEY_SIZE, .setkey = cast5_setkey, .encrypt = cbc_encrypt, .decrypt = cbc_decrypt, }, }, }, { .cra_name = "__ctr-cast5-avx", .cra_driver_name = "__driver-ctr-cast5-avx", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, .cra_blocksize = 1, .cra_ctxsize = sizeof(struct cast5_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = CAST5_MIN_KEY_SIZE, .max_keysize = CAST5_MAX_KEY_SIZE, .ivsize = CAST5_BLOCK_SIZE, .setkey = cast5_setkey, .encrypt = ctr_crypt, .decrypt = ctr_crypt, }, }, }, { .cra_name = "ecb(cast5)", .cra_driver_name = "ecb-cast5-avx", .cra_priority = 200, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = CAST5_BLOCK_SIZE, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = CAST5_MIN_KEY_SIZE, .max_keysize = CAST5_MAX_KEY_SIZE, .setkey = ablk_set_key, .encrypt = ablk_encrypt, .decrypt = ablk_decrypt, }, }, }, { .cra_name = "cbc(cast5)", .cra_driver_name = "cbc-cast5-avx", .cra_priority = 200, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = CAST5_BLOCK_SIZE, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = CAST5_MIN_KEY_SIZE, .max_keysize = CAST5_MAX_KEY_SIZE, .ivsize = CAST5_BLOCK_SIZE, .setkey = ablk_set_key, .encrypt = __ablk_encrypt, .decrypt = ablk_decrypt, }, }, }, { .cra_name = "ctr(cast5)", .cra_driver_name = "ctr-cast5-avx", .cra_priority = 200, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = 1, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = CAST5_MIN_KEY_SIZE, .max_keysize = CAST5_MAX_KEY_SIZE, .ivsize = CAST5_BLOCK_SIZE, .setkey = ablk_set_key, .encrypt = ablk_encrypt, .decrypt = ablk_encrypt, .geniv = "chainiv", }, }, } }; static int __init cast5_init(void) { u64 xcr0; if (!cpu_has_avx || !cpu_has_osxsave) { pr_info("AVX instructions are not detected.\n"); return -ENODEV; } xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK); if ((xcr0 & (XSTATE_SSE | XSTATE_YMM)) != (XSTATE_SSE | XSTATE_YMM)) { pr_info("AVX detected but unusable.\n"); return -ENODEV; } return crypto_register_algs(cast5_algs, ARRAY_SIZE(cast5_algs)); } static void __exit cast5_exit(void) { crypto_unregister_algs(cast5_algs, ARRAY_SIZE(cast5_algs)); } module_init(cast5_init); module_exit(cast5_exit); MODULE_DESCRIPTION("Cast5 Cipher Algorithm, AVX optimized"); MODULE_LICENSE("GPL"); MODULE_ALIAS_CRYPTO("cast5");
./CrossVul/dataset_final_sorted/CWE-264/c/good_5861_27
crossvul-cpp_data_good_3524_10
/* -*- linux-c -*- * INET 802.1Q VLAN * Ethernet-type device handling. * * Authors: Ben Greear <greearb@candelatech.com> * Please send support related email to: netdev@vger.kernel.org * VLAN Home Page: http://www.candelatech.com/~greear/vlan.html * * Fixes: Mar 22 2001: Martin Bokaemper <mbokaemper@unispherenetworks.com> * - reset skb->pkt_type on incoming packets when MAC was changed * - see that changed MAC is saddr for outgoing packets * Oct 20, 2001: Ard van Breeman: * - Fix MC-list, finally. * - Flush MC-list on VLAN destroy. * * * 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/module.h> #include <linux/slab.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/ethtool.h> #include <net/arp.h> #include "vlan.h" #include "vlanproc.h" #include <linux/if_vlan.h> /* * Rebuild the Ethernet MAC header. This is called after an ARP * (or in future other address resolution) has completed on this * sk_buff. We now let ARP fill in the other fields. * * This routine CANNOT use cached dst->neigh! * Really, it is used only when dst->neigh is wrong. * * TODO: This needs a checkup, I'm ignorant here. --BLG */ static int vlan_dev_rebuild_header(struct sk_buff *skb) { struct net_device *dev = skb->dev; struct vlan_ethhdr *veth = (struct vlan_ethhdr *)(skb->data); switch (veth->h_vlan_encapsulated_proto) { #ifdef CONFIG_INET case htons(ETH_P_IP): /* TODO: Confirm this will work with VLAN headers... */ return arp_find(veth->h_dest, skb); #endif default: pr_debug("%s: unable to resolve type %X addresses\n", dev->name, ntohs(veth->h_vlan_encapsulated_proto)); memcpy(veth->h_source, dev->dev_addr, ETH_ALEN); break; } return 0; } static inline u16 vlan_dev_get_egress_qos_mask(struct net_device *dev, struct sk_buff *skb) { struct vlan_priority_tci_mapping *mp; mp = vlan_dev_info(dev)->egress_priority_map[(skb->priority & 0xF)]; while (mp) { if (mp->priority == skb->priority) { return mp->vlan_qos; /* This should already be shifted * to mask correctly with the * VLAN's TCI */ } mp = mp->next; } return 0; } /* * Create the VLAN header for an arbitrary protocol layer * * saddr=NULL means use device source address * daddr=NULL means leave destination address (eg unresolved arp) * * This is called when the SKB is moving down the stack towards the * physical devices. */ static int vlan_dev_hard_header(struct sk_buff *skb, struct net_device *dev, unsigned short type, const void *daddr, const void *saddr, unsigned int len) { struct vlan_hdr *vhdr; unsigned int vhdrlen = 0; u16 vlan_tci = 0; int rc; if (!(vlan_dev_info(dev)->flags & VLAN_FLAG_REORDER_HDR)) { vhdr = (struct vlan_hdr *) skb_push(skb, VLAN_HLEN); vlan_tci = vlan_dev_info(dev)->vlan_id; vlan_tci |= vlan_dev_get_egress_qos_mask(dev, skb); vhdr->h_vlan_TCI = htons(vlan_tci); /* * Set the protocol type. For a packet of type ETH_P_802_3/2 we * put the length in here instead. */ if (type != ETH_P_802_3 && type != ETH_P_802_2) vhdr->h_vlan_encapsulated_proto = htons(type); else vhdr->h_vlan_encapsulated_proto = htons(len); skb->protocol = htons(ETH_P_8021Q); type = ETH_P_8021Q; vhdrlen = VLAN_HLEN; } /* Before delegating work to the lower layer, enter our MAC-address */ if (saddr == NULL) saddr = dev->dev_addr; /* Now make the underlying real hard header */ dev = vlan_dev_info(dev)->real_dev; rc = dev_hard_header(skb, dev, type, daddr, saddr, len + vhdrlen); if (rc > 0) rc += vhdrlen; return rc; } static netdev_tx_t vlan_dev_hard_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct vlan_ethhdr *veth = (struct vlan_ethhdr *)(skb->data); unsigned int len; int ret; /* Handle non-VLAN frames if they are sent to us, for example by DHCP. * * NOTE: THIS ASSUMES DIX ETHERNET, SPECIFICALLY NOT SUPPORTING * OTHER THINGS LIKE FDDI/TokenRing/802.3 SNAPs... */ if (veth->h_vlan_proto != htons(ETH_P_8021Q) || vlan_dev_info(dev)->flags & VLAN_FLAG_REORDER_HDR) { u16 vlan_tci; vlan_tci = vlan_dev_info(dev)->vlan_id; vlan_tci |= vlan_dev_get_egress_qos_mask(dev, skb); skb = __vlan_hwaccel_put_tag(skb, vlan_tci); } skb_set_dev(skb, vlan_dev_info(dev)->real_dev); len = skb->len; ret = dev_queue_xmit(skb); if (likely(ret == NET_XMIT_SUCCESS || ret == NET_XMIT_CN)) { struct vlan_pcpu_stats *stats; stats = this_cpu_ptr(vlan_dev_info(dev)->vlan_pcpu_stats); u64_stats_update_begin(&stats->syncp); stats->tx_packets++; stats->tx_bytes += len; u64_stats_update_end(&stats->syncp); } else { this_cpu_inc(vlan_dev_info(dev)->vlan_pcpu_stats->tx_dropped); } return ret; } static int vlan_dev_change_mtu(struct net_device *dev, int new_mtu) { /* TODO: gotta make sure the underlying layer can handle it, * maybe an IFF_VLAN_CAPABLE flag for devices? */ if (vlan_dev_info(dev)->real_dev->mtu < new_mtu) return -ERANGE; dev->mtu = new_mtu; return 0; } void vlan_dev_set_ingress_priority(const struct net_device *dev, u32 skb_prio, u16 vlan_prio) { struct vlan_dev_info *vlan = vlan_dev_info(dev); if (vlan->ingress_priority_map[vlan_prio & 0x7] && !skb_prio) vlan->nr_ingress_mappings--; else if (!vlan->ingress_priority_map[vlan_prio & 0x7] && skb_prio) vlan->nr_ingress_mappings++; vlan->ingress_priority_map[vlan_prio & 0x7] = skb_prio; } int vlan_dev_set_egress_priority(const struct net_device *dev, u32 skb_prio, u16 vlan_prio) { struct vlan_dev_info *vlan = vlan_dev_info(dev); struct vlan_priority_tci_mapping *mp = NULL; struct vlan_priority_tci_mapping *np; u32 vlan_qos = (vlan_prio << VLAN_PRIO_SHIFT) & VLAN_PRIO_MASK; /* See if a priority mapping exists.. */ mp = vlan->egress_priority_map[skb_prio & 0xF]; while (mp) { if (mp->priority == skb_prio) { if (mp->vlan_qos && !vlan_qos) vlan->nr_egress_mappings--; else if (!mp->vlan_qos && vlan_qos) vlan->nr_egress_mappings++; mp->vlan_qos = vlan_qos; return 0; } mp = mp->next; } /* Create a new mapping then. */ mp = vlan->egress_priority_map[skb_prio & 0xF]; np = kmalloc(sizeof(struct vlan_priority_tci_mapping), GFP_KERNEL); if (!np) return -ENOBUFS; np->next = mp; np->priority = skb_prio; np->vlan_qos = vlan_qos; vlan->egress_priority_map[skb_prio & 0xF] = np; if (vlan_qos) vlan->nr_egress_mappings++; return 0; } /* Flags are defined in the vlan_flags enum in include/linux/if_vlan.h file. */ int vlan_dev_change_flags(const struct net_device *dev, u32 flags, u32 mask) { struct vlan_dev_info *vlan = vlan_dev_info(dev); u32 old_flags = vlan->flags; if (mask & ~(VLAN_FLAG_REORDER_HDR | VLAN_FLAG_GVRP | VLAN_FLAG_LOOSE_BINDING)) return -EINVAL; vlan->flags = (old_flags & ~mask) | (flags & mask); if (netif_running(dev) && (vlan->flags ^ old_flags) & VLAN_FLAG_GVRP) { if (vlan->flags & VLAN_FLAG_GVRP) vlan_gvrp_request_join(dev); else vlan_gvrp_request_leave(dev); } return 0; } void vlan_dev_get_realdev_name(const struct net_device *dev, char *result) { strncpy(result, vlan_dev_info(dev)->real_dev->name, 23); } static int vlan_dev_open(struct net_device *dev) { struct vlan_dev_info *vlan = vlan_dev_info(dev); struct net_device *real_dev = vlan->real_dev; int err; if (!(real_dev->flags & IFF_UP) && !(vlan->flags & VLAN_FLAG_LOOSE_BINDING)) return -ENETDOWN; if (compare_ether_addr(dev->dev_addr, real_dev->dev_addr)) { err = dev_uc_add(real_dev, dev->dev_addr); if (err < 0) goto out; } if (dev->flags & IFF_ALLMULTI) { err = dev_set_allmulti(real_dev, 1); if (err < 0) goto del_unicast; } if (dev->flags & IFF_PROMISC) { err = dev_set_promiscuity(real_dev, 1); if (err < 0) goto clear_allmulti; } memcpy(vlan->real_dev_addr, real_dev->dev_addr, ETH_ALEN); if (vlan->flags & VLAN_FLAG_GVRP) vlan_gvrp_request_join(dev); if (netif_carrier_ok(real_dev)) netif_carrier_on(dev); return 0; clear_allmulti: if (dev->flags & IFF_ALLMULTI) dev_set_allmulti(real_dev, -1); del_unicast: if (compare_ether_addr(dev->dev_addr, real_dev->dev_addr)) dev_uc_del(real_dev, dev->dev_addr); out: netif_carrier_off(dev); return err; } static int vlan_dev_stop(struct net_device *dev) { struct vlan_dev_info *vlan = vlan_dev_info(dev); struct net_device *real_dev = vlan->real_dev; dev_mc_unsync(real_dev, dev); dev_uc_unsync(real_dev, dev); if (dev->flags & IFF_ALLMULTI) dev_set_allmulti(real_dev, -1); if (dev->flags & IFF_PROMISC) dev_set_promiscuity(real_dev, -1); if (compare_ether_addr(dev->dev_addr, real_dev->dev_addr)) dev_uc_del(real_dev, dev->dev_addr); netif_carrier_off(dev); return 0; } static int vlan_dev_set_mac_address(struct net_device *dev, void *p) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; struct sockaddr *addr = p; int err; if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; if (!(dev->flags & IFF_UP)) goto out; if (compare_ether_addr(addr->sa_data, real_dev->dev_addr)) { err = dev_uc_add(real_dev, addr->sa_data); if (err < 0) return err; } if (compare_ether_addr(dev->dev_addr, real_dev->dev_addr)) dev_uc_del(real_dev, dev->dev_addr); out: memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN); return 0; } static int vlan_dev_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; const struct net_device_ops *ops = real_dev->netdev_ops; struct ifreq ifrr; int err = -EOPNOTSUPP; strncpy(ifrr.ifr_name, real_dev->name, IFNAMSIZ); ifrr.ifr_ifru = ifr->ifr_ifru; switch (cmd) { case SIOCGMIIPHY: case SIOCGMIIREG: case SIOCSMIIREG: if (netif_device_present(real_dev) && ops->ndo_do_ioctl) err = ops->ndo_do_ioctl(real_dev, &ifrr, cmd); break; } if (!err) ifr->ifr_ifru = ifrr.ifr_ifru; return err; } static int vlan_dev_neigh_setup(struct net_device *dev, struct neigh_parms *pa) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; const struct net_device_ops *ops = real_dev->netdev_ops; int err = 0; if (netif_device_present(real_dev) && ops->ndo_neigh_setup) err = ops->ndo_neigh_setup(real_dev, pa); return err; } #if defined(CONFIG_FCOE) || defined(CONFIG_FCOE_MODULE) static int vlan_dev_fcoe_ddp_setup(struct net_device *dev, u16 xid, struct scatterlist *sgl, unsigned int sgc) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; const struct net_device_ops *ops = real_dev->netdev_ops; int rc = 0; if (ops->ndo_fcoe_ddp_setup) rc = ops->ndo_fcoe_ddp_setup(real_dev, xid, sgl, sgc); return rc; } static int vlan_dev_fcoe_ddp_done(struct net_device *dev, u16 xid) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; const struct net_device_ops *ops = real_dev->netdev_ops; int len = 0; if (ops->ndo_fcoe_ddp_done) len = ops->ndo_fcoe_ddp_done(real_dev, xid); return len; } static int vlan_dev_fcoe_enable(struct net_device *dev) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; const struct net_device_ops *ops = real_dev->netdev_ops; int rc = -EINVAL; if (ops->ndo_fcoe_enable) rc = ops->ndo_fcoe_enable(real_dev); return rc; } static int vlan_dev_fcoe_disable(struct net_device *dev) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; const struct net_device_ops *ops = real_dev->netdev_ops; int rc = -EINVAL; if (ops->ndo_fcoe_disable) rc = ops->ndo_fcoe_disable(real_dev); return rc; } static int vlan_dev_fcoe_get_wwn(struct net_device *dev, u64 *wwn, int type) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; const struct net_device_ops *ops = real_dev->netdev_ops; int rc = -EINVAL; if (ops->ndo_fcoe_get_wwn) rc = ops->ndo_fcoe_get_wwn(real_dev, wwn, type); return rc; } static int vlan_dev_fcoe_ddp_target(struct net_device *dev, u16 xid, struct scatterlist *sgl, unsigned int sgc) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; const struct net_device_ops *ops = real_dev->netdev_ops; int rc = 0; if (ops->ndo_fcoe_ddp_target) rc = ops->ndo_fcoe_ddp_target(real_dev, xid, sgl, sgc); return rc; } #endif static void vlan_dev_change_rx_flags(struct net_device *dev, int change) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; if (change & IFF_ALLMULTI) dev_set_allmulti(real_dev, dev->flags & IFF_ALLMULTI ? 1 : -1); if (change & IFF_PROMISC) dev_set_promiscuity(real_dev, dev->flags & IFF_PROMISC ? 1 : -1); } static void vlan_dev_set_rx_mode(struct net_device *vlan_dev) { dev_mc_sync(vlan_dev_info(vlan_dev)->real_dev, vlan_dev); dev_uc_sync(vlan_dev_info(vlan_dev)->real_dev, vlan_dev); } /* * vlan network devices have devices nesting below it, and are a special * "super class" of normal network devices; split their locks off into a * separate class since they always nest. */ static struct lock_class_key vlan_netdev_xmit_lock_key; static struct lock_class_key vlan_netdev_addr_lock_key; static void vlan_dev_set_lockdep_one(struct net_device *dev, struct netdev_queue *txq, void *_subclass) { lockdep_set_class_and_subclass(&txq->_xmit_lock, &vlan_netdev_xmit_lock_key, *(int *)_subclass); } static void vlan_dev_set_lockdep_class(struct net_device *dev, int subclass) { lockdep_set_class_and_subclass(&dev->addr_list_lock, &vlan_netdev_addr_lock_key, subclass); netdev_for_each_tx_queue(dev, vlan_dev_set_lockdep_one, &subclass); } static const struct header_ops vlan_header_ops = { .create = vlan_dev_hard_header, .rebuild = vlan_dev_rebuild_header, .parse = eth_header_parse, }; static const struct net_device_ops vlan_netdev_ops; static int vlan_dev_init(struct net_device *dev) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; int subclass = 0; netif_carrier_off(dev); /* IFF_BROADCAST|IFF_MULTICAST; ??? */ dev->flags = real_dev->flags & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_MASTER | IFF_SLAVE); dev->iflink = real_dev->ifindex; dev->state = (real_dev->state & ((1<<__LINK_STATE_NOCARRIER) | (1<<__LINK_STATE_DORMANT))) | (1<<__LINK_STATE_PRESENT); dev->hw_features = NETIF_F_ALL_CSUM | NETIF_F_SG | NETIF_F_FRAGLIST | NETIF_F_ALL_TSO | NETIF_F_HIGHDMA | NETIF_F_SCTP_CSUM | NETIF_F_ALL_FCOE; dev->features |= real_dev->vlan_features | NETIF_F_LLTX; dev->gso_max_size = real_dev->gso_max_size; /* ipv6 shared card related stuff */ dev->dev_id = real_dev->dev_id; if (is_zero_ether_addr(dev->dev_addr)) memcpy(dev->dev_addr, real_dev->dev_addr, dev->addr_len); if (is_zero_ether_addr(dev->broadcast)) memcpy(dev->broadcast, real_dev->broadcast, dev->addr_len); #if defined(CONFIG_FCOE) || defined(CONFIG_FCOE_MODULE) dev->fcoe_ddp_xid = real_dev->fcoe_ddp_xid; #endif dev->needed_headroom = real_dev->needed_headroom; if (real_dev->features & NETIF_F_HW_VLAN_TX) { dev->header_ops = real_dev->header_ops; dev->hard_header_len = real_dev->hard_header_len; } else { dev->header_ops = &vlan_header_ops; dev->hard_header_len = real_dev->hard_header_len + VLAN_HLEN; } dev->netdev_ops = &vlan_netdev_ops; if (is_vlan_dev(real_dev)) subclass = 1; vlan_dev_set_lockdep_class(dev, subclass); vlan_dev_info(dev)->vlan_pcpu_stats = alloc_percpu(struct vlan_pcpu_stats); if (!vlan_dev_info(dev)->vlan_pcpu_stats) return -ENOMEM; return 0; } static void vlan_dev_uninit(struct net_device *dev) { struct vlan_priority_tci_mapping *pm; struct vlan_dev_info *vlan = vlan_dev_info(dev); int i; free_percpu(vlan->vlan_pcpu_stats); vlan->vlan_pcpu_stats = NULL; for (i = 0; i < ARRAY_SIZE(vlan->egress_priority_map); i++) { while ((pm = vlan->egress_priority_map[i]) != NULL) { vlan->egress_priority_map[i] = pm->next; kfree(pm); } } } static u32 vlan_dev_fix_features(struct net_device *dev, u32 features) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; u32 old_features = features; features &= real_dev->features; features &= real_dev->vlan_features; features |= old_features & NETIF_F_SOFT_FEATURES; if (dev_ethtool_get_rx_csum(real_dev)) features |= NETIF_F_RXCSUM; features |= NETIF_F_LLTX; return features; } static int vlan_ethtool_get_settings(struct net_device *dev, struct ethtool_cmd *cmd) { const struct vlan_dev_info *vlan = vlan_dev_info(dev); return dev_ethtool_get_settings(vlan->real_dev, cmd); } static void vlan_ethtool_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { strcpy(info->driver, vlan_fullname); strcpy(info->version, vlan_version); strcpy(info->fw_version, "N/A"); } static struct rtnl_link_stats64 *vlan_dev_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats) { if (vlan_dev_info(dev)->vlan_pcpu_stats) { struct vlan_pcpu_stats *p; u32 rx_errors = 0, tx_dropped = 0; int i; for_each_possible_cpu(i) { u64 rxpackets, rxbytes, rxmulticast, txpackets, txbytes; unsigned int start; p = per_cpu_ptr(vlan_dev_info(dev)->vlan_pcpu_stats, i); do { start = u64_stats_fetch_begin_bh(&p->syncp); rxpackets = p->rx_packets; rxbytes = p->rx_bytes; rxmulticast = p->rx_multicast; txpackets = p->tx_packets; txbytes = p->tx_bytes; } while (u64_stats_fetch_retry_bh(&p->syncp, start)); stats->rx_packets += rxpackets; stats->rx_bytes += rxbytes; stats->multicast += rxmulticast; stats->tx_packets += txpackets; stats->tx_bytes += txbytes; /* rx_errors & tx_dropped are u32 */ rx_errors += p->rx_errors; tx_dropped += p->tx_dropped; } stats->rx_errors = rx_errors; stats->tx_dropped = tx_dropped; } return stats; } static const struct ethtool_ops vlan_ethtool_ops = { .get_settings = vlan_ethtool_get_settings, .get_drvinfo = vlan_ethtool_get_drvinfo, .get_link = ethtool_op_get_link, }; static const struct net_device_ops vlan_netdev_ops = { .ndo_change_mtu = vlan_dev_change_mtu, .ndo_init = vlan_dev_init, .ndo_uninit = vlan_dev_uninit, .ndo_open = vlan_dev_open, .ndo_stop = vlan_dev_stop, .ndo_start_xmit = vlan_dev_hard_start_xmit, .ndo_validate_addr = eth_validate_addr, .ndo_set_mac_address = vlan_dev_set_mac_address, .ndo_set_rx_mode = vlan_dev_set_rx_mode, .ndo_set_multicast_list = vlan_dev_set_rx_mode, .ndo_change_rx_flags = vlan_dev_change_rx_flags, .ndo_do_ioctl = vlan_dev_ioctl, .ndo_neigh_setup = vlan_dev_neigh_setup, .ndo_get_stats64 = vlan_dev_get_stats64, #if defined(CONFIG_FCOE) || defined(CONFIG_FCOE_MODULE) .ndo_fcoe_ddp_setup = vlan_dev_fcoe_ddp_setup, .ndo_fcoe_ddp_done = vlan_dev_fcoe_ddp_done, .ndo_fcoe_enable = vlan_dev_fcoe_enable, .ndo_fcoe_disable = vlan_dev_fcoe_disable, .ndo_fcoe_get_wwn = vlan_dev_fcoe_get_wwn, .ndo_fcoe_ddp_target = vlan_dev_fcoe_ddp_target, #endif .ndo_fix_features = vlan_dev_fix_features, }; void vlan_setup(struct net_device *dev) { ether_setup(dev); dev->priv_flags |= IFF_802_1Q_VLAN; dev->priv_flags &= ~(IFF_XMIT_DST_RELEASE | IFF_TX_SKB_SHARING); dev->tx_queue_len = 0; dev->netdev_ops = &vlan_netdev_ops; dev->destructor = free_netdev; dev->ethtool_ops = &vlan_ethtool_ops; memset(dev->broadcast, 0, ETH_ALEN); }
./CrossVul/dataset_final_sorted/CWE-264/c/good_3524_10
crossvul-cpp_data_good_2423_4
/* * linux/arch/arm/kernel/ptrace.c * * By Ross Biro 1/23/92 * edited by Linus Torvalds * ARM modifications Copyright (C) 2000 Russell King * * 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. */ #include <linux/kernel.h> #include <linux/sched.h> #include <linux/mm.h> #include <linux/elf.h> #include <linux/smp.h> #include <linux/ptrace.h> #include <linux/user.h> #include <linux/security.h> #include <linux/init.h> #include <linux/signal.h> #include <linux/uaccess.h> #include <linux/perf_event.h> #include <linux/hw_breakpoint.h> #include <linux/regset.h> #include <linux/audit.h> #include <linux/tracehook.h> #include <linux/unistd.h> #include <asm/pgtable.h> #include <asm/traps.h> #define CREATE_TRACE_POINTS #include <trace/events/syscalls.h> #define REG_PC 15 #define REG_PSR 16 /* * does not yet catch signals sent when the child dies. * in exit.c or in signal.c. */ #if 0 /* * Breakpoint SWI instruction: SWI &9F0001 */ #define BREAKINST_ARM 0xef9f0001 #define BREAKINST_THUMB 0xdf00 /* fill this in later */ #else /* * New breakpoints - use an undefined instruction. The ARM architecture * reference manual guarantees that the following instruction space * will produce an undefined instruction exception on all CPUs: * * ARM: xxxx 0111 1111 xxxx xxxx xxxx 1111 xxxx * Thumb: 1101 1110 xxxx xxxx */ #define BREAKINST_ARM 0xe7f001f0 #define BREAKINST_THUMB 0xde01 #endif struct pt_regs_offset { const char *name; int offset; }; #define REG_OFFSET_NAME(r) \ {.name = #r, .offset = offsetof(struct pt_regs, ARM_##r)} #define REG_OFFSET_END {.name = NULL, .offset = 0} static const struct pt_regs_offset regoffset_table[] = { REG_OFFSET_NAME(r0), REG_OFFSET_NAME(r1), REG_OFFSET_NAME(r2), REG_OFFSET_NAME(r3), REG_OFFSET_NAME(r4), REG_OFFSET_NAME(r5), REG_OFFSET_NAME(r6), REG_OFFSET_NAME(r7), REG_OFFSET_NAME(r8), REG_OFFSET_NAME(r9), REG_OFFSET_NAME(r10), REG_OFFSET_NAME(fp), REG_OFFSET_NAME(ip), REG_OFFSET_NAME(sp), REG_OFFSET_NAME(lr), REG_OFFSET_NAME(pc), REG_OFFSET_NAME(cpsr), REG_OFFSET_NAME(ORIG_r0), REG_OFFSET_END, }; /** * regs_query_register_offset() - query register offset from its name * @name: the name of a register * * regs_query_register_offset() returns the offset of a register in struct * pt_regs from its name. If the name is invalid, this returns -EINVAL; */ int regs_query_register_offset(const char *name) { const struct pt_regs_offset *roff; for (roff = regoffset_table; roff->name != NULL; roff++) if (!strcmp(roff->name, name)) return roff->offset; return -EINVAL; } /** * regs_query_register_name() - query register name from its offset * @offset: the offset of a register in struct pt_regs. * * regs_query_register_name() returns the name of a register from its * offset in struct pt_regs. If the @offset is invalid, this returns NULL; */ const char *regs_query_register_name(unsigned int offset) { const struct pt_regs_offset *roff; for (roff = regoffset_table; roff->name != NULL; roff++) if (roff->offset == offset) return roff->name; return NULL; } /** * regs_within_kernel_stack() - check the address in the stack * @regs: pt_regs which contains kernel stack pointer. * @addr: address which is checked. * * regs_within_kernel_stack() checks @addr is within the kernel stack page(s). * If @addr is within the kernel stack, it returns true. If not, returns false. */ bool regs_within_kernel_stack(struct pt_regs *regs, unsigned long addr) { return ((addr & ~(THREAD_SIZE - 1)) == (kernel_stack_pointer(regs) & ~(THREAD_SIZE - 1))); } /** * regs_get_kernel_stack_nth() - get Nth entry of the stack * @regs: pt_regs which contains kernel stack pointer. * @n: stack entry number. * * regs_get_kernel_stack_nth() returns @n th entry of the kernel stack which * is specified by @regs. If the @n th entry is NOT in the kernel stack, * this returns 0. */ unsigned long regs_get_kernel_stack_nth(struct pt_regs *regs, unsigned int n) { unsigned long *addr = (unsigned long *)kernel_stack_pointer(regs); addr += n; if (regs_within_kernel_stack(regs, (unsigned long)addr)) return *addr; else return 0; } /* * this routine will get a word off of the processes privileged stack. * the offset is how far from the base addr as stored in the THREAD. * this routine assumes that all the privileged stacks are in our * data space. */ static inline long get_user_reg(struct task_struct *task, int offset) { return task_pt_regs(task)->uregs[offset]; } /* * this routine will put a word on the processes privileged stack. * the offset is how far from the base addr as stored in the THREAD. * this routine assumes that all the privileged stacks are in our * data space. */ static inline int put_user_reg(struct task_struct *task, int offset, long data) { struct pt_regs newregs, *regs = task_pt_regs(task); int ret = -EINVAL; newregs = *regs; newregs.uregs[offset] = data; if (valid_user_regs(&newregs)) { regs->uregs[offset] = data; ret = 0; } return ret; } /* * Called by kernel/ptrace.c when detaching.. */ void ptrace_disable(struct task_struct *child) { /* Nothing to do. */ } /* * Handle hitting a breakpoint. */ void ptrace_break(struct task_struct *tsk, struct pt_regs *regs) { siginfo_t info; info.si_signo = SIGTRAP; info.si_errno = 0; info.si_code = TRAP_BRKPT; info.si_addr = (void __user *)instruction_pointer(regs); force_sig_info(SIGTRAP, &info, tsk); } static int break_trap(struct pt_regs *regs, unsigned int instr) { ptrace_break(current, regs); return 0; } static struct undef_hook arm_break_hook = { .instr_mask = 0x0fffffff, .instr_val = 0x07f001f0, .cpsr_mask = PSR_T_BIT, .cpsr_val = 0, .fn = break_trap, }; static struct undef_hook thumb_break_hook = { .instr_mask = 0xffff, .instr_val = 0xde01, .cpsr_mask = PSR_T_BIT, .cpsr_val = PSR_T_BIT, .fn = break_trap, }; static struct undef_hook thumb2_break_hook = { .instr_mask = 0xffffffff, .instr_val = 0xf7f0a000, .cpsr_mask = PSR_T_BIT, .cpsr_val = PSR_T_BIT, .fn = break_trap, }; static int __init ptrace_break_init(void) { register_undef_hook(&arm_break_hook); register_undef_hook(&thumb_break_hook); register_undef_hook(&thumb2_break_hook); return 0; } core_initcall(ptrace_break_init); /* * Read the word at offset "off" into the "struct user". We * actually access the pt_regs stored on the kernel stack. */ static int ptrace_read_user(struct task_struct *tsk, unsigned long off, unsigned long __user *ret) { unsigned long tmp; if (off & 3) return -EIO; tmp = 0; if (off == PT_TEXT_ADDR) tmp = tsk->mm->start_code; else if (off == PT_DATA_ADDR) tmp = tsk->mm->start_data; else if (off == PT_TEXT_END_ADDR) tmp = tsk->mm->end_code; else if (off < sizeof(struct pt_regs)) tmp = get_user_reg(tsk, off >> 2); else if (off >= sizeof(struct user)) return -EIO; return put_user(tmp, ret); } /* * Write the word at offset "off" into "struct user". We * actually access the pt_regs stored on the kernel stack. */ static int ptrace_write_user(struct task_struct *tsk, unsigned long off, unsigned long val) { if (off & 3 || off >= sizeof(struct user)) return -EIO; if (off >= sizeof(struct pt_regs)) return 0; return put_user_reg(tsk, off >> 2, val); } #ifdef CONFIG_IWMMXT /* * Get the child iWMMXt state. */ static int ptrace_getwmmxregs(struct task_struct *tsk, void __user *ufp) { struct thread_info *thread = task_thread_info(tsk); if (!test_ti_thread_flag(thread, TIF_USING_IWMMXT)) return -ENODATA; iwmmxt_task_disable(thread); /* force it to ram */ return copy_to_user(ufp, &thread->fpstate.iwmmxt, IWMMXT_SIZE) ? -EFAULT : 0; } /* * Set the child iWMMXt state. */ static int ptrace_setwmmxregs(struct task_struct *tsk, void __user *ufp) { struct thread_info *thread = task_thread_info(tsk); if (!test_ti_thread_flag(thread, TIF_USING_IWMMXT)) return -EACCES; iwmmxt_task_release(thread); /* force a reload */ return copy_from_user(&thread->fpstate.iwmmxt, ufp, IWMMXT_SIZE) ? -EFAULT : 0; } #endif #ifdef CONFIG_CRUNCH /* * Get the child Crunch state. */ static int ptrace_getcrunchregs(struct task_struct *tsk, void __user *ufp) { struct thread_info *thread = task_thread_info(tsk); crunch_task_disable(thread); /* force it to ram */ return copy_to_user(ufp, &thread->crunchstate, CRUNCH_SIZE) ? -EFAULT : 0; } /* * Set the child Crunch state. */ static int ptrace_setcrunchregs(struct task_struct *tsk, void __user *ufp) { struct thread_info *thread = task_thread_info(tsk); crunch_task_release(thread); /* force a reload */ return copy_from_user(&thread->crunchstate, ufp, CRUNCH_SIZE) ? -EFAULT : 0; } #endif #ifdef CONFIG_HAVE_HW_BREAKPOINT /* * Convert a virtual register number into an index for a thread_info * breakpoint array. Breakpoints are identified using positive numbers * whilst watchpoints are negative. The registers are laid out as pairs * of (address, control), each pair mapping to a unique hw_breakpoint struct. * Register 0 is reserved for describing resource information. */ static int ptrace_hbp_num_to_idx(long num) { if (num < 0) num = (ARM_MAX_BRP << 1) - num; return (num - 1) >> 1; } /* * Returns the virtual register number for the address of the * breakpoint at index idx. */ static long ptrace_hbp_idx_to_num(int idx) { long mid = ARM_MAX_BRP << 1; long num = (idx << 1) + 1; return num > mid ? mid - num : num; } /* * Handle hitting a HW-breakpoint. */ static void ptrace_hbptriggered(struct perf_event *bp, struct perf_sample_data *data, struct pt_regs *regs) { struct arch_hw_breakpoint *bkpt = counter_arch_bp(bp); long num; int i; siginfo_t info; for (i = 0; i < ARM_MAX_HBP_SLOTS; ++i) if (current->thread.debug.hbp[i] == bp) break; num = (i == ARM_MAX_HBP_SLOTS) ? 0 : ptrace_hbp_idx_to_num(i); info.si_signo = SIGTRAP; info.si_errno = (int)num; info.si_code = TRAP_HWBKPT; info.si_addr = (void __user *)(bkpt->trigger); force_sig_info(SIGTRAP, &info, current); } /* * Set ptrace breakpoint pointers to zero for this task. * This is required in order to prevent child processes from unregistering * breakpoints held by their parent. */ void clear_ptrace_hw_breakpoint(struct task_struct *tsk) { memset(tsk->thread.debug.hbp, 0, sizeof(tsk->thread.debug.hbp)); } /* * Unregister breakpoints from this task and reset the pointers in * the thread_struct. */ void flush_ptrace_hw_breakpoint(struct task_struct *tsk) { int i; struct thread_struct *t = &tsk->thread; for (i = 0; i < ARM_MAX_HBP_SLOTS; i++) { if (t->debug.hbp[i]) { unregister_hw_breakpoint(t->debug.hbp[i]); t->debug.hbp[i] = NULL; } } } static u32 ptrace_get_hbp_resource_info(void) { u8 num_brps, num_wrps, debug_arch, wp_len; u32 reg = 0; num_brps = hw_breakpoint_slots(TYPE_INST); num_wrps = hw_breakpoint_slots(TYPE_DATA); debug_arch = arch_get_debug_arch(); wp_len = arch_get_max_wp_len(); reg |= debug_arch; reg <<= 8; reg |= wp_len; reg <<= 8; reg |= num_wrps; reg <<= 8; reg |= num_brps; return reg; } static struct perf_event *ptrace_hbp_create(struct task_struct *tsk, int type) { struct perf_event_attr attr; ptrace_breakpoint_init(&attr); /* Initialise fields to sane defaults. */ attr.bp_addr = 0; attr.bp_len = HW_BREAKPOINT_LEN_4; attr.bp_type = type; attr.disabled = 1; return register_user_hw_breakpoint(&attr, ptrace_hbptriggered, NULL, tsk); } static int ptrace_gethbpregs(struct task_struct *tsk, long num, unsigned long __user *data) { u32 reg; int idx, ret = 0; struct perf_event *bp; struct arch_hw_breakpoint_ctrl arch_ctrl; if (num == 0) { reg = ptrace_get_hbp_resource_info(); } else { idx = ptrace_hbp_num_to_idx(num); if (idx < 0 || idx >= ARM_MAX_HBP_SLOTS) { ret = -EINVAL; goto out; } bp = tsk->thread.debug.hbp[idx]; if (!bp) { reg = 0; goto put; } arch_ctrl = counter_arch_bp(bp)->ctrl; /* * Fix up the len because we may have adjusted it * to compensate for an unaligned address. */ while (!(arch_ctrl.len & 0x1)) arch_ctrl.len >>= 1; if (num & 0x1) reg = bp->attr.bp_addr; else reg = encode_ctrl_reg(arch_ctrl); } put: if (put_user(reg, data)) ret = -EFAULT; out: return ret; } static int ptrace_sethbpregs(struct task_struct *tsk, long num, unsigned long __user *data) { int idx, gen_len, gen_type, implied_type, ret = 0; u32 user_val; struct perf_event *bp; struct arch_hw_breakpoint_ctrl ctrl; struct perf_event_attr attr; if (num == 0) goto out; else if (num < 0) implied_type = HW_BREAKPOINT_RW; else implied_type = HW_BREAKPOINT_X; idx = ptrace_hbp_num_to_idx(num); if (idx < 0 || idx >= ARM_MAX_HBP_SLOTS) { ret = -EINVAL; goto out; } if (get_user(user_val, data)) { ret = -EFAULT; goto out; } bp = tsk->thread.debug.hbp[idx]; if (!bp) { bp = ptrace_hbp_create(tsk, implied_type); if (IS_ERR(bp)) { ret = PTR_ERR(bp); goto out; } tsk->thread.debug.hbp[idx] = bp; } attr = bp->attr; if (num & 0x1) { /* Address */ attr.bp_addr = user_val; } else { /* Control */ decode_ctrl_reg(user_val, &ctrl); ret = arch_bp_generic_fields(ctrl, &gen_len, &gen_type); if (ret) goto out; if ((gen_type & implied_type) != gen_type) { ret = -EINVAL; goto out; } attr.bp_len = gen_len; attr.bp_type = gen_type; attr.disabled = !ctrl.enabled; } ret = modify_user_hw_breakpoint(bp, &attr); out: return ret; } #endif /* regset get/set implementations */ static int gpr_get(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, void *kbuf, void __user *ubuf) { struct pt_regs *regs = task_pt_regs(target); return user_regset_copyout(&pos, &count, &kbuf, &ubuf, regs, 0, sizeof(*regs)); } static int gpr_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { int ret; struct pt_regs newregs; ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &newregs, 0, sizeof(newregs)); if (ret) return ret; if (!valid_user_regs(&newregs)) return -EINVAL; *task_pt_regs(target) = newregs; return 0; } static int fpa_get(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, void *kbuf, void __user *ubuf) { return user_regset_copyout(&pos, &count, &kbuf, &ubuf, &task_thread_info(target)->fpstate, 0, sizeof(struct user_fp)); } static int fpa_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { struct thread_info *thread = task_thread_info(target); thread->used_cp[1] = thread->used_cp[2] = 1; return user_regset_copyin(&pos, &count, &kbuf, &ubuf, &thread->fpstate, 0, sizeof(struct user_fp)); } #ifdef CONFIG_VFP /* * VFP register get/set implementations. * * With respect to the kernel, struct user_fp is divided into three chunks: * 16 or 32 real VFP registers (d0-d15 or d0-31) * These are transferred to/from the real registers in the task's * vfp_hard_struct. The number of registers depends on the kernel * configuration. * * 16 or 0 fake VFP registers (d16-d31 or empty) * i.e., the user_vfp structure has space for 32 registers even if * the kernel doesn't have them all. * * vfp_get() reads this chunk as zero where applicable * vfp_set() ignores this chunk * * 1 word for the FPSCR * * The bounds-checking logic built into user_regset_copyout and friends * means that we can make a simple sequence of calls to map the relevant data * to/from the specified slice of the user regset structure. */ static int vfp_get(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, void *kbuf, void __user *ubuf) { int ret; struct thread_info *thread = task_thread_info(target); struct vfp_hard_struct const *vfp = &thread->vfpstate.hard; const size_t user_fpregs_offset = offsetof(struct user_vfp, fpregs); const size_t user_fpscr_offset = offsetof(struct user_vfp, fpscr); vfp_sync_hwstate(thread); ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf, &vfp->fpregs, user_fpregs_offset, user_fpregs_offset + sizeof(vfp->fpregs)); if (ret) return ret; ret = user_regset_copyout_zero(&pos, &count, &kbuf, &ubuf, user_fpregs_offset + sizeof(vfp->fpregs), user_fpscr_offset); if (ret) return ret; return user_regset_copyout(&pos, &count, &kbuf, &ubuf, &vfp->fpscr, user_fpscr_offset, user_fpscr_offset + sizeof(vfp->fpscr)); } /* * For vfp_set() a read-modify-write is done on the VFP registers, * in order to avoid writing back a half-modified set of registers on * failure. */ static int vfp_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { int ret; struct thread_info *thread = task_thread_info(target); struct vfp_hard_struct new_vfp; const size_t user_fpregs_offset = offsetof(struct user_vfp, fpregs); const size_t user_fpscr_offset = offsetof(struct user_vfp, fpscr); vfp_sync_hwstate(thread); new_vfp = thread->vfpstate.hard; ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &new_vfp.fpregs, user_fpregs_offset, user_fpregs_offset + sizeof(new_vfp.fpregs)); if (ret) return ret; ret = user_regset_copyin_ignore(&pos, &count, &kbuf, &ubuf, user_fpregs_offset + sizeof(new_vfp.fpregs), user_fpscr_offset); if (ret) return ret; ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &new_vfp.fpscr, user_fpscr_offset, user_fpscr_offset + sizeof(new_vfp.fpscr)); if (ret) return ret; vfp_flush_hwstate(thread); thread->vfpstate.hard = new_vfp; return 0; } #endif /* CONFIG_VFP */ enum arm_regset { REGSET_GPR, REGSET_FPR, #ifdef CONFIG_VFP REGSET_VFP, #endif }; static const struct user_regset arm_regsets[] = { [REGSET_GPR] = { .core_note_type = NT_PRSTATUS, .n = ELF_NGREG, .size = sizeof(u32), .align = sizeof(u32), .get = gpr_get, .set = gpr_set }, [REGSET_FPR] = { /* * For the FPA regs in fpstate, the real fields are a mixture * of sizes, so pretend that the registers are word-sized: */ .core_note_type = NT_PRFPREG, .n = sizeof(struct user_fp) / sizeof(u32), .size = sizeof(u32), .align = sizeof(u32), .get = fpa_get, .set = fpa_set }, #ifdef CONFIG_VFP [REGSET_VFP] = { /* * Pretend that the VFP regs are word-sized, since the FPSCR is * a single word dangling at the end of struct user_vfp: */ .core_note_type = NT_ARM_VFP, .n = ARM_VFPREGS_SIZE / sizeof(u32), .size = sizeof(u32), .align = sizeof(u32), .get = vfp_get, .set = vfp_set }, #endif /* CONFIG_VFP */ }; static const struct user_regset_view user_arm_view = { .name = "arm", .e_machine = ELF_ARCH, .ei_osabi = ELF_OSABI, .regsets = arm_regsets, .n = ARRAY_SIZE(arm_regsets) }; const struct user_regset_view *task_user_regset_view(struct task_struct *task) { return &user_arm_view; } long arch_ptrace(struct task_struct *child, long request, unsigned long addr, unsigned long data) { int ret; unsigned long __user *datap = (unsigned long __user *) data; switch (request) { case PTRACE_PEEKUSR: ret = ptrace_read_user(child, addr, datap); break; case PTRACE_POKEUSR: ret = ptrace_write_user(child, addr, data); break; case PTRACE_GETREGS: ret = copy_regset_to_user(child, &user_arm_view, REGSET_GPR, 0, sizeof(struct pt_regs), datap); break; case PTRACE_SETREGS: ret = copy_regset_from_user(child, &user_arm_view, REGSET_GPR, 0, sizeof(struct pt_regs), datap); break; case PTRACE_GETFPREGS: ret = copy_regset_to_user(child, &user_arm_view, REGSET_FPR, 0, sizeof(union fp_state), datap); break; case PTRACE_SETFPREGS: ret = copy_regset_from_user(child, &user_arm_view, REGSET_FPR, 0, sizeof(union fp_state), datap); break; #ifdef CONFIG_IWMMXT case PTRACE_GETWMMXREGS: ret = ptrace_getwmmxregs(child, datap); break; case PTRACE_SETWMMXREGS: ret = ptrace_setwmmxregs(child, datap); break; #endif case PTRACE_GET_THREAD_AREA: ret = put_user(task_thread_info(child)->tp_value[0], datap); break; case PTRACE_SET_SYSCALL: task_thread_info(child)->syscall = data; ret = 0; break; #ifdef CONFIG_CRUNCH case PTRACE_GETCRUNCHREGS: ret = ptrace_getcrunchregs(child, datap); break; case PTRACE_SETCRUNCHREGS: ret = ptrace_setcrunchregs(child, datap); break; #endif #ifdef CONFIG_VFP case PTRACE_GETVFPREGS: ret = copy_regset_to_user(child, &user_arm_view, REGSET_VFP, 0, ARM_VFPREGS_SIZE, datap); break; case PTRACE_SETVFPREGS: ret = copy_regset_from_user(child, &user_arm_view, REGSET_VFP, 0, ARM_VFPREGS_SIZE, datap); break; #endif #ifdef CONFIG_HAVE_HW_BREAKPOINT case PTRACE_GETHBPREGS: if (ptrace_get_breakpoints(child) < 0) return -ESRCH; ret = ptrace_gethbpregs(child, addr, (unsigned long __user *)data); ptrace_put_breakpoints(child); break; case PTRACE_SETHBPREGS: if (ptrace_get_breakpoints(child) < 0) return -ESRCH; ret = ptrace_sethbpregs(child, addr, (unsigned long __user *)data); ptrace_put_breakpoints(child); break; #endif default: ret = ptrace_request(child, request, addr, data); break; } return ret; } enum ptrace_syscall_dir { PTRACE_SYSCALL_ENTER = 0, PTRACE_SYSCALL_EXIT, }; static int tracehook_report_syscall(struct pt_regs *regs, enum ptrace_syscall_dir dir) { unsigned long ip; /* * IP is used to denote syscall entry/exit: * IP = 0 -> entry, =1 -> exit */ ip = regs->ARM_ip; regs->ARM_ip = dir; if (dir == PTRACE_SYSCALL_EXIT) tracehook_report_syscall_exit(regs, 0); else if (tracehook_report_syscall_entry(regs)) current_thread_info()->syscall = -1; regs->ARM_ip = ip; return current_thread_info()->syscall; } asmlinkage int syscall_trace_enter(struct pt_regs *regs, int scno) { current_thread_info()->syscall = scno; /* Do the secure computing check first; failures should be fast. */ if (secure_computing(scno) == -1) return -1; if (test_thread_flag(TIF_SYSCALL_TRACE)) scno = tracehook_report_syscall(regs, PTRACE_SYSCALL_ENTER); if (test_thread_flag(TIF_SYSCALL_TRACEPOINT)) trace_sys_enter(regs, scno); audit_syscall_entry(AUDIT_ARCH_ARM, scno, regs->ARM_r0, regs->ARM_r1, regs->ARM_r2, regs->ARM_r3); return scno; } asmlinkage void syscall_trace_exit(struct pt_regs *regs) { /* * Audit the syscall before anything else, as a debugger may * come in and change the current registers. */ audit_syscall_exit(regs); /* * Note that we haven't updated the ->syscall field for the * current thread. This isn't a problem because it will have * been set on syscall entry and there hasn't been an opportunity * for a PTRACE_SET_SYSCALL since then. */ if (test_thread_flag(TIF_SYSCALL_TRACEPOINT)) trace_sys_exit(regs, regs_return_value(regs)); if (test_thread_flag(TIF_SYSCALL_TRACE)) tracehook_report_syscall(regs, PTRACE_SYSCALL_EXIT); }
./CrossVul/dataset_final_sorted/CWE-264/c/good_2423_4
crossvul-cpp_data_bad_2244_0
/* * linux/fs/namespace.c * * (C) Copyright Al Viro 2000, 2001 * Released under GPL v2. * * Based on code from fs/super.c, copyright Linus Torvalds and others. * Heavily rewritten. */ #include <linux/syscalls.h> #include <linux/export.h> #include <linux/capability.h> #include <linux/mnt_namespace.h> #include <linux/user_namespace.h> #include <linux/namei.h> #include <linux/security.h> #include <linux/idr.h> #include <linux/acct.h> /* acct_auto_close_mnt */ #include <linux/init.h> /* init_rootfs */ #include <linux/fs_struct.h> /* get_fs_root et.al. */ #include <linux/fsnotify.h> /* fsnotify_vfsmount_delete */ #include <linux/uaccess.h> #include <linux/proc_ns.h> #include <linux/magic.h> #include <linux/bootmem.h> #include "pnode.h" #include "internal.h" static unsigned int m_hash_mask __read_mostly; static unsigned int m_hash_shift __read_mostly; static unsigned int mp_hash_mask __read_mostly; static unsigned int mp_hash_shift __read_mostly; static __initdata unsigned long mhash_entries; static int __init set_mhash_entries(char *str) { if (!str) return 0; mhash_entries = simple_strtoul(str, &str, 0); return 1; } __setup("mhash_entries=", set_mhash_entries); static __initdata unsigned long mphash_entries; static int __init set_mphash_entries(char *str) { if (!str) return 0; mphash_entries = simple_strtoul(str, &str, 0); return 1; } __setup("mphash_entries=", set_mphash_entries); static u64 event; static DEFINE_IDA(mnt_id_ida); static DEFINE_IDA(mnt_group_ida); static DEFINE_SPINLOCK(mnt_id_lock); static int mnt_id_start = 0; static int mnt_group_start = 1; static struct hlist_head *mount_hashtable __read_mostly; static struct hlist_head *mountpoint_hashtable __read_mostly; static struct kmem_cache *mnt_cache __read_mostly; static DECLARE_RWSEM(namespace_sem); /* /sys/fs */ struct kobject *fs_kobj; EXPORT_SYMBOL_GPL(fs_kobj); /* * vfsmount lock may be taken for read to prevent changes to the * vfsmount hash, ie. during mountpoint lookups or walking back * up the tree. * * It should be taken for write in all cases where the vfsmount * tree or hash is modified or when a vfsmount structure is modified. */ __cacheline_aligned_in_smp DEFINE_SEQLOCK(mount_lock); static inline struct hlist_head *m_hash(struct vfsmount *mnt, struct dentry *dentry) { unsigned long tmp = ((unsigned long)mnt / L1_CACHE_BYTES); tmp += ((unsigned long)dentry / L1_CACHE_BYTES); tmp = tmp + (tmp >> m_hash_shift); return &mount_hashtable[tmp & m_hash_mask]; } static inline struct hlist_head *mp_hash(struct dentry *dentry) { unsigned long tmp = ((unsigned long)dentry / L1_CACHE_BYTES); tmp = tmp + (tmp >> mp_hash_shift); return &mountpoint_hashtable[tmp & mp_hash_mask]; } /* * allocation is serialized by namespace_sem, but we need the spinlock to * serialize with freeing. */ static int mnt_alloc_id(struct mount *mnt) { int res; retry: ida_pre_get(&mnt_id_ida, GFP_KERNEL); spin_lock(&mnt_id_lock); res = ida_get_new_above(&mnt_id_ida, mnt_id_start, &mnt->mnt_id); if (!res) mnt_id_start = mnt->mnt_id + 1; spin_unlock(&mnt_id_lock); if (res == -EAGAIN) goto retry; return res; } static void mnt_free_id(struct mount *mnt) { int id = mnt->mnt_id; spin_lock(&mnt_id_lock); ida_remove(&mnt_id_ida, id); if (mnt_id_start > id) mnt_id_start = id; spin_unlock(&mnt_id_lock); } /* * Allocate a new peer group ID * * mnt_group_ida is protected by namespace_sem */ static int mnt_alloc_group_id(struct mount *mnt) { int res; if (!ida_pre_get(&mnt_group_ida, GFP_KERNEL)) return -ENOMEM; res = ida_get_new_above(&mnt_group_ida, mnt_group_start, &mnt->mnt_group_id); if (!res) mnt_group_start = mnt->mnt_group_id + 1; return res; } /* * Release a peer group ID */ void mnt_release_group_id(struct mount *mnt) { int id = mnt->mnt_group_id; ida_remove(&mnt_group_ida, id); if (mnt_group_start > id) mnt_group_start = id; mnt->mnt_group_id = 0; } /* * vfsmount lock must be held for read */ static inline void mnt_add_count(struct mount *mnt, int n) { #ifdef CONFIG_SMP this_cpu_add(mnt->mnt_pcp->mnt_count, n); #else preempt_disable(); mnt->mnt_count += n; preempt_enable(); #endif } /* * vfsmount lock must be held for write */ unsigned int mnt_get_count(struct mount *mnt) { #ifdef CONFIG_SMP unsigned int count = 0; int cpu; for_each_possible_cpu(cpu) { count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_count; } return count; #else return mnt->mnt_count; #endif } static struct mount *alloc_vfsmnt(const char *name) { struct mount *mnt = kmem_cache_zalloc(mnt_cache, GFP_KERNEL); if (mnt) { int err; err = mnt_alloc_id(mnt); if (err) goto out_free_cache; if (name) { mnt->mnt_devname = kstrdup(name, GFP_KERNEL); if (!mnt->mnt_devname) goto out_free_id; } #ifdef CONFIG_SMP mnt->mnt_pcp = alloc_percpu(struct mnt_pcp); if (!mnt->mnt_pcp) goto out_free_devname; this_cpu_add(mnt->mnt_pcp->mnt_count, 1); #else mnt->mnt_count = 1; mnt->mnt_writers = 0; #endif INIT_HLIST_NODE(&mnt->mnt_hash); INIT_LIST_HEAD(&mnt->mnt_child); INIT_LIST_HEAD(&mnt->mnt_mounts); INIT_LIST_HEAD(&mnt->mnt_list); INIT_LIST_HEAD(&mnt->mnt_expire); INIT_LIST_HEAD(&mnt->mnt_share); INIT_LIST_HEAD(&mnt->mnt_slave_list); INIT_LIST_HEAD(&mnt->mnt_slave); #ifdef CONFIG_FSNOTIFY INIT_HLIST_HEAD(&mnt->mnt_fsnotify_marks); #endif } return mnt; #ifdef CONFIG_SMP out_free_devname: kfree(mnt->mnt_devname); #endif out_free_id: mnt_free_id(mnt); out_free_cache: kmem_cache_free(mnt_cache, mnt); return NULL; } /* * Most r/o checks on a fs are for operations that take * discrete amounts of time, like a write() or unlink(). * We must keep track of when those operations start * (for permission checks) and when they end, so that * we can determine when writes are able to occur to * a filesystem. */ /* * __mnt_is_readonly: check whether a mount is read-only * @mnt: the mount to check for its write status * * This shouldn't be used directly ouside of the VFS. * It does not guarantee that the filesystem will stay * r/w, just that it is right *now*. This can not and * should not be used in place of IS_RDONLY(inode). * mnt_want/drop_write() will _keep_ the filesystem * r/w. */ int __mnt_is_readonly(struct vfsmount *mnt) { if (mnt->mnt_flags & MNT_READONLY) return 1; if (mnt->mnt_sb->s_flags & MS_RDONLY) return 1; return 0; } EXPORT_SYMBOL_GPL(__mnt_is_readonly); static inline void mnt_inc_writers(struct mount *mnt) { #ifdef CONFIG_SMP this_cpu_inc(mnt->mnt_pcp->mnt_writers); #else mnt->mnt_writers++; #endif } static inline void mnt_dec_writers(struct mount *mnt) { #ifdef CONFIG_SMP this_cpu_dec(mnt->mnt_pcp->mnt_writers); #else mnt->mnt_writers--; #endif } static unsigned int mnt_get_writers(struct mount *mnt) { #ifdef CONFIG_SMP unsigned int count = 0; int cpu; for_each_possible_cpu(cpu) { count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_writers; } return count; #else return mnt->mnt_writers; #endif } static int mnt_is_readonly(struct vfsmount *mnt) { if (mnt->mnt_sb->s_readonly_remount) return 1; /* Order wrt setting s_flags/s_readonly_remount in do_remount() */ smp_rmb(); return __mnt_is_readonly(mnt); } /* * Most r/o & frozen checks on a fs are for operations that take discrete * amounts of time, like a write() or unlink(). We must keep track of when * those operations start (for permission checks) and when they end, so that we * can determine when writes are able to occur to a filesystem. */ /** * __mnt_want_write - get write access to a mount without freeze protection * @m: the mount on which to take a write * * This tells the low-level filesystem that a write is about to be performed to * it, and makes sure that writes are allowed (mnt it read-write) before * returning success. This operation does not protect against filesystem being * frozen. When the write operation is finished, __mnt_drop_write() must be * called. This is effectively a refcount. */ int __mnt_want_write(struct vfsmount *m) { struct mount *mnt = real_mount(m); int ret = 0; preempt_disable(); mnt_inc_writers(mnt); /* * The store to mnt_inc_writers must be visible before we pass * MNT_WRITE_HOLD loop below, so that the slowpath can see our * incremented count after it has set MNT_WRITE_HOLD. */ smp_mb(); while (ACCESS_ONCE(mnt->mnt.mnt_flags) & MNT_WRITE_HOLD) cpu_relax(); /* * After the slowpath clears MNT_WRITE_HOLD, mnt_is_readonly will * be set to match its requirements. So we must not load that until * MNT_WRITE_HOLD is cleared. */ smp_rmb(); if (mnt_is_readonly(m)) { mnt_dec_writers(mnt); ret = -EROFS; } preempt_enable(); return ret; } /** * mnt_want_write - get write access to a mount * @m: the mount on which to take a write * * This tells the low-level filesystem that a write is about to be performed to * it, and makes sure that writes are allowed (mount is read-write, filesystem * is not frozen) before returning success. When the write operation is * finished, mnt_drop_write() must be called. This is effectively a refcount. */ int mnt_want_write(struct vfsmount *m) { int ret; sb_start_write(m->mnt_sb); ret = __mnt_want_write(m); if (ret) sb_end_write(m->mnt_sb); return ret; } EXPORT_SYMBOL_GPL(mnt_want_write); /** * mnt_clone_write - get write access to a mount * @mnt: the mount on which to take a write * * This is effectively like mnt_want_write, except * it must only be used to take an extra write reference * on a mountpoint that we already know has a write reference * on it. This allows some optimisation. * * After finished, mnt_drop_write must be called as usual to * drop the reference. */ int mnt_clone_write(struct vfsmount *mnt) { /* superblock may be r/o */ if (__mnt_is_readonly(mnt)) return -EROFS; preempt_disable(); mnt_inc_writers(real_mount(mnt)); preempt_enable(); return 0; } EXPORT_SYMBOL_GPL(mnt_clone_write); /** * __mnt_want_write_file - get write access to a file's mount * @file: the file who's mount on which to take a write * * This is like __mnt_want_write, but it takes a file and can * do some optimisations if the file is open for write already */ int __mnt_want_write_file(struct file *file) { if (!(file->f_mode & FMODE_WRITER)) return __mnt_want_write(file->f_path.mnt); else return mnt_clone_write(file->f_path.mnt); } /** * mnt_want_write_file - get write access to a file's mount * @file: the file who's mount on which to take a write * * This is like mnt_want_write, but it takes a file and can * do some optimisations if the file is open for write already */ int mnt_want_write_file(struct file *file) { int ret; sb_start_write(file->f_path.mnt->mnt_sb); ret = __mnt_want_write_file(file); if (ret) sb_end_write(file->f_path.mnt->mnt_sb); return ret; } EXPORT_SYMBOL_GPL(mnt_want_write_file); /** * __mnt_drop_write - give up write access to a mount * @mnt: the mount on which to give up write access * * Tells the low-level filesystem that we are done * performing writes to it. Must be matched with * __mnt_want_write() call above. */ void __mnt_drop_write(struct vfsmount *mnt) { preempt_disable(); mnt_dec_writers(real_mount(mnt)); preempt_enable(); } /** * mnt_drop_write - give up write access to a mount * @mnt: the mount on which to give up write access * * Tells the low-level filesystem that we are done performing writes to it and * also allows filesystem to be frozen again. Must be matched with * mnt_want_write() call above. */ void mnt_drop_write(struct vfsmount *mnt) { __mnt_drop_write(mnt); sb_end_write(mnt->mnt_sb); } EXPORT_SYMBOL_GPL(mnt_drop_write); void __mnt_drop_write_file(struct file *file) { __mnt_drop_write(file->f_path.mnt); } void mnt_drop_write_file(struct file *file) { mnt_drop_write(file->f_path.mnt); } EXPORT_SYMBOL(mnt_drop_write_file); static int mnt_make_readonly(struct mount *mnt) { int ret = 0; lock_mount_hash(); mnt->mnt.mnt_flags |= MNT_WRITE_HOLD; /* * After storing MNT_WRITE_HOLD, we'll read the counters. This store * should be visible before we do. */ smp_mb(); /* * With writers on hold, if this value is zero, then there are * definitely no active writers (although held writers may subsequently * increment the count, they'll have to wait, and decrement it after * seeing MNT_READONLY). * * It is OK to have counter incremented on one CPU and decremented on * another: the sum will add up correctly. The danger would be when we * sum up each counter, if we read a counter before it is incremented, * but then read another CPU's count which it has been subsequently * decremented from -- we would see more decrements than we should. * MNT_WRITE_HOLD protects against this scenario, because * mnt_want_write first increments count, then smp_mb, then spins on * MNT_WRITE_HOLD, so it can't be decremented by another CPU while * we're counting up here. */ if (mnt_get_writers(mnt) > 0) ret = -EBUSY; else mnt->mnt.mnt_flags |= MNT_READONLY; /* * MNT_READONLY must become visible before ~MNT_WRITE_HOLD, so writers * that become unheld will see MNT_READONLY. */ smp_wmb(); mnt->mnt.mnt_flags &= ~MNT_WRITE_HOLD; unlock_mount_hash(); return ret; } static void __mnt_unmake_readonly(struct mount *mnt) { lock_mount_hash(); mnt->mnt.mnt_flags &= ~MNT_READONLY; unlock_mount_hash(); } int sb_prepare_remount_readonly(struct super_block *sb) { struct mount *mnt; int err = 0; /* Racy optimization. Recheck the counter under MNT_WRITE_HOLD */ if (atomic_long_read(&sb->s_remove_count)) return -EBUSY; lock_mount_hash(); list_for_each_entry(mnt, &sb->s_mounts, mnt_instance) { if (!(mnt->mnt.mnt_flags & MNT_READONLY)) { mnt->mnt.mnt_flags |= MNT_WRITE_HOLD; smp_mb(); if (mnt_get_writers(mnt) > 0) { err = -EBUSY; break; } } } if (!err && atomic_long_read(&sb->s_remove_count)) err = -EBUSY; if (!err) { sb->s_readonly_remount = 1; smp_wmb(); } list_for_each_entry(mnt, &sb->s_mounts, mnt_instance) { if (mnt->mnt.mnt_flags & MNT_WRITE_HOLD) mnt->mnt.mnt_flags &= ~MNT_WRITE_HOLD; } unlock_mount_hash(); return err; } static void free_vfsmnt(struct mount *mnt) { kfree(mnt->mnt_devname); #ifdef CONFIG_SMP free_percpu(mnt->mnt_pcp); #endif kmem_cache_free(mnt_cache, mnt); } static void delayed_free_vfsmnt(struct rcu_head *head) { free_vfsmnt(container_of(head, struct mount, mnt_rcu)); } /* call under rcu_read_lock */ bool legitimize_mnt(struct vfsmount *bastard, unsigned seq) { struct mount *mnt; if (read_seqretry(&mount_lock, seq)) return false; if (bastard == NULL) return true; mnt = real_mount(bastard); mnt_add_count(mnt, 1); if (likely(!read_seqretry(&mount_lock, seq))) return true; if (bastard->mnt_flags & MNT_SYNC_UMOUNT) { mnt_add_count(mnt, -1); return false; } rcu_read_unlock(); mntput(bastard); rcu_read_lock(); return false; } /* * find the first mount at @dentry on vfsmount @mnt. * call under rcu_read_lock() */ struct mount *__lookup_mnt(struct vfsmount *mnt, struct dentry *dentry) { struct hlist_head *head = m_hash(mnt, dentry); struct mount *p; hlist_for_each_entry_rcu(p, head, mnt_hash) if (&p->mnt_parent->mnt == mnt && p->mnt_mountpoint == dentry) return p; return NULL; } /* * find the last mount at @dentry on vfsmount @mnt. * mount_lock must be held. */ struct mount *__lookup_mnt_last(struct vfsmount *mnt, struct dentry *dentry) { struct mount *p, *res; res = p = __lookup_mnt(mnt, dentry); if (!p) goto out; hlist_for_each_entry_continue(p, mnt_hash) { if (&p->mnt_parent->mnt != mnt || p->mnt_mountpoint != dentry) break; res = p; } out: return res; } /* * lookup_mnt - Return the first child mount mounted at path * * "First" means first mounted chronologically. If you create the * following mounts: * * mount /dev/sda1 /mnt * mount /dev/sda2 /mnt * mount /dev/sda3 /mnt * * Then lookup_mnt() on the base /mnt dentry in the root mount will * return successively the root dentry and vfsmount of /dev/sda1, then * /dev/sda2, then /dev/sda3, then NULL. * * lookup_mnt takes a reference to the found vfsmount. */ struct vfsmount *lookup_mnt(struct path *path) { struct mount *child_mnt; struct vfsmount *m; unsigned seq; rcu_read_lock(); do { seq = read_seqbegin(&mount_lock); child_mnt = __lookup_mnt(path->mnt, path->dentry); m = child_mnt ? &child_mnt->mnt : NULL; } while (!legitimize_mnt(m, seq)); rcu_read_unlock(); return m; } static struct mountpoint *new_mountpoint(struct dentry *dentry) { struct hlist_head *chain = mp_hash(dentry); struct mountpoint *mp; int ret; hlist_for_each_entry(mp, chain, m_hash) { if (mp->m_dentry == dentry) { /* might be worth a WARN_ON() */ if (d_unlinked(dentry)) return ERR_PTR(-ENOENT); mp->m_count++; return mp; } } mp = kmalloc(sizeof(struct mountpoint), GFP_KERNEL); if (!mp) return ERR_PTR(-ENOMEM); ret = d_set_mounted(dentry); if (ret) { kfree(mp); return ERR_PTR(ret); } mp->m_dentry = dentry; mp->m_count = 1; hlist_add_head(&mp->m_hash, chain); return mp; } static void put_mountpoint(struct mountpoint *mp) { if (!--mp->m_count) { struct dentry *dentry = mp->m_dentry; spin_lock(&dentry->d_lock); dentry->d_flags &= ~DCACHE_MOUNTED; spin_unlock(&dentry->d_lock); hlist_del(&mp->m_hash); kfree(mp); } } static inline int check_mnt(struct mount *mnt) { return mnt->mnt_ns == current->nsproxy->mnt_ns; } /* * vfsmount lock must be held for write */ static void touch_mnt_namespace(struct mnt_namespace *ns) { if (ns) { ns->event = ++event; wake_up_interruptible(&ns->poll); } } /* * vfsmount lock must be held for write */ static void __touch_mnt_namespace(struct mnt_namespace *ns) { if (ns && ns->event != event) { ns->event = event; wake_up_interruptible(&ns->poll); } } /* * vfsmount lock must be held for write */ static void detach_mnt(struct mount *mnt, struct path *old_path) { old_path->dentry = mnt->mnt_mountpoint; old_path->mnt = &mnt->mnt_parent->mnt; mnt->mnt_parent = mnt; mnt->mnt_mountpoint = mnt->mnt.mnt_root; list_del_init(&mnt->mnt_child); hlist_del_init_rcu(&mnt->mnt_hash); put_mountpoint(mnt->mnt_mp); mnt->mnt_mp = NULL; } /* * vfsmount lock must be held for write */ void mnt_set_mountpoint(struct mount *mnt, struct mountpoint *mp, struct mount *child_mnt) { mp->m_count++; mnt_add_count(mnt, 1); /* essentially, that's mntget */ child_mnt->mnt_mountpoint = dget(mp->m_dentry); child_mnt->mnt_parent = mnt; child_mnt->mnt_mp = mp; } /* * vfsmount lock must be held for write */ static void attach_mnt(struct mount *mnt, struct mount *parent, struct mountpoint *mp) { mnt_set_mountpoint(parent, mp, mnt); hlist_add_head_rcu(&mnt->mnt_hash, m_hash(&parent->mnt, mp->m_dentry)); list_add_tail(&mnt->mnt_child, &parent->mnt_mounts); } /* * vfsmount lock must be held for write */ static void commit_tree(struct mount *mnt, struct mount *shadows) { struct mount *parent = mnt->mnt_parent; struct mount *m; LIST_HEAD(head); struct mnt_namespace *n = parent->mnt_ns; BUG_ON(parent == mnt); list_add_tail(&head, &mnt->mnt_list); list_for_each_entry(m, &head, mnt_list) m->mnt_ns = n; list_splice(&head, n->list.prev); if (shadows) hlist_add_after_rcu(&shadows->mnt_hash, &mnt->mnt_hash); else hlist_add_head_rcu(&mnt->mnt_hash, m_hash(&parent->mnt, mnt->mnt_mountpoint)); list_add_tail(&mnt->mnt_child, &parent->mnt_mounts); touch_mnt_namespace(n); } static struct mount *next_mnt(struct mount *p, struct mount *root) { struct list_head *next = p->mnt_mounts.next; if (next == &p->mnt_mounts) { while (1) { if (p == root) return NULL; next = p->mnt_child.next; if (next != &p->mnt_parent->mnt_mounts) break; p = p->mnt_parent; } } return list_entry(next, struct mount, mnt_child); } static struct mount *skip_mnt_tree(struct mount *p) { struct list_head *prev = p->mnt_mounts.prev; while (prev != &p->mnt_mounts) { p = list_entry(prev, struct mount, mnt_child); prev = p->mnt_mounts.prev; } return p; } struct vfsmount * vfs_kern_mount(struct file_system_type *type, int flags, const char *name, void *data) { struct mount *mnt; struct dentry *root; if (!type) return ERR_PTR(-ENODEV); mnt = alloc_vfsmnt(name); if (!mnt) return ERR_PTR(-ENOMEM); if (flags & MS_KERNMOUNT) mnt->mnt.mnt_flags = MNT_INTERNAL; root = mount_fs(type, flags, name, data); if (IS_ERR(root)) { mnt_free_id(mnt); free_vfsmnt(mnt); return ERR_CAST(root); } mnt->mnt.mnt_root = root; mnt->mnt.mnt_sb = root->d_sb; mnt->mnt_mountpoint = mnt->mnt.mnt_root; mnt->mnt_parent = mnt; lock_mount_hash(); list_add_tail(&mnt->mnt_instance, &root->d_sb->s_mounts); unlock_mount_hash(); return &mnt->mnt; } EXPORT_SYMBOL_GPL(vfs_kern_mount); static struct mount *clone_mnt(struct mount *old, struct dentry *root, int flag) { struct super_block *sb = old->mnt.mnt_sb; struct mount *mnt; int err; mnt = alloc_vfsmnt(old->mnt_devname); if (!mnt) return ERR_PTR(-ENOMEM); if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE)) mnt->mnt_group_id = 0; /* not a peer of original */ else mnt->mnt_group_id = old->mnt_group_id; if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) { err = mnt_alloc_group_id(mnt); if (err) goto out_free; } mnt->mnt.mnt_flags = old->mnt.mnt_flags & ~(MNT_WRITE_HOLD|MNT_MARKED); /* Don't allow unprivileged users to change mount flags */ if ((flag & CL_UNPRIVILEGED) && (mnt->mnt.mnt_flags & MNT_READONLY)) mnt->mnt.mnt_flags |= MNT_LOCK_READONLY; /* Don't allow unprivileged users to reveal what is under a mount */ if ((flag & CL_UNPRIVILEGED) && list_empty(&old->mnt_expire)) mnt->mnt.mnt_flags |= MNT_LOCKED; atomic_inc(&sb->s_active); mnt->mnt.mnt_sb = sb; mnt->mnt.mnt_root = dget(root); mnt->mnt_mountpoint = mnt->mnt.mnt_root; mnt->mnt_parent = mnt; lock_mount_hash(); list_add_tail(&mnt->mnt_instance, &sb->s_mounts); unlock_mount_hash(); if ((flag & CL_SLAVE) || ((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) { list_add(&mnt->mnt_slave, &old->mnt_slave_list); mnt->mnt_master = old; CLEAR_MNT_SHARED(mnt); } else if (!(flag & CL_PRIVATE)) { if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old)) list_add(&mnt->mnt_share, &old->mnt_share); if (IS_MNT_SLAVE(old)) list_add(&mnt->mnt_slave, &old->mnt_slave); mnt->mnt_master = old->mnt_master; } if (flag & CL_MAKE_SHARED) set_mnt_shared(mnt); /* stick the duplicate mount on the same expiry list * as the original if that was on one */ if (flag & CL_EXPIRE) { if (!list_empty(&old->mnt_expire)) list_add(&mnt->mnt_expire, &old->mnt_expire); } return mnt; out_free: mnt_free_id(mnt); free_vfsmnt(mnt); return ERR_PTR(err); } static void mntput_no_expire(struct mount *mnt) { put_again: rcu_read_lock(); mnt_add_count(mnt, -1); if (likely(mnt->mnt_ns)) { /* shouldn't be the last one */ rcu_read_unlock(); return; } lock_mount_hash(); if (mnt_get_count(mnt)) { rcu_read_unlock(); unlock_mount_hash(); return; } if (unlikely(mnt->mnt_pinned)) { mnt_add_count(mnt, mnt->mnt_pinned + 1); mnt->mnt_pinned = 0; rcu_read_unlock(); unlock_mount_hash(); acct_auto_close_mnt(&mnt->mnt); goto put_again; } if (unlikely(mnt->mnt.mnt_flags & MNT_DOOMED)) { rcu_read_unlock(); unlock_mount_hash(); return; } mnt->mnt.mnt_flags |= MNT_DOOMED; rcu_read_unlock(); list_del(&mnt->mnt_instance); unlock_mount_hash(); /* * This probably indicates that somebody messed * up a mnt_want/drop_write() pair. If this * happens, the filesystem was probably unable * to make r/w->r/o transitions. */ /* * The locking used to deal with mnt_count decrement provides barriers, * so mnt_get_writers() below is safe. */ WARN_ON(mnt_get_writers(mnt)); fsnotify_vfsmount_delete(&mnt->mnt); dput(mnt->mnt.mnt_root); deactivate_super(mnt->mnt.mnt_sb); mnt_free_id(mnt); call_rcu(&mnt->mnt_rcu, delayed_free_vfsmnt); } void mntput(struct vfsmount *mnt) { if (mnt) { struct mount *m = real_mount(mnt); /* avoid cacheline pingpong, hope gcc doesn't get "smart" */ if (unlikely(m->mnt_expiry_mark)) m->mnt_expiry_mark = 0; mntput_no_expire(m); } } EXPORT_SYMBOL(mntput); struct vfsmount *mntget(struct vfsmount *mnt) { if (mnt) mnt_add_count(real_mount(mnt), 1); return mnt; } EXPORT_SYMBOL(mntget); void mnt_pin(struct vfsmount *mnt) { lock_mount_hash(); real_mount(mnt)->mnt_pinned++; unlock_mount_hash(); } EXPORT_SYMBOL(mnt_pin); void mnt_unpin(struct vfsmount *m) { struct mount *mnt = real_mount(m); lock_mount_hash(); if (mnt->mnt_pinned) { mnt_add_count(mnt, 1); mnt->mnt_pinned--; } unlock_mount_hash(); } EXPORT_SYMBOL(mnt_unpin); static inline void mangle(struct seq_file *m, const char *s) { seq_escape(m, s, " \t\n\\"); } /* * Simple .show_options callback for filesystems which don't want to * implement more complex mount option showing. * * See also save_mount_options(). */ int generic_show_options(struct seq_file *m, struct dentry *root) { const char *options; rcu_read_lock(); options = rcu_dereference(root->d_sb->s_options); if (options != NULL && options[0]) { seq_putc(m, ','); mangle(m, options); } rcu_read_unlock(); return 0; } EXPORT_SYMBOL(generic_show_options); /* * If filesystem uses generic_show_options(), this function should be * called from the fill_super() callback. * * The .remount_fs callback usually needs to be handled in a special * way, to make sure, that previous options are not overwritten if the * remount fails. * * Also note, that if the filesystem's .remount_fs function doesn't * reset all options to their default value, but changes only newly * given options, then the displayed options will not reflect reality * any more. */ void save_mount_options(struct super_block *sb, char *options) { BUG_ON(sb->s_options); rcu_assign_pointer(sb->s_options, kstrdup(options, GFP_KERNEL)); } EXPORT_SYMBOL(save_mount_options); void replace_mount_options(struct super_block *sb, char *options) { char *old = sb->s_options; rcu_assign_pointer(sb->s_options, options); if (old) { synchronize_rcu(); kfree(old); } } EXPORT_SYMBOL(replace_mount_options); #ifdef CONFIG_PROC_FS /* iterator; we want it to have access to namespace_sem, thus here... */ static void *m_start(struct seq_file *m, loff_t *pos) { struct proc_mounts *p = proc_mounts(m); down_read(&namespace_sem); if (p->cached_event == p->ns->event) { void *v = p->cached_mount; if (*pos == p->cached_index) return v; if (*pos == p->cached_index + 1) { v = seq_list_next(v, &p->ns->list, &p->cached_index); return p->cached_mount = v; } } p->cached_event = p->ns->event; p->cached_mount = seq_list_start(&p->ns->list, *pos); p->cached_index = *pos; return p->cached_mount; } static void *m_next(struct seq_file *m, void *v, loff_t *pos) { struct proc_mounts *p = proc_mounts(m); p->cached_mount = seq_list_next(v, &p->ns->list, pos); p->cached_index = *pos; return p->cached_mount; } static void m_stop(struct seq_file *m, void *v) { up_read(&namespace_sem); } static int m_show(struct seq_file *m, void *v) { struct proc_mounts *p = proc_mounts(m); struct mount *r = list_entry(v, struct mount, mnt_list); return p->show(m, &r->mnt); } const struct seq_operations mounts_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = m_show, }; #endif /* CONFIG_PROC_FS */ /** * may_umount_tree - check if a mount tree is busy * @mnt: root of mount tree * * This is called to check if a tree of mounts has any * open files, pwds, chroots or sub mounts that are * busy. */ int may_umount_tree(struct vfsmount *m) { struct mount *mnt = real_mount(m); int actual_refs = 0; int minimum_refs = 0; struct mount *p; BUG_ON(!m); /* write lock needed for mnt_get_count */ lock_mount_hash(); for (p = mnt; p; p = next_mnt(p, mnt)) { actual_refs += mnt_get_count(p); minimum_refs += 2; } unlock_mount_hash(); if (actual_refs > minimum_refs) return 0; return 1; } EXPORT_SYMBOL(may_umount_tree); /** * may_umount - check if a mount point is busy * @mnt: root of mount * * This is called to check if a mount point has any * open files, pwds, chroots or sub mounts. If the * mount has sub mounts this will return busy * regardless of whether the sub mounts are busy. * * Doesn't take quota and stuff into account. IOW, in some cases it will * give false negatives. The main reason why it's here is that we need * a non-destructive way to look for easily umountable filesystems. */ int may_umount(struct vfsmount *mnt) { int ret = 1; down_read(&namespace_sem); lock_mount_hash(); if (propagate_mount_busy(real_mount(mnt), 2)) ret = 0; unlock_mount_hash(); up_read(&namespace_sem); return ret; } EXPORT_SYMBOL(may_umount); static HLIST_HEAD(unmounted); /* protected by namespace_sem */ static void namespace_unlock(void) { struct mount *mnt; struct hlist_head head = unmounted; if (likely(hlist_empty(&head))) { up_write(&namespace_sem); return; } head.first->pprev = &head.first; INIT_HLIST_HEAD(&unmounted); up_write(&namespace_sem); synchronize_rcu(); while (!hlist_empty(&head)) { mnt = hlist_entry(head.first, struct mount, mnt_hash); hlist_del_init(&mnt->mnt_hash); if (mnt->mnt_ex_mountpoint.mnt) path_put(&mnt->mnt_ex_mountpoint); mntput(&mnt->mnt); } } static inline void namespace_lock(void) { down_write(&namespace_sem); } /* * mount_lock must be held * namespace_sem must be held for write * how = 0 => just this tree, don't propagate * how = 1 => propagate; we know that nobody else has reference to any victims * how = 2 => lazy umount */ void umount_tree(struct mount *mnt, int how) { HLIST_HEAD(tmp_list); struct mount *p; struct mount *last = NULL; for (p = mnt; p; p = next_mnt(p, mnt)) { hlist_del_init_rcu(&p->mnt_hash); hlist_add_head(&p->mnt_hash, &tmp_list); } if (how) propagate_umount(&tmp_list); hlist_for_each_entry(p, &tmp_list, mnt_hash) { list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); __touch_mnt_namespace(p->mnt_ns); p->mnt_ns = NULL; if (how < 2) p->mnt.mnt_flags |= MNT_SYNC_UMOUNT; list_del_init(&p->mnt_child); if (mnt_has_parent(p)) { put_mountpoint(p->mnt_mp); /* move the reference to mountpoint into ->mnt_ex_mountpoint */ p->mnt_ex_mountpoint.dentry = p->mnt_mountpoint; p->mnt_ex_mountpoint.mnt = &p->mnt_parent->mnt; p->mnt_mountpoint = p->mnt.mnt_root; p->mnt_parent = p; p->mnt_mp = NULL; } change_mnt_propagation(p, MS_PRIVATE); last = p; } if (last) { last->mnt_hash.next = unmounted.first; unmounted.first = tmp_list.first; unmounted.first->pprev = &unmounted.first; } } static void shrink_submounts(struct mount *mnt); static int do_umount(struct mount *mnt, int flags) { struct super_block *sb = mnt->mnt.mnt_sb; int retval; retval = security_sb_umount(&mnt->mnt, flags); if (retval) return retval; /* * Allow userspace to request a mountpoint be expired rather than * unmounting unconditionally. Unmount only happens if: * (1) the mark is already set (the mark is cleared by mntput()) * (2) the usage count == 1 [parent vfsmount] + 1 [sys_umount] */ if (flags & MNT_EXPIRE) { if (&mnt->mnt == current->fs->root.mnt || flags & (MNT_FORCE | MNT_DETACH)) return -EINVAL; /* * probably don't strictly need the lock here if we examined * all race cases, but it's a slowpath. */ lock_mount_hash(); if (mnt_get_count(mnt) != 2) { unlock_mount_hash(); return -EBUSY; } unlock_mount_hash(); if (!xchg(&mnt->mnt_expiry_mark, 1)) return -EAGAIN; } /* * If we may have to abort operations to get out of this * mount, and they will themselves hold resources we must * allow the fs to do things. In the Unix tradition of * 'Gee thats tricky lets do it in userspace' the umount_begin * might fail to complete on the first run through as other tasks * must return, and the like. Thats for the mount program to worry * about for the moment. */ if (flags & MNT_FORCE && sb->s_op->umount_begin) { sb->s_op->umount_begin(sb); } /* * No sense to grab the lock for this test, but test itself looks * somewhat bogus. Suggestions for better replacement? * Ho-hum... In principle, we might treat that as umount + switch * to rootfs. GC would eventually take care of the old vfsmount. * Actually it makes sense, especially if rootfs would contain a * /reboot - static binary that would close all descriptors and * call reboot(9). Then init(8) could umount root and exec /reboot. */ if (&mnt->mnt == current->fs->root.mnt && !(flags & MNT_DETACH)) { /* * Special case for "unmounting" root ... * we just try to remount it readonly. */ down_write(&sb->s_umount); if (!(sb->s_flags & MS_RDONLY)) retval = do_remount_sb(sb, MS_RDONLY, NULL, 0); up_write(&sb->s_umount); return retval; } namespace_lock(); lock_mount_hash(); event++; if (flags & MNT_DETACH) { if (!list_empty(&mnt->mnt_list)) umount_tree(mnt, 2); retval = 0; } else { shrink_submounts(mnt); retval = -EBUSY; if (!propagate_mount_busy(mnt, 2)) { if (!list_empty(&mnt->mnt_list)) umount_tree(mnt, 1); retval = 0; } } unlock_mount_hash(); namespace_unlock(); return retval; } /* * Is the caller allowed to modify his namespace? */ static inline bool may_mount(void) { return ns_capable(current->nsproxy->mnt_ns->user_ns, CAP_SYS_ADMIN); } /* * Now umount can handle mount points as well as block devices. * This is important for filesystems which use unnamed block devices. * * We now support a flag for forced unmount like the other 'big iron' * unixes. Our API is identical to OSF/1 to avoid making a mess of AMD */ SYSCALL_DEFINE2(umount, char __user *, name, int, flags) { struct path path; struct mount *mnt; int retval; int lookup_flags = 0; if (flags & ~(MNT_FORCE | MNT_DETACH | MNT_EXPIRE | UMOUNT_NOFOLLOW)) return -EINVAL; if (!may_mount()) return -EPERM; if (!(flags & UMOUNT_NOFOLLOW)) lookup_flags |= LOOKUP_FOLLOW; retval = user_path_mountpoint_at(AT_FDCWD, name, lookup_flags, &path); if (retval) goto out; mnt = real_mount(path.mnt); retval = -EINVAL; if (path.dentry != path.mnt->mnt_root) goto dput_and_out; if (!check_mnt(mnt)) goto dput_and_out; if (mnt->mnt.mnt_flags & MNT_LOCKED) goto dput_and_out; retval = do_umount(mnt, flags); dput_and_out: /* we mustn't call path_put() as that would clear mnt_expiry_mark */ dput(path.dentry); mntput_no_expire(mnt); out: return retval; } #ifdef __ARCH_WANT_SYS_OLDUMOUNT /* * The 2.0 compatible umount. No flags. */ SYSCALL_DEFINE1(oldumount, char __user *, name) { return sys_umount(name, 0); } #endif static bool is_mnt_ns_file(struct dentry *dentry) { /* Is this a proxy for a mount namespace? */ struct inode *inode = dentry->d_inode; struct proc_ns *ei; if (!proc_ns_inode(inode)) return false; ei = get_proc_ns(inode); if (ei->ns_ops != &mntns_operations) return false; return true; } static bool mnt_ns_loop(struct dentry *dentry) { /* Could bind mounting the mount namespace inode cause a * mount namespace loop? */ struct mnt_namespace *mnt_ns; if (!is_mnt_ns_file(dentry)) return false; mnt_ns = get_proc_ns(dentry->d_inode)->ns; return current->nsproxy->mnt_ns->seq >= mnt_ns->seq; } struct mount *copy_tree(struct mount *mnt, struct dentry *dentry, int flag) { struct mount *res, *p, *q, *r, *parent; if (!(flag & CL_COPY_UNBINDABLE) && IS_MNT_UNBINDABLE(mnt)) return ERR_PTR(-EINVAL); if (!(flag & CL_COPY_MNT_NS_FILE) && is_mnt_ns_file(dentry)) return ERR_PTR(-EINVAL); res = q = clone_mnt(mnt, dentry, flag); if (IS_ERR(q)) return q; q->mnt.mnt_flags &= ~MNT_LOCKED; q->mnt_mountpoint = mnt->mnt_mountpoint; p = mnt; list_for_each_entry(r, &mnt->mnt_mounts, mnt_child) { struct mount *s; if (!is_subdir(r->mnt_mountpoint, dentry)) continue; for (s = r; s; s = next_mnt(s, r)) { if (!(flag & CL_COPY_UNBINDABLE) && IS_MNT_UNBINDABLE(s)) { s = skip_mnt_tree(s); continue; } if (!(flag & CL_COPY_MNT_NS_FILE) && is_mnt_ns_file(s->mnt.mnt_root)) { s = skip_mnt_tree(s); continue; } while (p != s->mnt_parent) { p = p->mnt_parent; q = q->mnt_parent; } p = s; parent = q; q = clone_mnt(p, p->mnt.mnt_root, flag); if (IS_ERR(q)) goto out; lock_mount_hash(); list_add_tail(&q->mnt_list, &res->mnt_list); attach_mnt(q, parent, p->mnt_mp); unlock_mount_hash(); } } return res; out: if (res) { lock_mount_hash(); umount_tree(res, 0); unlock_mount_hash(); } return q; } /* Caller should check returned pointer for errors */ struct vfsmount *collect_mounts(struct path *path) { struct mount *tree; namespace_lock(); tree = copy_tree(real_mount(path->mnt), path->dentry, CL_COPY_ALL | CL_PRIVATE); namespace_unlock(); if (IS_ERR(tree)) return ERR_CAST(tree); return &tree->mnt; } void drop_collected_mounts(struct vfsmount *mnt) { namespace_lock(); lock_mount_hash(); umount_tree(real_mount(mnt), 0); unlock_mount_hash(); namespace_unlock(); } int iterate_mounts(int (*f)(struct vfsmount *, void *), void *arg, struct vfsmount *root) { struct mount *mnt; int res = f(root, arg); if (res) return res; list_for_each_entry(mnt, &real_mount(root)->mnt_list, mnt_list) { res = f(&mnt->mnt, arg); if (res) return res; } return 0; } static void cleanup_group_ids(struct mount *mnt, struct mount *end) { struct mount *p; for (p = mnt; p != end; p = next_mnt(p, mnt)) { if (p->mnt_group_id && !IS_MNT_SHARED(p)) mnt_release_group_id(p); } } static int invent_group_ids(struct mount *mnt, bool recurse) { struct mount *p; for (p = mnt; p; p = recurse ? next_mnt(p, mnt) : NULL) { if (!p->mnt_group_id && !IS_MNT_SHARED(p)) { int err = mnt_alloc_group_id(p); if (err) { cleanup_group_ids(mnt, p); return err; } } } return 0; } /* * @source_mnt : mount tree to be attached * @nd : place the mount tree @source_mnt is attached * @parent_nd : if non-null, detach the source_mnt from its parent and * store the parent mount and mountpoint dentry. * (done when source_mnt is moved) * * NOTE: in the table below explains the semantics when a source mount * of a given type is attached to a destination mount of a given type. * --------------------------------------------------------------------------- * | BIND MOUNT OPERATION | * |************************************************************************** * | source-->| shared | private | slave | unbindable | * | dest | | | | | * | | | | | | | * | v | | | | | * |************************************************************************** * | shared | shared (++) | shared (+) | shared(+++)| invalid | * | | | | | | * |non-shared| shared (+) | private | slave (*) | invalid | * *************************************************************************** * A bind operation clones the source mount and mounts the clone on the * destination mount. * * (++) the cloned mount is propagated to all the mounts in the propagation * tree of the destination mount and the cloned mount is added to * the peer group of the source mount. * (+) the cloned mount is created under the destination mount and is marked * as shared. The cloned mount is added to the peer group of the source * mount. * (+++) the mount is propagated to all the mounts in the propagation tree * of the destination mount and the cloned mount is made slave * of the same master as that of the source mount. The cloned mount * is marked as 'shared and slave'. * (*) the cloned mount is made a slave of the same master as that of the * source mount. * * --------------------------------------------------------------------------- * | MOVE MOUNT OPERATION | * |************************************************************************** * | source-->| shared | private | slave | unbindable | * | dest | | | | | * | | | | | | | * | v | | | | | * |************************************************************************** * | shared | shared (+) | shared (+) | shared(+++) | invalid | * | | | | | | * |non-shared| shared (+*) | private | slave (*) | unbindable | * *************************************************************************** * * (+) the mount is moved to the destination. And is then propagated to * all the mounts in the propagation tree of the destination mount. * (+*) the mount is moved to the destination. * (+++) the mount is moved to the destination and is then propagated to * all the mounts belonging to the destination mount's propagation tree. * the mount is marked as 'shared and slave'. * (*) the mount continues to be a slave at the new location. * * if the source mount is a tree, the operations explained above is * applied to each mount in the tree. * Must be called without spinlocks held, since this function can sleep * in allocations. */ static int attach_recursive_mnt(struct mount *source_mnt, struct mount *dest_mnt, struct mountpoint *dest_mp, struct path *parent_path) { HLIST_HEAD(tree_list); struct mount *child, *p; struct hlist_node *n; int err; if (IS_MNT_SHARED(dest_mnt)) { err = invent_group_ids(source_mnt, true); if (err) goto out; err = propagate_mnt(dest_mnt, dest_mp, source_mnt, &tree_list); lock_mount_hash(); if (err) goto out_cleanup_ids; for (p = source_mnt; p; p = next_mnt(p, source_mnt)) set_mnt_shared(p); } else { lock_mount_hash(); } if (parent_path) { detach_mnt(source_mnt, parent_path); attach_mnt(source_mnt, dest_mnt, dest_mp); touch_mnt_namespace(source_mnt->mnt_ns); } else { mnt_set_mountpoint(dest_mnt, dest_mp, source_mnt); commit_tree(source_mnt, NULL); } hlist_for_each_entry_safe(child, n, &tree_list, mnt_hash) { struct mount *q; hlist_del_init(&child->mnt_hash); q = __lookup_mnt_last(&child->mnt_parent->mnt, child->mnt_mountpoint); commit_tree(child, q); } unlock_mount_hash(); return 0; out_cleanup_ids: while (!hlist_empty(&tree_list)) { child = hlist_entry(tree_list.first, struct mount, mnt_hash); umount_tree(child, 0); } unlock_mount_hash(); cleanup_group_ids(source_mnt, NULL); out: return err; } static struct mountpoint *lock_mount(struct path *path) { struct vfsmount *mnt; struct dentry *dentry = path->dentry; retry: mutex_lock(&dentry->d_inode->i_mutex); if (unlikely(cant_mount(dentry))) { mutex_unlock(&dentry->d_inode->i_mutex); return ERR_PTR(-ENOENT); } namespace_lock(); mnt = lookup_mnt(path); if (likely(!mnt)) { struct mountpoint *mp = new_mountpoint(dentry); if (IS_ERR(mp)) { namespace_unlock(); mutex_unlock(&dentry->d_inode->i_mutex); return mp; } return mp; } namespace_unlock(); mutex_unlock(&path->dentry->d_inode->i_mutex); path_put(path); path->mnt = mnt; dentry = path->dentry = dget(mnt->mnt_root); goto retry; } static void unlock_mount(struct mountpoint *where) { struct dentry *dentry = where->m_dentry; put_mountpoint(where); namespace_unlock(); mutex_unlock(&dentry->d_inode->i_mutex); } static int graft_tree(struct mount *mnt, struct mount *p, struct mountpoint *mp) { if (mnt->mnt.mnt_sb->s_flags & MS_NOUSER) return -EINVAL; if (S_ISDIR(mp->m_dentry->d_inode->i_mode) != S_ISDIR(mnt->mnt.mnt_root->d_inode->i_mode)) return -ENOTDIR; return attach_recursive_mnt(mnt, p, mp, NULL); } /* * Sanity check the flags to change_mnt_propagation. */ static int flags_to_propagation_type(int flags) { int type = flags & ~(MS_REC | MS_SILENT); /* Fail if any non-propagation flags are set */ if (type & ~(MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE)) return 0; /* Only one propagation flag should be set */ if (!is_power_of_2(type)) return 0; return type; } /* * recursively change the type of the mountpoint. */ static int do_change_type(struct path *path, int flag) { struct mount *m; struct mount *mnt = real_mount(path->mnt); int recurse = flag & MS_REC; int type; int err = 0; if (path->dentry != path->mnt->mnt_root) return -EINVAL; type = flags_to_propagation_type(flag); if (!type) return -EINVAL; namespace_lock(); if (type == MS_SHARED) { err = invent_group_ids(mnt, recurse); if (err) goto out_unlock; } lock_mount_hash(); for (m = mnt; m; m = (recurse ? next_mnt(m, mnt) : NULL)) change_mnt_propagation(m, type); unlock_mount_hash(); out_unlock: namespace_unlock(); return err; } static bool has_locked_children(struct mount *mnt, struct dentry *dentry) { struct mount *child; list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) { if (!is_subdir(child->mnt_mountpoint, dentry)) continue; if (child->mnt.mnt_flags & MNT_LOCKED) return true; } return false; } /* * do loopback mount. */ static int do_loopback(struct path *path, const char *old_name, int recurse) { struct path old_path; struct mount *mnt = NULL, *old, *parent; struct mountpoint *mp; int err; if (!old_name || !*old_name) return -EINVAL; err = kern_path(old_name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &old_path); if (err) return err; err = -EINVAL; if (mnt_ns_loop(old_path.dentry)) goto out; mp = lock_mount(path); err = PTR_ERR(mp); if (IS_ERR(mp)) goto out; old = real_mount(old_path.mnt); parent = real_mount(path->mnt); err = -EINVAL; if (IS_MNT_UNBINDABLE(old)) goto out2; if (!check_mnt(parent) || !check_mnt(old)) goto out2; if (!recurse && has_locked_children(old, old_path.dentry)) goto out2; if (recurse) mnt = copy_tree(old, old_path.dentry, CL_COPY_MNT_NS_FILE); else mnt = clone_mnt(old, old_path.dentry, 0); if (IS_ERR(mnt)) { err = PTR_ERR(mnt); goto out2; } mnt->mnt.mnt_flags &= ~MNT_LOCKED; err = graft_tree(mnt, parent, mp); if (err) { lock_mount_hash(); umount_tree(mnt, 0); unlock_mount_hash(); } out2: unlock_mount(mp); out: path_put(&old_path); return err; } static int change_mount_flags(struct vfsmount *mnt, int ms_flags) { int error = 0; int readonly_request = 0; if (ms_flags & MS_RDONLY) readonly_request = 1; if (readonly_request == __mnt_is_readonly(mnt)) return 0; if (readonly_request) error = mnt_make_readonly(real_mount(mnt)); else __mnt_unmake_readonly(real_mount(mnt)); return error; } /* * change filesystem flags. dir should be a physical root of filesystem. * If you've mounted a non-root directory somewhere and want to do remount * on it - tough luck. */ static int do_remount(struct path *path, int flags, int mnt_flags, void *data) { int err; struct super_block *sb = path->mnt->mnt_sb; struct mount *mnt = real_mount(path->mnt); if (!check_mnt(mnt)) return -EINVAL; if (path->dentry != path->mnt->mnt_root) return -EINVAL; /* Don't allow changing of locked mnt flags. * * No locks need to be held here while testing the various * MNT_LOCK flags because those flags can never be cleared * once they are set. */ if ((mnt->mnt.mnt_flags & MNT_LOCK_READONLY) && !(mnt_flags & MNT_READONLY)) { return -EPERM; } err = security_sb_remount(sb, data); if (err) return err; down_write(&sb->s_umount); if (flags & MS_BIND) err = change_mount_flags(path->mnt, flags); else if (!capable(CAP_SYS_ADMIN)) err = -EPERM; else err = do_remount_sb(sb, flags, data, 0); if (!err) { lock_mount_hash(); mnt_flags |= mnt->mnt.mnt_flags & ~MNT_USER_SETTABLE_MASK; mnt->mnt.mnt_flags = mnt_flags; touch_mnt_namespace(mnt->mnt_ns); unlock_mount_hash(); } up_write(&sb->s_umount); return err; } static inline int tree_contains_unbindable(struct mount *mnt) { struct mount *p; for (p = mnt; p; p = next_mnt(p, mnt)) { if (IS_MNT_UNBINDABLE(p)) return 1; } return 0; } static int do_move_mount(struct path *path, const char *old_name) { struct path old_path, parent_path; struct mount *p; struct mount *old; struct mountpoint *mp; int err; if (!old_name || !*old_name) return -EINVAL; err = kern_path(old_name, LOOKUP_FOLLOW, &old_path); if (err) return err; mp = lock_mount(path); err = PTR_ERR(mp); if (IS_ERR(mp)) goto out; old = real_mount(old_path.mnt); p = real_mount(path->mnt); err = -EINVAL; if (!check_mnt(p) || !check_mnt(old)) goto out1; if (old->mnt.mnt_flags & MNT_LOCKED) goto out1; err = -EINVAL; if (old_path.dentry != old_path.mnt->mnt_root) goto out1; if (!mnt_has_parent(old)) goto out1; if (S_ISDIR(path->dentry->d_inode->i_mode) != S_ISDIR(old_path.dentry->d_inode->i_mode)) goto out1; /* * Don't move a mount residing in a shared parent. */ if (IS_MNT_SHARED(old->mnt_parent)) goto out1; /* * Don't move a mount tree containing unbindable mounts to a destination * mount which is shared. */ if (IS_MNT_SHARED(p) && tree_contains_unbindable(old)) goto out1; err = -ELOOP; for (; mnt_has_parent(p); p = p->mnt_parent) if (p == old) goto out1; err = attach_recursive_mnt(old, real_mount(path->mnt), mp, &parent_path); if (err) goto out1; /* if the mount is moved, it should no longer be expire * automatically */ list_del_init(&old->mnt_expire); out1: unlock_mount(mp); out: if (!err) path_put(&parent_path); path_put(&old_path); return err; } static struct vfsmount *fs_set_subtype(struct vfsmount *mnt, const char *fstype) { int err; const char *subtype = strchr(fstype, '.'); if (subtype) { subtype++; err = -EINVAL; if (!subtype[0]) goto err; } else subtype = ""; mnt->mnt_sb->s_subtype = kstrdup(subtype, GFP_KERNEL); err = -ENOMEM; if (!mnt->mnt_sb->s_subtype) goto err; return mnt; err: mntput(mnt); return ERR_PTR(err); } /* * add a mount into a namespace's mount tree */ static int do_add_mount(struct mount *newmnt, struct path *path, int mnt_flags) { struct mountpoint *mp; struct mount *parent; int err; mnt_flags &= ~MNT_INTERNAL_FLAGS; mp = lock_mount(path); if (IS_ERR(mp)) return PTR_ERR(mp); parent = real_mount(path->mnt); err = -EINVAL; if (unlikely(!check_mnt(parent))) { /* that's acceptable only for automounts done in private ns */ if (!(mnt_flags & MNT_SHRINKABLE)) goto unlock; /* ... and for those we'd better have mountpoint still alive */ if (!parent->mnt_ns) goto unlock; } /* Refuse the same filesystem on the same mount point */ err = -EBUSY; if (path->mnt->mnt_sb == newmnt->mnt.mnt_sb && path->mnt->mnt_root == path->dentry) goto unlock; err = -EINVAL; if (S_ISLNK(newmnt->mnt.mnt_root->d_inode->i_mode)) goto unlock; newmnt->mnt.mnt_flags = mnt_flags; err = graft_tree(newmnt, parent, mp); unlock: unlock_mount(mp); return err; } /* * create a new mount for userspace and request it to be added into the * namespace's tree */ static int do_new_mount(struct path *path, const char *fstype, int flags, int mnt_flags, const char *name, void *data) { struct file_system_type *type; struct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns; struct vfsmount *mnt; int err; if (!fstype) return -EINVAL; type = get_fs_type(fstype); if (!type) return -ENODEV; if (user_ns != &init_user_ns) { if (!(type->fs_flags & FS_USERNS_MOUNT)) { put_filesystem(type); return -EPERM; } /* Only in special cases allow devices from mounts * created outside the initial user namespace. */ if (!(type->fs_flags & FS_USERNS_DEV_MOUNT)) { flags |= MS_NODEV; mnt_flags |= MNT_NODEV; } } mnt = vfs_kern_mount(type, flags, name, data); if (!IS_ERR(mnt) && (type->fs_flags & FS_HAS_SUBTYPE) && !mnt->mnt_sb->s_subtype) mnt = fs_set_subtype(mnt, fstype); put_filesystem(type); if (IS_ERR(mnt)) return PTR_ERR(mnt); err = do_add_mount(real_mount(mnt), path, mnt_flags); if (err) mntput(mnt); return err; } int finish_automount(struct vfsmount *m, struct path *path) { struct mount *mnt = real_mount(m); int err; /* The new mount record should have at least 2 refs to prevent it being * expired before we get a chance to add it */ BUG_ON(mnt_get_count(mnt) < 2); if (m->mnt_sb == path->mnt->mnt_sb && m->mnt_root == path->dentry) { err = -ELOOP; goto fail; } err = do_add_mount(mnt, path, path->mnt->mnt_flags | MNT_SHRINKABLE); if (!err) return 0; fail: /* remove m from any expiration list it may be on */ if (!list_empty(&mnt->mnt_expire)) { namespace_lock(); list_del_init(&mnt->mnt_expire); namespace_unlock(); } mntput(m); mntput(m); return err; } /** * mnt_set_expiry - Put a mount on an expiration list * @mnt: The mount to list. * @expiry_list: The list to add the mount to. */ void mnt_set_expiry(struct vfsmount *mnt, struct list_head *expiry_list) { namespace_lock(); list_add_tail(&real_mount(mnt)->mnt_expire, expiry_list); namespace_unlock(); } EXPORT_SYMBOL(mnt_set_expiry); /* * process a list of expirable mountpoints with the intent of discarding any * mountpoints that aren't in use and haven't been touched since last we came * here */ void mark_mounts_for_expiry(struct list_head *mounts) { struct mount *mnt, *next; LIST_HEAD(graveyard); if (list_empty(mounts)) return; namespace_lock(); lock_mount_hash(); /* extract from the expiration list every vfsmount that matches the * following criteria: * - only referenced by its parent vfsmount * - still marked for expiry (marked on the last call here; marks are * cleared by mntput()) */ list_for_each_entry_safe(mnt, next, mounts, mnt_expire) { if (!xchg(&mnt->mnt_expiry_mark, 1) || propagate_mount_busy(mnt, 1)) continue; list_move(&mnt->mnt_expire, &graveyard); } while (!list_empty(&graveyard)) { mnt = list_first_entry(&graveyard, struct mount, mnt_expire); touch_mnt_namespace(mnt->mnt_ns); umount_tree(mnt, 1); } unlock_mount_hash(); namespace_unlock(); } EXPORT_SYMBOL_GPL(mark_mounts_for_expiry); /* * Ripoff of 'select_parent()' * * search the list of submounts for a given mountpoint, and move any * shrinkable submounts to the 'graveyard' list. */ static int select_submounts(struct mount *parent, struct list_head *graveyard) { struct mount *this_parent = parent; struct list_head *next; int found = 0; repeat: next = this_parent->mnt_mounts.next; resume: while (next != &this_parent->mnt_mounts) { struct list_head *tmp = next; struct mount *mnt = list_entry(tmp, struct mount, mnt_child); next = tmp->next; if (!(mnt->mnt.mnt_flags & MNT_SHRINKABLE)) continue; /* * Descend a level if the d_mounts list is non-empty. */ if (!list_empty(&mnt->mnt_mounts)) { this_parent = mnt; goto repeat; } if (!propagate_mount_busy(mnt, 1)) { list_move_tail(&mnt->mnt_expire, graveyard); found++; } } /* * All done at this level ... ascend and resume the search */ if (this_parent != parent) { next = this_parent->mnt_child.next; this_parent = this_parent->mnt_parent; goto resume; } return found; } /* * process a list of expirable mountpoints with the intent of discarding any * submounts of a specific parent mountpoint * * mount_lock must be held for write */ static void shrink_submounts(struct mount *mnt) { LIST_HEAD(graveyard); struct mount *m; /* extract submounts of 'mountpoint' from the expiration list */ while (select_submounts(mnt, &graveyard)) { while (!list_empty(&graveyard)) { m = list_first_entry(&graveyard, struct mount, mnt_expire); touch_mnt_namespace(m->mnt_ns); umount_tree(m, 1); } } } /* * Some copy_from_user() implementations do not return the exact number of * bytes remaining to copy on a fault. But copy_mount_options() requires that. * Note that this function differs from copy_from_user() in that it will oops * on bad values of `to', rather than returning a short copy. */ static long exact_copy_from_user(void *to, const void __user * from, unsigned long n) { char *t = to; const char __user *f = from; char c; if (!access_ok(VERIFY_READ, from, n)) return n; while (n) { if (__get_user(c, f)) { memset(t, 0, n); break; } *t++ = c; f++; n--; } return n; } int copy_mount_options(const void __user * data, unsigned long *where) { int i; unsigned long page; unsigned long size; *where = 0; if (!data) return 0; if (!(page = __get_free_page(GFP_KERNEL))) return -ENOMEM; /* We only care that *some* data at the address the user * gave us is valid. Just in case, we'll zero * the remainder of the page. */ /* copy_from_user cannot cross TASK_SIZE ! */ size = TASK_SIZE - (unsigned long)data; if (size > PAGE_SIZE) size = PAGE_SIZE; i = size - exact_copy_from_user((void *)page, data, size); if (!i) { free_page(page); return -EFAULT; } if (i != PAGE_SIZE) memset((char *)page + i, 0, PAGE_SIZE - i); *where = page; return 0; } int copy_mount_string(const void __user *data, char **where) { char *tmp; if (!data) { *where = NULL; return 0; } tmp = strndup_user(data, PAGE_SIZE); if (IS_ERR(tmp)) return PTR_ERR(tmp); *where = tmp; return 0; } /* * Flags is a 32-bit value that allows up to 31 non-fs dependent flags to * be given to the mount() call (ie: read-only, no-dev, no-suid etc). * * data is a (void *) that can point to any structure up to * PAGE_SIZE-1 bytes, which can contain arbitrary fs-dependent * information (or be NULL). * * Pre-0.97 versions of mount() didn't have a flags word. * When the flags word was introduced its top half was required * to have the magic value 0xC0ED, and this remained so until 2.4.0-test9. * Therefore, if this magic number is present, it carries no information * and must be discarded. */ long do_mount(const char *dev_name, const char *dir_name, const char *type_page, unsigned long flags, void *data_page) { struct path path; int retval = 0; int mnt_flags = 0; /* Discard magic */ if ((flags & MS_MGC_MSK) == MS_MGC_VAL) flags &= ~MS_MGC_MSK; /* Basic sanity checks */ if (!dir_name || !*dir_name || !memchr(dir_name, 0, PAGE_SIZE)) return -EINVAL; if (data_page) ((char *)data_page)[PAGE_SIZE - 1] = 0; /* ... and get the mountpoint */ retval = kern_path(dir_name, LOOKUP_FOLLOW, &path); if (retval) return retval; retval = security_sb_mount(dev_name, &path, type_page, flags, data_page); if (!retval && !may_mount()) retval = -EPERM; if (retval) goto dput_out; /* Default to relatime unless overriden */ if (!(flags & MS_NOATIME)) mnt_flags |= MNT_RELATIME; /* Separate the per-mountpoint flags */ if (flags & MS_NOSUID) mnt_flags |= MNT_NOSUID; if (flags & MS_NODEV) mnt_flags |= MNT_NODEV; if (flags & MS_NOEXEC) mnt_flags |= MNT_NOEXEC; if (flags & MS_NOATIME) mnt_flags |= MNT_NOATIME; if (flags & MS_NODIRATIME) mnt_flags |= MNT_NODIRATIME; if (flags & MS_STRICTATIME) mnt_flags &= ~(MNT_RELATIME | MNT_NOATIME); if (flags & MS_RDONLY) mnt_flags |= MNT_READONLY; flags &= ~(MS_NOSUID | MS_NOEXEC | MS_NODEV | MS_ACTIVE | MS_BORN | MS_NOATIME | MS_NODIRATIME | MS_RELATIME| MS_KERNMOUNT | MS_STRICTATIME); if (flags & MS_REMOUNT) retval = do_remount(&path, flags & ~MS_REMOUNT, mnt_flags, data_page); else if (flags & MS_BIND) retval = do_loopback(&path, dev_name, flags & MS_REC); else if (flags & (MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE)) retval = do_change_type(&path, flags); else if (flags & MS_MOVE) retval = do_move_mount(&path, dev_name); else retval = do_new_mount(&path, type_page, flags, mnt_flags, dev_name, data_page); dput_out: path_put(&path); return retval; } static void free_mnt_ns(struct mnt_namespace *ns) { proc_free_inum(ns->proc_inum); put_user_ns(ns->user_ns); kfree(ns); } /* * Assign a sequence number so we can detect when we attempt to bind * mount a reference to an older mount namespace into the current * mount namespace, preventing reference counting loops. A 64bit * number incrementing at 10Ghz will take 12,427 years to wrap which * is effectively never, so we can ignore the possibility. */ static atomic64_t mnt_ns_seq = ATOMIC64_INIT(1); static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *user_ns) { struct mnt_namespace *new_ns; int ret; new_ns = kmalloc(sizeof(struct mnt_namespace), GFP_KERNEL); if (!new_ns) return ERR_PTR(-ENOMEM); ret = proc_alloc_inum(&new_ns->proc_inum); if (ret) { kfree(new_ns); return ERR_PTR(ret); } new_ns->seq = atomic64_add_return(1, &mnt_ns_seq); atomic_set(&new_ns->count, 1); new_ns->root = NULL; INIT_LIST_HEAD(&new_ns->list); init_waitqueue_head(&new_ns->poll); new_ns->event = 0; new_ns->user_ns = get_user_ns(user_ns); return new_ns; } struct mnt_namespace *copy_mnt_ns(unsigned long flags, struct mnt_namespace *ns, struct user_namespace *user_ns, struct fs_struct *new_fs) { struct mnt_namespace *new_ns; struct vfsmount *rootmnt = NULL, *pwdmnt = NULL; struct mount *p, *q; struct mount *old; struct mount *new; int copy_flags; BUG_ON(!ns); if (likely(!(flags & CLONE_NEWNS))) { get_mnt_ns(ns); return ns; } old = ns->root; new_ns = alloc_mnt_ns(user_ns); if (IS_ERR(new_ns)) return new_ns; namespace_lock(); /* First pass: copy the tree topology */ copy_flags = CL_COPY_UNBINDABLE | CL_EXPIRE; if (user_ns != ns->user_ns) copy_flags |= CL_SHARED_TO_SLAVE | CL_UNPRIVILEGED; new = copy_tree(old, old->mnt.mnt_root, copy_flags); if (IS_ERR(new)) { namespace_unlock(); free_mnt_ns(new_ns); return ERR_CAST(new); } new_ns->root = new; list_add_tail(&new_ns->list, &new->mnt_list); /* * Second pass: switch the tsk->fs->* elements and mark new vfsmounts * as belonging to new namespace. We have already acquired a private * fs_struct, so tsk->fs->lock is not needed. */ p = old; q = new; while (p) { q->mnt_ns = new_ns; if (new_fs) { if (&p->mnt == new_fs->root.mnt) { new_fs->root.mnt = mntget(&q->mnt); rootmnt = &p->mnt; } if (&p->mnt == new_fs->pwd.mnt) { new_fs->pwd.mnt = mntget(&q->mnt); pwdmnt = &p->mnt; } } p = next_mnt(p, old); q = next_mnt(q, new); if (!q) break; while (p->mnt.mnt_root != q->mnt.mnt_root) p = next_mnt(p, old); } namespace_unlock(); if (rootmnt) mntput(rootmnt); if (pwdmnt) mntput(pwdmnt); return new_ns; } /** * create_mnt_ns - creates a private namespace and adds a root filesystem * @mnt: pointer to the new root filesystem mountpoint */ static struct mnt_namespace *create_mnt_ns(struct vfsmount *m) { struct mnt_namespace *new_ns = alloc_mnt_ns(&init_user_ns); if (!IS_ERR(new_ns)) { struct mount *mnt = real_mount(m); mnt->mnt_ns = new_ns; new_ns->root = mnt; list_add(&mnt->mnt_list, &new_ns->list); } else { mntput(m); } return new_ns; } struct dentry *mount_subtree(struct vfsmount *mnt, const char *name) { struct mnt_namespace *ns; struct super_block *s; struct path path; int err; ns = create_mnt_ns(mnt); if (IS_ERR(ns)) return ERR_CAST(ns); err = vfs_path_lookup(mnt->mnt_root, mnt, name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &path); put_mnt_ns(ns); if (err) return ERR_PTR(err); /* trade a vfsmount reference for active sb one */ s = path.mnt->mnt_sb; atomic_inc(&s->s_active); mntput(path.mnt); /* lock the sucker */ down_write(&s->s_umount); /* ... and return the root of (sub)tree on it */ return path.dentry; } EXPORT_SYMBOL(mount_subtree); SYSCALL_DEFINE5(mount, char __user *, dev_name, char __user *, dir_name, char __user *, type, unsigned long, flags, void __user *, data) { int ret; char *kernel_type; struct filename *kernel_dir; char *kernel_dev; unsigned long data_page; ret = copy_mount_string(type, &kernel_type); if (ret < 0) goto out_type; kernel_dir = getname(dir_name); if (IS_ERR(kernel_dir)) { ret = PTR_ERR(kernel_dir); goto out_dir; } ret = copy_mount_string(dev_name, &kernel_dev); if (ret < 0) goto out_dev; ret = copy_mount_options(data, &data_page); if (ret < 0) goto out_data; ret = do_mount(kernel_dev, kernel_dir->name, kernel_type, flags, (void *) data_page); free_page(data_page); out_data: kfree(kernel_dev); out_dev: putname(kernel_dir); out_dir: kfree(kernel_type); out_type: return ret; } /* * Return true if path is reachable from root * * namespace_sem or mount_lock is held */ bool is_path_reachable(struct mount *mnt, struct dentry *dentry, const struct path *root) { while (&mnt->mnt != root->mnt && mnt_has_parent(mnt)) { dentry = mnt->mnt_mountpoint; mnt = mnt->mnt_parent; } return &mnt->mnt == root->mnt && is_subdir(dentry, root->dentry); } int path_is_under(struct path *path1, struct path *path2) { int res; read_seqlock_excl(&mount_lock); res = is_path_reachable(real_mount(path1->mnt), path1->dentry, path2); read_sequnlock_excl(&mount_lock); return res; } EXPORT_SYMBOL(path_is_under); /* * pivot_root Semantics: * Moves the root file system of the current process to the directory put_old, * makes new_root as the new root file system of the current process, and sets * root/cwd of all processes which had them on the current root to new_root. * * Restrictions: * The new_root and put_old must be directories, and must not be on the * same file system as the current process root. The put_old must be * underneath new_root, i.e. adding a non-zero number of /.. to the string * pointed to by put_old must yield the same directory as new_root. No other * file system may be mounted on put_old. After all, new_root is a mountpoint. * * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem. * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives * in this situation. * * Notes: * - we don't move root/cwd if they are not at the root (reason: if something * cared enough to change them, it's probably wrong to force them elsewhere) * - it's okay to pick a root that isn't the root of a file system, e.g. * /nfs/my_root where /nfs is the mount point. It must be a mountpoint, * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root * first. */ SYSCALL_DEFINE2(pivot_root, const char __user *, new_root, const char __user *, put_old) { struct path new, old, parent_path, root_parent, root; struct mount *new_mnt, *root_mnt, *old_mnt; struct mountpoint *old_mp, *root_mp; int error; if (!may_mount()) return -EPERM; error = user_path_dir(new_root, &new); if (error) goto out0; error = user_path_dir(put_old, &old); if (error) goto out1; error = security_sb_pivotroot(&old, &new); if (error) goto out2; get_fs_root(current->fs, &root); old_mp = lock_mount(&old); error = PTR_ERR(old_mp); if (IS_ERR(old_mp)) goto out3; error = -EINVAL; new_mnt = real_mount(new.mnt); root_mnt = real_mount(root.mnt); old_mnt = real_mount(old.mnt); if (IS_MNT_SHARED(old_mnt) || IS_MNT_SHARED(new_mnt->mnt_parent) || IS_MNT_SHARED(root_mnt->mnt_parent)) goto out4; if (!check_mnt(root_mnt) || !check_mnt(new_mnt)) goto out4; if (new_mnt->mnt.mnt_flags & MNT_LOCKED) goto out4; error = -ENOENT; if (d_unlinked(new.dentry)) goto out4; error = -EBUSY; if (new_mnt == root_mnt || old_mnt == root_mnt) goto out4; /* loop, on the same file system */ error = -EINVAL; if (root.mnt->mnt_root != root.dentry) goto out4; /* not a mountpoint */ if (!mnt_has_parent(root_mnt)) goto out4; /* not attached */ root_mp = root_mnt->mnt_mp; if (new.mnt->mnt_root != new.dentry) goto out4; /* not a mountpoint */ if (!mnt_has_parent(new_mnt)) goto out4; /* not attached */ /* make sure we can reach put_old from new_root */ if (!is_path_reachable(old_mnt, old.dentry, &new)) goto out4; root_mp->m_count++; /* pin it so it won't go away */ lock_mount_hash(); detach_mnt(new_mnt, &parent_path); detach_mnt(root_mnt, &root_parent); if (root_mnt->mnt.mnt_flags & MNT_LOCKED) { new_mnt->mnt.mnt_flags |= MNT_LOCKED; root_mnt->mnt.mnt_flags &= ~MNT_LOCKED; } /* mount old root on put_old */ attach_mnt(root_mnt, old_mnt, old_mp); /* mount new_root on / */ attach_mnt(new_mnt, real_mount(root_parent.mnt), root_mp); touch_mnt_namespace(current->nsproxy->mnt_ns); unlock_mount_hash(); chroot_fs_refs(&root, &new); put_mountpoint(root_mp); error = 0; out4: unlock_mount(old_mp); if (!error) { path_put(&root_parent); path_put(&parent_path); } out3: path_put(&root); out2: path_put(&old); out1: path_put(&new); out0: return error; } static void __init init_mount_tree(void) { struct vfsmount *mnt; struct mnt_namespace *ns; struct path root; struct file_system_type *type; type = get_fs_type("rootfs"); if (!type) panic("Can't find rootfs type"); mnt = vfs_kern_mount(type, 0, "rootfs", NULL); put_filesystem(type); if (IS_ERR(mnt)) panic("Can't create rootfs"); ns = create_mnt_ns(mnt); if (IS_ERR(ns)) panic("Can't allocate initial namespace"); init_task.nsproxy->mnt_ns = ns; get_mnt_ns(ns); root.mnt = mnt; root.dentry = mnt->mnt_root; set_fs_pwd(current->fs, &root); set_fs_root(current->fs, &root); } void __init mnt_init(void) { unsigned u; int err; mnt_cache = kmem_cache_create("mnt_cache", sizeof(struct mount), 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL); mount_hashtable = alloc_large_system_hash("Mount-cache", sizeof(struct hlist_head), mhash_entries, 19, 0, &m_hash_shift, &m_hash_mask, 0, 0); mountpoint_hashtable = alloc_large_system_hash("Mountpoint-cache", sizeof(struct hlist_head), mphash_entries, 19, 0, &mp_hash_shift, &mp_hash_mask, 0, 0); if (!mount_hashtable || !mountpoint_hashtable) panic("Failed to allocate mount hash table\n"); for (u = 0; u <= m_hash_mask; u++) INIT_HLIST_HEAD(&mount_hashtable[u]); for (u = 0; u <= mp_hash_mask; u++) INIT_HLIST_HEAD(&mountpoint_hashtable[u]); kernfs_init(); err = sysfs_init(); if (err) printk(KERN_WARNING "%s: sysfs_init error: %d\n", __func__, err); fs_kobj = kobject_create_and_add("fs", NULL); if (!fs_kobj) printk(KERN_WARNING "%s: kobj create error\n", __func__); init_rootfs(); init_mount_tree(); } void put_mnt_ns(struct mnt_namespace *ns) { if (!atomic_dec_and_test(&ns->count)) return; drop_collected_mounts(&ns->root->mnt); free_mnt_ns(ns); } struct vfsmount *kern_mount_data(struct file_system_type *type, void *data) { struct vfsmount *mnt; mnt = vfs_kern_mount(type, MS_KERNMOUNT, type->name, data); if (!IS_ERR(mnt)) { /* * it is a longterm mount, don't release mnt until * we unmount before file sys is unregistered */ real_mount(mnt)->mnt_ns = MNT_NS_INTERNAL; } return mnt; } EXPORT_SYMBOL_GPL(kern_mount_data); void kern_unmount(struct vfsmount *mnt) { /* release long term mount so mount point can be released */ if (!IS_ERR_OR_NULL(mnt)) { real_mount(mnt)->mnt_ns = NULL; synchronize_rcu(); /* yecchhh... */ mntput(mnt); } } EXPORT_SYMBOL(kern_unmount); bool our_mnt(struct vfsmount *mnt) { return check_mnt(real_mount(mnt)); } bool current_chrooted(void) { /* Does the current process have a non-standard root */ struct path ns_root; struct path fs_root; bool chrooted; /* Find the namespace root */ ns_root.mnt = &current->nsproxy->mnt_ns->root->mnt; ns_root.dentry = ns_root.mnt->mnt_root; path_get(&ns_root); while (d_mountpoint(ns_root.dentry) && follow_down_one(&ns_root)) ; get_fs_root(current->fs, &fs_root); chrooted = !path_equal(&fs_root, &ns_root); path_put(&fs_root); path_put(&ns_root); return chrooted; } bool fs_fully_visible(struct file_system_type *type) { struct mnt_namespace *ns = current->nsproxy->mnt_ns; struct mount *mnt; bool visible = false; if (unlikely(!ns)) return false; down_read(&namespace_sem); list_for_each_entry(mnt, &ns->list, mnt_list) { struct mount *child; if (mnt->mnt.mnt_sb->s_type != type) continue; /* This mount is not fully visible if there are any child mounts * that cover anything except for empty directories. */ list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) { struct inode *inode = child->mnt_mountpoint->d_inode; if (!S_ISDIR(inode->i_mode)) goto next; if (inode->i_nlink > 2) goto next; } visible = true; goto found; next: ; } found: up_read(&namespace_sem); return visible; } static void *mntns_get(struct task_struct *task) { struct mnt_namespace *ns = NULL; struct nsproxy *nsproxy; task_lock(task); nsproxy = task->nsproxy; if (nsproxy) { ns = nsproxy->mnt_ns; get_mnt_ns(ns); } task_unlock(task); return ns; } static void mntns_put(void *ns) { put_mnt_ns(ns); } static int mntns_install(struct nsproxy *nsproxy, void *ns) { struct fs_struct *fs = current->fs; struct mnt_namespace *mnt_ns = ns; struct path root; if (!ns_capable(mnt_ns->user_ns, CAP_SYS_ADMIN) || !ns_capable(current_user_ns(), CAP_SYS_CHROOT) || !ns_capable(current_user_ns(), CAP_SYS_ADMIN)) return -EPERM; if (fs->users != 1) return -EINVAL; get_mnt_ns(mnt_ns); put_mnt_ns(nsproxy->mnt_ns); nsproxy->mnt_ns = mnt_ns; /* Find the root */ root.mnt = &mnt_ns->root->mnt; root.dentry = mnt_ns->root->mnt.mnt_root; path_get(&root); while(d_mountpoint(root.dentry) && follow_down_one(&root)) ; /* Update the pwd and root */ set_fs_pwd(fs, &root); set_fs_root(fs, &root); path_put(&root); return 0; } static unsigned int mntns_inum(void *ns) { struct mnt_namespace *mnt_ns = ns; return mnt_ns->proc_inum; } const struct proc_ns_operations mntns_operations = { .name = "mnt", .type = CLONE_NEWNS, .get = mntns_get, .put = mntns_put, .install = mntns_install, .inum = mntns_inum, };
./CrossVul/dataset_final_sorted/CWE-264/c/bad_2244_0
crossvul-cpp_data_bad_4617_1
// Copyright (c) 2018, Peter Ohler, All rights reserved. #include <ctype.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include "bind.h" #include "con.h" #include "debug.h" #include "domain.h" #include "dtime.h" #include "hook.h" #include "gqlsub.h" #include "http.h" #include "log.h" #include "page.h" #include "pub.h" #include "ready.h" #include "res.h" #include "seg.h" #include "server.h" #include "sse.h" #include "subject.h" #include "upgraded.h" #include "websocket.h" #define CON_TIMEOUT 10.0 #define INITIAL_POLL_SIZE 1024 typedef enum { HEAD_AGAIN = 'A', HEAD_ERR = 'E', HEAD_OK = 'O', HEAD_HANDLED = 'H', } HeadReturn; static bool con_ws_read(agooCon c); static bool con_ws_write(agooCon c); static short con_ws_events(agooCon c); static bool con_sse_write(agooCon c); static short con_sse_events(agooCon c); static struct _agooBind ws_bind = { .kind = AGOO_CON_WS, .read = con_ws_read, .write = con_ws_write, .events = con_ws_events, }; static struct _agooBind sse_bind = { .kind = AGOO_CON_SSE, .read = NULL, .write = con_sse_write, .events = con_sse_events, }; agooCon agoo_con_create(agooErr err, int sock, uint64_t id, agooBind b) { agooCon c; if (NULL == (c = (agooCon)AGOO_CALLOC(1, sizeof(struct _agooCon)))) { AGOO_ERR_MEM(err, "Connection"); } else { c->sock = sock; c->id = id; c->timeout = dtime() + CON_TIMEOUT; c->bind = b; c->loop = NULL; pthread_mutex_init(&c->res_lock, 0); } return c; } void agoo_con_destroy(agooCon c) { atomic_fetch_sub(&agoo_server.con_cnt, 1); if (AGOO_CON_WS == c->bind->kind || AGOO_CON_SSE == c->bind->kind) { agoo_ws_req_close(c); } if (0 < c->sock) { #ifdef HAVE_OPENSSL_SSL_H if (NULL != c->ssl) { SSL_free(c->ssl); c->ssl = NULL; } #endif close(c->sock); c->sock = 0; } if (NULL != c->req) { agoo_req_destroy(c->req); } if (NULL != c->up) { agoo_upgraded_release_con(c->up); c->up = NULL; } if (NULL != c->gsub) { agoo_server_del_gsub(c->gsub); gql_sub_destroy(c->gsub); c->gsub = NULL; } agoo_log_cat(&agoo_con_cat, "Connection %llu closed.", (unsigned long long)c->id); agooRes res; while (NULL != (res = c->res_head)) { c->res_head = res->next; AGOO_FREE(res); } pthread_mutex_destroy(&c->res_lock); AGOO_FREE(c); } void agoo_con_res_append(agooCon c, agooRes res) { pthread_mutex_lock(&c->res_lock); if (NULL == c->res_tail) { c->res_head = res; } else { c->res_tail->next = res; } c->res_tail = res; pthread_mutex_unlock(&c->res_lock); } static void agoo_con_res_prepend(agooCon c, agooRes res) { pthread_mutex_lock(&c->res_lock); res->next = c->res_head; c->res_head = res; if (NULL == c->res_tail) { c->res_tail = res; } pthread_mutex_unlock(&c->res_lock); } static agooRes agoo_con_res_pop(agooCon c) { agooRes res; pthread_mutex_lock(&c->res_lock); if (NULL != (res = c->res_head)) { c->res_head = res->next; if (res == c->res_tail) { c->res_tail = NULL; } } pthread_mutex_unlock(&c->res_lock); return res; } static agooRes agoo_con_res_peek(agooCon c) { agooRes res; pthread_mutex_lock(&c->res_lock); res = c->res_head; pthread_mutex_unlock(&c->res_lock); return res; } const char* agoo_con_header_value(const char *header, int hlen, const char *key, int *vlen) { // Search for \r then check for \n and then the key followed by a :. Keep // trying until the end of the header. const char *h = header; const char *hend = header + hlen; const char *value; int klen = (int)strlen(key); while (h < hend) { if (0 == strncasecmp(key, h, klen) && ':' == h[klen]) { h += klen + 1; for (; ' ' == *h; h++) { } value = h; for (; '\r' != *h && '\0' != *h; h++) { } *vlen = (int)(h - value); return value; } for (; h < hend; h++) { if ('\r' == *h && '\n' == *(h + 1)) { h += 2; break; } } } return NULL; } static HeadReturn bad_request(agooCon c, int status, int line) { agooRes res; const char *msg = agoo_http_code_message(status); if (NULL == (res = agoo_res_create(c))) { agoo_log_cat(&agoo_error_cat, "memory allocation of response failed on connection %llu @ %d.", (unsigned long long)c->id, line); } else { char buf[256]; int cnt = snprintf(buf, sizeof(buf), "HTTP/1.1 %d %s\r\nConnection: Close\r\nContent-Length: 0\r\n\r\n", status, msg); agooText message = agoo_text_create(buf, cnt); agoo_con_res_append(c, res); res->close = true; agoo_res_message_push(res, message); } return HEAD_ERR; } static bool should_close(const char *header, int hlen) { const char *v; int vlen = 0; if (NULL != (v = agoo_con_header_value(header, hlen, "Connection", &vlen))) { return (5 == vlen && 0 == strncasecmp("Close", v, 5)); } return false; } static bool page_response(agooCon c, agooPage p, char *hend) { agooRes res; char *b; if (NULL == (res = agoo_res_create(c))) { return true; } agoo_con_res_append(c, res); b = strstr(c->buf, "\r\n"); res->close = should_close(b, (int)(hend - b)); if (res->close) { c->closing = true; } agoo_res_message_push(res, p->resp); return false; } // rserver static void push_error(agooUpgraded up, const char *msg, int mlen) { if (NULL != up && agoo_server.ctx_nil_value != up->ctx && up->on_error) { agooReq req = agoo_req_create(mlen); if (NULL == req) { return; } memcpy(req->msg, msg, mlen); req->msg[mlen] = '\0'; req->up = up; req->method = AGOO_ON_ERROR; req->hook = agoo_hook_create(AGOO_NONE, NULL, up->ctx, PUSH_HOOK, &agoo_server.eval_queue); agoo_upgraded_ref(up); agoo_queue_push(&agoo_server.eval_queue, (void*)req); } } static HeadReturn con_header_read(agooCon c, size_t *mlenp) { char *hend = strstr(c->buf, "\r\n\r\n"); agooMethod method; struct _agooSeg path; char *query = NULL; char *qend; char *b; size_t clen = 0; long mlen; agooHook hook = NULL; agooPage p; struct _agooErr err = AGOO_ERR_INIT; if (NULL == hend) { if (sizeof(c->buf) - 1 <= c->bcnt) { return bad_request(c, 431, __LINE__); } return HEAD_AGAIN; } if (agoo_req_cat.on) { *hend = '\0'; agoo_log_cat(&agoo_req_cat, "%s %llu: %s", agoo_con_kind_str(c->bind->kind), (unsigned long long)c->id, c->buf); *hend = '\r'; } for (b = c->buf; ' ' != *b; b++) { if ('\0' == *b) { return bad_request(c, 400, __LINE__); } } switch (toupper(*c->buf)) { case 'G': if (3 != b - c->buf || 0 != strncmp("GET", c->buf, 3)) { return bad_request(c, 400, __LINE__); } method = AGOO_GET; break; case 'P': { const char *v; int vlen = 0; char *vend; if (3 == b - c->buf && 0 == strncmp("PUT", c->buf, 3)) { method = AGOO_PUT; } else if (4 == b - c->buf && 0 == strncmp("POST", c->buf, 4)) { method = AGOO_POST; } else { return bad_request(c, 400, __LINE__); } if (NULL == (v = agoo_con_header_value(c->buf, (int)(hend - c->buf), "Content-Length", &vlen))) { return bad_request(c, 411, __LINE__); } clen = (size_t)strtoul(v, &vend, 10); if (vend != v + vlen) { return bad_request(c, 411, __LINE__); } break; } case 'D': if (6 != b - c->buf || 0 != strncmp("DELETE", c->buf, 6)) { return bad_request(c, 400, __LINE__); } method = AGOO_DELETE; break; case 'H': if (4 != b - c->buf || 0 != strncmp("HEAD", c->buf, 4)) { return bad_request(c, 400, __LINE__); } method = AGOO_HEAD; break; case 'O': if (7 != b - c->buf || 0 != strncmp("OPTIONS", c->buf, 7)) { return bad_request(c, 400, __LINE__); } method = AGOO_OPTIONS; break; case 'C': if (7 != b - c->buf || 0 != strncmp("CONNECT", c->buf, 7)) { return bad_request(c, 400, __LINE__); } method = AGOO_CONNECT; break; default: return bad_request(c, 400, __LINE__); } for (; ' ' == *b; b++) { if ('\0' == *b) { return bad_request(c, 400, __LINE__); } } path.start = b; for (; ' ' != *b; b++) { switch (*b) { case '?': path.end = b; query = b + 1; break; case '\0': return bad_request(c, 400, __LINE__); default: break; } } if (NULL == query) { path.end = b; query = b; qend = b; } else { qend = b; } mlen = hend - c->buf + 4 + clen; *mlenp = mlen; if (AGOO_GET == method) { char root_buf[20148]; const char *root = NULL; if (NULL != (p = agoo_group_get(&err, path.start, (int)(path.end - path.start)))) { if (page_response(c, p, hend)) { return bad_request(c, 500, __LINE__); } return HEAD_HANDLED; } if (agoo_domain_use()) { const char *host; int vlen = 0; if (NULL == (host = agoo_con_header_value(c->buf, (int)(hend - c->buf), "Host", &vlen))) { return bad_request(c, 411, __LINE__); } ((char*)host)[vlen] = '\0'; root = agoo_domain_resolve(host, root_buf, sizeof(root_buf)); ((char*)host)[vlen] = '\r'; } if (agoo_server.root_first && NULL != (p = agoo_page_get(&err, path.start, (int)(path.end - path.start), root))) { if (page_response(c, p, hend)) { return bad_request(c, 500, __LINE__); } return HEAD_HANDLED; } if (NULL == (hook = agoo_hook_find(agoo_server.hooks, method, &path))) { if (NULL != (p = agoo_page_get(&err, path.start, (int)(path.end - path.start), root))) { if (page_response(c, p, hend)) { return bad_request(c, 500, __LINE__); } return HEAD_HANDLED; } if (NULL == agoo_server.hook404) { return bad_request(c, 404, __LINE__); } hook = agoo_server.hook404; } } else if (NULL == (hook = agoo_hook_find(agoo_server.hooks, method, &path))) { return bad_request(c, 404, __LINE__); } // Create request and populate. if (NULL == (c->req = agoo_req_create(mlen))) { return bad_request(c, 413, __LINE__); } if ((long)c->bcnt <= mlen) { memcpy(c->req->msg, c->buf, c->bcnt); if ((long)c->bcnt < mlen) { memset(c->req->msg + c->bcnt, 0, mlen - c->bcnt); } } else { memcpy(c->req->msg, c->buf, mlen); } c->req->msg[mlen] = '\0'; c->req->method = method; c->req->upgrade = AGOO_UP_NONE; c->req->up = NULL; c->req->path.start = c->req->msg + (path.start - c->buf); c->req->path.len = (int)(path.end - path.start); c->req->query.start = c->req->msg + (query - c->buf); c->req->query.len = (int)(qend - query); c->req->query.start[c->req->query.len] = '\0'; c->req->body.start = c->req->msg + (hend - c->buf + 4); c->req->body.len = (unsigned int)clen; b = strstr(b, "\r\n"); c->req->header.start = c->req->msg + (b + 2 - c->buf); if (b < hend) { c->req->header.len = (unsigned int)(hend - b - 2); } else { c->req->header.len = 0; } c->req->res = NULL; c->req->hook = hook; return HEAD_OK; } static void check_upgrade(agooCon c) { const char *v; int vlen = 0; if (NULL == c->req) { return; } if (NULL != (v = agoo_con_header_value(c->req->header.start, c->req->header.len, "Connection", &vlen))) { if (NULL != strstr(v, "Upgrade")) { if (NULL != (v = agoo_con_header_value(c->req->header.start, c->req->header.len, "Upgrade", &vlen))) { if (0 == strncasecmp("WebSocket", v, vlen)) { c->res_tail->close = false; c->res_tail->con_kind = AGOO_CON_WS; return; } } } } if (NULL != (v = agoo_con_header_value(c->req->header.start, c->req->header.len, "Accept", &vlen))) { if (0 == strncasecmp("text/event-stream", v, vlen)) { c->res_tail->close = false; c->res_tail->con_kind = AGOO_CON_SSE; return; } } } #ifdef HAVE_OPENSSL_SSL_H static void con_ssl_error(agooCon c, const char *what, unsigned long e, const char *filename, int line) { char buf[224]; if (0 == e) { e = ERR_get_error(); } c->dead = true; ERR_error_string_n(e, buf, sizeof(buf)); agoo_log_cat(&agoo_error_cat, "%s %s at %s:%d", what, buf, filename, line); } #endif bool agoo_con_http_read(agooCon c) { ssize_t cnt = 0; if (c->dead || 0 == c->sock || c->closing) { return true; } if (AGOO_CON_HTTPS == c->bind->kind) { #ifdef HAVE_OPENSSL_SSL_H if (NULL != c->req) { cnt = SSL_read(c->ssl, c->req->msg + c->bcnt, (int)(c->req->mlen - c->bcnt)); } else { cnt = SSL_read(c->ssl, c->buf + c->bcnt, (int)(sizeof(c->buf) - c->bcnt - 1)); } if (0 > cnt) { //unsigned long e = ERR_get_error(); int e = (int)ERR_get_error(); if (0 == e) { return false; } else { con_ssl_error(c, "read", (unsigned long)e, __FILE__, __LINE__); c->dead = true; return true; } } #else agoo_log_cat(&agoo_error_cat, "SSL not included in the build."); c->dead = true; #endif } else { if (NULL != c->req) { cnt = recv(c->sock, c->req->msg + c->bcnt, c->req->mlen - c->bcnt, 0); } else { cnt = recv(c->sock, c->buf + c->bcnt, sizeof(c->buf) - c->bcnt - 1, 0); } } c->timeout = dtime() + CON_TIMEOUT; if (0 >= cnt) { // If nothing read then no need to complain. Just close. if (0 < c->bcnt) { if (0 == cnt) { agoo_log_cat(&agoo_warn_cat, "Nothing to read. Client closed socket on connection %llu.", (unsigned long long)c->id); } else { agoo_log_cat(&agoo_warn_cat, "Failed to read request. %s.", strerror(errno)); } } c->dead = true; return true; } c->bcnt += cnt; while (true) { if (NULL == c->req) { size_t mlen; switch (con_header_read(c, &mlen)) { case HEAD_AGAIN: // Try again the next time. Didn't read enough. return false; case HEAD_OK: // req was created break; case HEAD_HANDLED: if (mlen < c->bcnt) { memmove(c->buf, c->buf + mlen, c->bcnt - mlen); c->bcnt -= mlen; // req is NULL so try to ready the header on the next request. continue; } else { c->bcnt = 0; *c->buf = '\0'; return false; } break; case HEAD_ERR: default: c->bcnt = 0; *c->buf = '\0'; return false; } } if (NULL != c->req) { if (c->req->mlen <= c->bcnt) { agooReq req; agooRes res; long mlen; if (agoo_debug_cat.on && NULL != c->req && NULL != c->req->body.start) { agoo_log_cat(&agoo_debug_cat, "%s request on %llu: %s", agoo_con_kind_str(c->bind->kind), (unsigned long long)c->id, c->req->body.start); } if (NULL == (res = agoo_res_create(c))) { c->req = NULL; agoo_log_cat(&agoo_error_cat, "memory allocation of response failed on connection %llu.", (unsigned long long)c->id); return bad_request(c, 500, __LINE__); } else { agoo_con_res_append(c, res); res->close = should_close(c->req->header.start, c->req->header.len); if (res->close) { c->closing = true; } } c->req->res = res; mlen = c->req->mlen; check_upgrade(c); req = c->req; c->req = NULL; if (req->hook->no_queue && FUNC_HOOK == req->hook->type) { req->hook->func(req); agoo_req_destroy(req); } else { agoo_queue_push(req->hook->queue, (void*)req); } if (mlen < (long)c->bcnt) { memmove(c->buf, c->buf + mlen, c->bcnt - mlen); c->bcnt -= mlen; } else { c->bcnt = 0; *c->buf = '\0'; break; } continue; } } break; } return false; } // return false to remove/close connection bool agoo_con_http_write(agooCon c) { agooRes res = agoo_con_res_pop(c); agooText message = agoo_res_message_peek(res); ssize_t cnt = 0; if (NULL == message) { return true; } c->timeout = dtime() + CON_TIMEOUT; if (0 == c->wcnt) { if (agoo_resp_cat.on) { char buf[4096]; char *hend = strstr(message->text, "\r\n\r\n"); if (NULL == hend) { hend = message->text + message->len; } if ((long)sizeof(buf) <= hend - message->text) { hend = message->text + sizeof(buf) - 1; } memcpy(buf, message->text, hend - message->text); buf[hend - message->text] = '\0'; agoo_log_cat(&agoo_resp_cat, "%s %llu: %s", agoo_con_kind_str(c->bind->kind), (unsigned long long)c->id, buf); } if (agoo_debug_cat.on) { agoo_log_cat(&agoo_debug_cat, "%s response on %llu: %s", agoo_con_kind_str(c->bind->kind), (unsigned long long)c->id, message->text); } } if (AGOO_CON_HTTPS == c->bind->kind) { #ifdef HAVE_OPENSSL_SSL_H if (0 >= (cnt = SSL_write(c->ssl, message->text + c->wcnt, (int)(message->len - c->wcnt)))) { unsigned long e = ERR_get_error(); if (0 == e) { return true; } con_ssl_error(c, "write", (unsigned long)e, __FILE__, __LINE__); c->dead = true; return false; } #else agoo_log_cat(&agoo_error_cat, "SSL not included in the build."); c->dead = true; #endif } else { if (0 > (cnt = send(c->sock, message->text + c->wcnt, message->len - c->wcnt, MSG_DONTWAIT))) { if (EAGAIN == errno) { return true; } agoo_log_cat(&agoo_error_cat, "Socket error @ %llu.", (unsigned long long)c->id); c->dead = true; return false; } } c->wcnt += cnt; if (c->wcnt == message->len) { // finished agooText next = agoo_res_message_next(res); c->wcnt = 0; if (NULL == next && res->final) { bool done = res->close; agoo_res_destroy(res); return !done; } } agoo_con_res_prepend(c, res); return true; } static bool con_ws_read(agooCon c) { ssize_t cnt; uint8_t *b; uint8_t op; long mlen; if (NULL != c->req) { cnt = recv(c->sock, c->req->msg + c->bcnt, c->req->mlen - c->bcnt, 0); } else { cnt = recv(c->sock, c->buf + c->bcnt, sizeof(c->buf) - c->bcnt - 1, 0); } c->timeout = dtime() + CON_TIMEOUT; if (0 >= cnt) { // If nothing read then no need to complain. Just close. if (0 < c->bcnt) { if (0 == cnt) { agoo_log_cat(&agoo_warn_cat, "Nothing to read. Client closed socket on connection %llu.", (unsigned long long)c->id); } else { char msg[1024]; int len = snprintf(msg, sizeof(msg) - 1, "Failed to read WebSocket message. %s.", strerror(errno)); push_error(c->up, msg, len); agoo_log_cat(&agoo_warn_cat, "Failed to read WebSocket message. %s.", strerror(errno)); } } return true; } c->bcnt += cnt; while (true) { if (NULL == c->req) { if (c->bcnt < 2) { return false; // Try again. } b = (uint8_t*)c->buf; if (0 >= (mlen = agoo_ws_calc_len(c, b, c->bcnt))) { return (mlen < 0); } op = 0x0F & *b; switch (op) { case AGOO_WS_OP_TEXT: case AGOO_WS_OP_BIN: if (NULL != c->gsub) { // GraphQL subscriptions do not accept input on the // connection. break; } if (agoo_ws_create_req(c, mlen)) { return true; } break; case AGOO_WS_OP_CLOSE: return true; case AGOO_WS_OP_PING: if (mlen == (long)c->bcnt) { agoo_ws_pong(c); c->bcnt = 0; } break; case AGOO_WS_OP_PONG: // ignore if (mlen == (long)c->bcnt) { c->bcnt = 0; } break; case AGOO_WS_OP_CONT: default: { char msg[1024]; int len = snprintf(msg, sizeof(msg) - 1, "WebSocket op 0x%02x not supported on %llu.", op, (unsigned long long)c->id); push_error(c->up, msg, len); agoo_log_cat(&agoo_error_cat, "WebSocket op 0x%02x not supported on %llu.", op, (unsigned long long)c->id); return true; } } } if (NULL != c->req) { mlen = c->req->mlen; c->req->mlen = agoo_ws_decode(c->req->msg, c->req->mlen); if (mlen <= (long)c->bcnt) { if (agoo_debug_cat.on) { if (AGOO_ON_MSG == c->req->method) { agoo_log_cat(&agoo_debug_cat, "WebSocket message on %llu: %s", (unsigned long long)c->id, c->req->msg); } else { agoo_log_cat(&agoo_debug_cat, "WebSocket binary message on %llu", (unsigned long long)c->id); } } } agoo_upgraded_ref(c->up); agoo_queue_push(&agoo_server.eval_queue, (void*)c->req); if (mlen < (long)c->bcnt) { memmove(c->buf, c->buf + mlen, c->bcnt - mlen); c->bcnt -= mlen; } else { c->bcnt = 0; *c->buf = '\0'; c->req = NULL; break; } c->req = NULL; continue; } break; } return false; } static const char ping_msg[] = "\x89\x00"; static const char pong_msg[] = "\x8a\x00"; static bool con_ws_write(agooCon c) { agooRes res = agoo_con_res_pop(c); agooText message = agoo_res_message_peek(res); ssize_t cnt; if (NULL == message) { if (res->ping) { if (0 > (cnt = send(c->sock, ping_msg, sizeof(ping_msg) - 1, 0))) { char msg[1024]; int len; if (EAGAIN == errno) { return true; } len = snprintf(msg, sizeof(msg) - 1, "Socket error @ %llu.", (unsigned long long)c->id); push_error(c->up, msg, len); agoo_log_cat(&agoo_error_cat, "Socket error @ %llu.", (unsigned long long)c->id); agoo_ws_req_close(c); agoo_res_destroy(res); return false; } } else if (res->pong) { if (0 > (cnt = send(c->sock, pong_msg, sizeof(pong_msg) - 1, 0))) { char msg[1024]; int len; if (EAGAIN == errno) { return true; } len = snprintf(msg, sizeof(msg) - 1, "Socket error @ %llu.", (unsigned long long)c->id); push_error(c->up, msg, len); agoo_log_cat(&agoo_error_cat, "Socket error @ %llu.", (unsigned long long)c->id); agoo_ws_req_close(c); agoo_res_destroy(res); return false; } } else { agoo_ws_req_close(c); agoo_res_destroy(res); return false; } return true; } c->timeout = dtime() + CON_TIMEOUT; if (0 == c->wcnt) { agooText t; if (agoo_push_cat.on) { if (message->bin) { agoo_log_cat(&agoo_push_cat, "%llu binary", (unsigned long long)c->id); } else { agoo_log_cat(&agoo_push_cat, "%llu: %s", (unsigned long long)c->id, message->text); } } t = agoo_ws_expand(message); if (t != message) { agoo_res_message_push(res, t); message = t; } } if (0 > (cnt = send(c->sock, message->text + c->wcnt, message->len - c->wcnt, 0))) { char msg[1024]; int len; if (EAGAIN == errno) { return true; } len = snprintf(msg, sizeof(msg) - 1, "Socket error @ %llu.", (unsigned long long)c->id); push_error(c->up, msg, len); agoo_log_cat(&agoo_error_cat, "Socket error @ %llu.", (unsigned long long)c->id); agoo_ws_req_close(c); return false; } c->wcnt += cnt; if (c->wcnt == message->len) { // finished agooText next = agoo_res_message_next(res); c->wcnt = 0; if (NULL == next && res->final) { bool done = res->close; agoo_res_destroy(res); return !done; } } agoo_con_res_prepend(c, res); return true; } static bool con_sse_write(agooCon c) { agooRes res = agoo_con_res_pop(c); agooText message = agoo_res_message_peek(res); ssize_t cnt; if (NULL == message) { agoo_res_destroy(res); return false; } c->timeout = dtime() + CON_TIMEOUT *2; if (0 == c->wcnt) { agooText t; if (agoo_push_cat.on) { agoo_log_cat(&agoo_push_cat, "%llu: %s %p", (unsigned long long)c->id, message->text, (void*)res); } t = agoo_sse_expand(message); if (t != message) { agoo_res_message_push(res, t); message = t; } } if (0 > (cnt = send(c->sock, message->text + c->wcnt, message->len - c->wcnt, 0))) { char msg[1024]; int len; if (EAGAIN == errno) { return true; } len = snprintf(msg, sizeof(msg) - 1, "Socket error @ %llu.", (unsigned long long)c->id); push_error(c->up, msg, len); agoo_log_cat(&agoo_error_cat, "Socket error @ %llu.", (unsigned long long)c->id); return false; } c->wcnt += cnt; if (c->wcnt == message->len) { // finished agooText next = agoo_res_message_next(res); c->wcnt = 0; if (NULL == next) { bool done = res->close; agoo_res_destroy(res); return !done; } } agoo_con_res_prepend(c, res); return true; } static void publish_pub(agooPub pub, agooConLoop loop) { agooUpgraded up; const char *sub = pub->subject->pattern; int cnt = 0; for (up = agoo_server.up_list; NULL != up; up = up->next) { if (NULL != up->con && up->con->loop == loop && agoo_upgraded_match(up, sub)) { agooRes res = agoo_res_create(up->con); if (NULL != res) { agoo_con_res_append(up->con, res); res->con_kind = AGOO_CON_ANY; agoo_res_message_push(res, agoo_text_dup(pub->msg)); cnt++; } } } } static void unsubscribe_pub(agooPub pub) { if (NULL == pub->up) { agooUpgraded up; for (up = agoo_server.up_list; NULL != up; up = up->next) { agoo_upgraded_del_subject(up, pub->subject); } } else { agoo_upgraded_del_subject(pub->up, pub->subject); } } static void process_pub_con(agooPub pub, agooConLoop loop) { agooUpgraded up = pub->up; if (NULL != up && NULL != up->con && up->con->loop == loop) { int pending; // TBD Change pending to be based on length of con queue if (1 == (pending = atomic_fetch_sub(&up->pending, 1))) { if (NULL != up && agoo_server.ctx_nil_value != up->ctx && up->on_empty) { agooReq req = agoo_req_create(0); req->up = up; req->method = AGOO_ON_EMPTY; req->hook = agoo_hook_create(AGOO_NONE, NULL, up->ctx, PUSH_HOOK, &agoo_server.eval_queue); agoo_upgraded_ref(up); agoo_queue_push(&agoo_server.eval_queue, (void*)req); } } } switch (pub->kind) { case AGOO_PUB_CLOSE: // A close after already closed is used to decrement the reference // count on the upgraded so it can be destroyed in the con loop // threads. if (NULL != up->con && up->con->loop == loop) { agooRes res = agoo_res_create(up->con); if (NULL != res) { agoo_con_res_append(up->con, res); res->con_kind = up->con->bind->kind; res->close = true; } } break; case AGOO_PUB_WRITE: { if (NULL == up->con) { agoo_log_cat(&agoo_warn_cat, "Connection already closed. WebSocket write failed."); } else if (up->con->loop == loop) { agooRes res = agoo_res_create(up->con); if (NULL != res) { agoo_con_res_append(up->con, res); res->con_kind = AGOO_CON_ANY; agoo_res_message_push(res, pub->msg); } } break; case AGOO_PUB_SUB: if (NULL != up && up->con->loop == loop) { agoo_upgraded_add_subject(pub->up, pub->subject); pub->subject = NULL; } break; case AGOO_PUB_UN: if (NULL != up && up->con->loop == loop) { unsubscribe_pub(pub); } break; case AGOO_PUB_MSG: publish_pub(pub, loop); break; } default: break; } agoo_pub_destroy(pub); } short agoo_con_http_events(agooCon c) { short events = 0; agooRes res = agoo_con_res_peek(c); if (NULL != res && NULL != res->message) { events = POLLIN | POLLOUT; } else if (!c->closing) { events = POLLIN; } return events; } static short con_ws_events(agooCon c) { short events = 0; agooRes res = agoo_con_res_peek(c); if (NULL != res && (res->close || res->ping || NULL != res->message)) { events = POLLIN | POLLOUT; } else if (!c->closing) { events = POLLIN; } return events; } static short con_sse_events(agooCon c) { short events = 0; agooRes res = agoo_con_res_peek(c); if (NULL != res && NULL != res->message) { events = POLLOUT; } return events; } static bool remove_dead_res(agooCon c) { agooRes res; bool empty; pthread_mutex_lock(&c->res_lock); while (NULL != (res = c->res_head)) { if (NULL == agoo_res_message_peek(c->res_head) && !c->res_head->close && !c->res_head->ping) { break; } c->res_head = res->next; if (res == c->res_tail) { c->res_tail = NULL; } agoo_res_destroy(res); } empty = NULL == c->res_head; pthread_mutex_unlock(&c->res_lock); return empty; } static agooReadyIO con_ready_io(void *ctx) { agooCon c = (agooCon)ctx; if (NULL != c->bind && !c->dead && 0 != c->sock) { switch (c->bind->events(c)) { case POLLIN: return AGOO_READY_IN; case POLLOUT: return AGOO_READY_OUT; case POLLIN | POLLOUT: return AGOO_READY_BOTH; default: break; } } return AGOO_READY_NONE; } // Ready to close check. True if ready to close. static bool con_ready_check(void *ctx, double now) { agooCon c = (agooCon)ctx; if (c->dead || 0 == c->sock) { if (remove_dead_res(c)) { return true; } } else if (0.0 == c->timeout || now < c->timeout) { return false; } else if (c->closing) { if (remove_dead_res(c)) { return true; } } else if (AGOO_CON_WS == c->bind->kind || AGOO_CON_SSE == c->bind->kind) { c->timeout = dtime() + CON_TIMEOUT; if (AGOO_CON_WS == c->bind->kind) { agoo_ws_ping(c); } return false; } else { c->closing = true; c->timeout = now + 0.5; } return false; } static bool con_ready_read(agooReady ready, void *ctx) { agooCon c = (agooCon)ctx; if (NULL != c->bind->read) { if (!c->bind->read(c)) { return true; } } else { return true; // not an error, just ignore } c->dead = true; return false; } static bool con_ready_write(void *ctx) { agooCon c = (agooCon)ctx; agooRes res = agoo_con_res_peek(c); if (NULL != res) { agooConKind kind = res->con_kind; if (NULL != c->bind->write) { if (c->bind->write(c)) { //if (kind != c->kind && AGOO_CON_ANY != kind) { if (AGOO_CON_ANY != kind) { switch (kind) { case AGOO_CON_WS: c->bind = &ws_bind; break; case AGOO_CON_SSE: c->bind = &sse_bind; break; default: break; } } return true; } } } c->dead = true; return false; } static void con_ready_destroy(void *ctx) { agoo_con_destroy((agooCon)ctx); } static void con_ready_error(void *ctx) { ((agooCon)ctx)->dead = true; } static struct _agooHandler con_handler = { .io = con_ready_io, .check = con_ready_check, .read = con_ready_read, .write = con_ready_write, .error = con_ready_error, .destroy = con_ready_destroy, }; static agooReadyIO queue_ready_io(void *ctx) { return AGOO_READY_IN; } static void con_ssl_setup(agooCon c) { #ifdef HAVE_OPENSSL_SSL_H if (NULL == (c->ssl = SSL_new(agoo_server.ssl_ctx))) { con_ssl_error(c, "new SSL", 0, __FILE__, __LINE__); } if (!SSL_set_fd(c->ssl, c->sock)) { con_ssl_error(c, "SSL set fd", 0, __FILE__, __LINE__); } if (!SSL_accept(c->ssl)) { con_ssl_error(c, "SSL accept", 0, __FILE__, __LINE__); } #else agoo_log_cat(&agoo_error_cat, "SSL not included in the build."); c->dead = true; #endif } static bool con_queue_ready_read(agooReady ready, void *ctx) { agooConLoop loop = (agooConLoop)ctx; struct _agooErr err = AGOO_ERR_INIT; agooCon c; agoo_queue_release(&agoo_server.con_queue); while (NULL != (c = (agooCon)agoo_queue_pop(&agoo_server.con_queue, 0.0))) { c->loop = loop; if (AGOO_ERR_OK != agoo_ready_add(&err, ready, c->sock, &con_handler, c)) { agoo_log_cat(&agoo_error_cat, "Failed to add connection to manager. %s", err.msg); agoo_err_clear(&err); } if (AGOO_CON_HTTPS == c->bind->kind) { con_ssl_setup(c); } } return true; } static struct _agooHandler con_queue_handler = { .io = queue_ready_io, .check = NULL, .read = con_queue_ready_read, .write = NULL, .error = NULL, .destroy = NULL, }; static bool pub_queue_ready_read(agooReady ready, void *ctx) { agooConLoop loop = (agooConLoop)ctx; agooPub pub; agoo_queue_release(&loop->pub_queue); while (NULL != (pub = (agooPub)agoo_queue_pop(&loop->pub_queue, 0.0))) { process_pub_con(pub, loop); } return true; } static struct _agooHandler pub_queue_handler = { .io = queue_ready_io, .check = NULL, .read = pub_queue_ready_read, .write = NULL, .error = NULL, .destroy = NULL, }; void* agoo_con_loop(void *x) { agooConLoop loop = (agooConLoop)x; struct _agooErr err = AGOO_ERR_INIT; agooReady ready = agoo_ready_create(&err); agooPub pub; agooCon c; int con_queue_fd = agoo_queue_listen(&agoo_server.con_queue); int pub_queue_fd = agoo_queue_listen(&loop->pub_queue); if (NULL == ready) { agoo_log_cat(&agoo_error_cat, "Failed to create connection manager. %s", err.msg); exit(EXIT_FAILURE); return NULL; } if (AGOO_ERR_OK != agoo_ready_add(&err, ready, con_queue_fd, &con_queue_handler, loop) || AGOO_ERR_OK != agoo_ready_add(&err, ready, pub_queue_fd, &pub_queue_handler, loop)) { agoo_log_cat(&agoo_error_cat, "Failed to add queue connection to manager. %s", err.msg); exit(EXIT_FAILURE); return NULL; } atomic_fetch_add(&agoo_server.running, 1); while (agoo_server.active) { while (NULL != (c = (agooCon)agoo_queue_pop(&agoo_server.con_queue, 0.0))) { c->loop = loop; if (AGOO_ERR_OK != agoo_ready_add(&err, ready, c->sock, &con_handler, c)) { agoo_log_cat(&agoo_error_cat, "Failed to add connection to manager. %s", err.msg); agoo_err_clear(&err); } if (AGOO_CON_HTTPS == c->bind->kind) { con_ssl_setup(c); } } while (NULL != (pub = (agooPub)agoo_queue_pop(&loop->pub_queue, 0.0))) { process_pub_con(pub, loop); } if (AGOO_ERR_OK != agoo_ready_go(&err, ready)) { agoo_log_cat(&agoo_error_cat, "IO error. %s", err.msg); agoo_err_clear(&err); } } agoo_ready_destroy(ready); atomic_fetch_sub(&agoo_server.running, 1); return NULL; } agooConLoop agoo_conloop_create(agooErr err, int id) { agooConLoop loop; if (NULL == (loop = (agooConLoop)AGOO_MALLOC(sizeof(struct _agooConLoop)))) { AGOO_ERR_MEM(err, "connection thread"); } else { int stat; loop->next = NULL; if (AGOO_ERR_OK != agoo_queue_multi_init(err, &loop->pub_queue, 256, true, false)) { AGOO_FREE(loop); return NULL; } loop->id = id; loop->res_head = NULL; loop->res_tail = NULL; if (0 != pthread_mutex_init(&loop->lock, 0)) { AGOO_FREE(loop); agoo_err_no(err, "Failed to initialize loop mutex."); return NULL; } if (0 != (stat = pthread_create(&loop->thread, NULL, agoo_con_loop, loop))) { agoo_err_set(err, stat, "Failed to create connection loop. %s", strerror(stat)); return NULL; } } return loop; } void agoo_conloop_destroy(agooConLoop loop) { agooRes res; agoo_queue_cleanup(&loop->pub_queue); while (NULL != (res = loop->res_head)) { loop->res_head = res->next; AGOO_FREE(res); } AGOO_FREE(loop); }
./CrossVul/dataset_final_sorted/CWE-444/c/bad_4617_1
crossvul-cpp_data_good_1353_0
/* * Copyright (C) Igor Sysoev * Copyright (C) Nginx, Inc. */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> #include <nginx.h> static ngx_int_t ngx_http_send_error_page(ngx_http_request_t *r, ngx_http_err_page_t *err_page); static ngx_int_t ngx_http_send_special_response(ngx_http_request_t *r, ngx_http_core_loc_conf_t *clcf, ngx_uint_t err); static ngx_int_t ngx_http_send_refresh(ngx_http_request_t *r); static u_char ngx_http_error_full_tail[] = "<hr><center>" NGINX_VER "</center>" CRLF "</body>" CRLF "</html>" CRLF ; static u_char ngx_http_error_build_tail[] = "<hr><center>" NGINX_VER_BUILD "</center>" CRLF "</body>" CRLF "</html>" CRLF ; static u_char ngx_http_error_tail[] = "<hr><center>nginx</center>" CRLF "</body>" CRLF "</html>" CRLF ; static u_char ngx_http_msie_padding[] = "<!-- a padding to disable MSIE and Chrome friendly error page -->" CRLF "<!-- a padding to disable MSIE and Chrome friendly error page -->" CRLF "<!-- a padding to disable MSIE and Chrome friendly error page -->" CRLF "<!-- a padding to disable MSIE and Chrome friendly error page -->" CRLF "<!-- a padding to disable MSIE and Chrome friendly error page -->" CRLF "<!-- a padding to disable MSIE and Chrome friendly error page -->" CRLF ; static u_char ngx_http_msie_refresh_head[] = "<html><head><meta http-equiv=\"Refresh\" content=\"0; URL="; static u_char ngx_http_msie_refresh_tail[] = "\"></head><body></body></html>" CRLF; static char ngx_http_error_301_page[] = "<html>" CRLF "<head><title>301 Moved Permanently</title></head>" CRLF "<body>" CRLF "<center><h1>301 Moved Permanently</h1></center>" CRLF ; static char ngx_http_error_302_page[] = "<html>" CRLF "<head><title>302 Found</title></head>" CRLF "<body>" CRLF "<center><h1>302 Found</h1></center>" CRLF ; static char ngx_http_error_303_page[] = "<html>" CRLF "<head><title>303 See Other</title></head>" CRLF "<body>" CRLF "<center><h1>303 See Other</h1></center>" CRLF ; static char ngx_http_error_307_page[] = "<html>" CRLF "<head><title>307 Temporary Redirect</title></head>" CRLF "<body>" CRLF "<center><h1>307 Temporary Redirect</h1></center>" CRLF ; static char ngx_http_error_308_page[] = "<html>" CRLF "<head><title>308 Permanent Redirect</title></head>" CRLF "<body>" CRLF "<center><h1>308 Permanent Redirect</h1></center>" CRLF ; static char ngx_http_error_400_page[] = "<html>" CRLF "<head><title>400 Bad Request</title></head>" CRLF "<body>" CRLF "<center><h1>400 Bad Request</h1></center>" CRLF ; static char ngx_http_error_401_page[] = "<html>" CRLF "<head><title>401 Authorization Required</title></head>" CRLF "<body>" CRLF "<center><h1>401 Authorization Required</h1></center>" CRLF ; static char ngx_http_error_402_page[] = "<html>" CRLF "<head><title>402 Payment Required</title></head>" CRLF "<body>" CRLF "<center><h1>402 Payment Required</h1></center>" CRLF ; static char ngx_http_error_403_page[] = "<html>" CRLF "<head><title>403 Forbidden</title></head>" CRLF "<body>" CRLF "<center><h1>403 Forbidden</h1></center>" CRLF ; static char ngx_http_error_404_page[] = "<html>" CRLF "<head><title>404 Not Found</title></head>" CRLF "<body>" CRLF "<center><h1>404 Not Found</h1></center>" CRLF ; static char ngx_http_error_405_page[] = "<html>" CRLF "<head><title>405 Not Allowed</title></head>" CRLF "<body>" CRLF "<center><h1>405 Not Allowed</h1></center>" CRLF ; static char ngx_http_error_406_page[] = "<html>" CRLF "<head><title>406 Not Acceptable</title></head>" CRLF "<body>" CRLF "<center><h1>406 Not Acceptable</h1></center>" CRLF ; static char ngx_http_error_408_page[] = "<html>" CRLF "<head><title>408 Request Time-out</title></head>" CRLF "<body>" CRLF "<center><h1>408 Request Time-out</h1></center>" CRLF ; static char ngx_http_error_409_page[] = "<html>" CRLF "<head><title>409 Conflict</title></head>" CRLF "<body>" CRLF "<center><h1>409 Conflict</h1></center>" CRLF ; static char ngx_http_error_410_page[] = "<html>" CRLF "<head><title>410 Gone</title></head>" CRLF "<body>" CRLF "<center><h1>410 Gone</h1></center>" CRLF ; static char ngx_http_error_411_page[] = "<html>" CRLF "<head><title>411 Length Required</title></head>" CRLF "<body>" CRLF "<center><h1>411 Length Required</h1></center>" CRLF ; static char ngx_http_error_412_page[] = "<html>" CRLF "<head><title>412 Precondition Failed</title></head>" CRLF "<body>" CRLF "<center><h1>412 Precondition Failed</h1></center>" CRLF ; static char ngx_http_error_413_page[] = "<html>" CRLF "<head><title>413 Request Entity Too Large</title></head>" CRLF "<body>" CRLF "<center><h1>413 Request Entity Too Large</h1></center>" CRLF ; static char ngx_http_error_414_page[] = "<html>" CRLF "<head><title>414 Request-URI Too Large</title></head>" CRLF "<body>" CRLF "<center><h1>414 Request-URI Too Large</h1></center>" CRLF ; static char ngx_http_error_415_page[] = "<html>" CRLF "<head><title>415 Unsupported Media Type</title></head>" CRLF "<body>" CRLF "<center><h1>415 Unsupported Media Type</h1></center>" CRLF ; static char ngx_http_error_416_page[] = "<html>" CRLF "<head><title>416 Requested Range Not Satisfiable</title></head>" CRLF "<body>" CRLF "<center><h1>416 Requested Range Not Satisfiable</h1></center>" CRLF ; static char ngx_http_error_421_page[] = "<html>" CRLF "<head><title>421 Misdirected Request</title></head>" CRLF "<body>" CRLF "<center><h1>421 Misdirected Request</h1></center>" CRLF ; static char ngx_http_error_429_page[] = "<html>" CRLF "<head><title>429 Too Many Requests</title></head>" CRLF "<body>" CRLF "<center><h1>429 Too Many Requests</h1></center>" CRLF ; static char ngx_http_error_494_page[] = "<html>" CRLF "<head><title>400 Request Header Or Cookie Too Large</title></head>" CRLF "<body>" CRLF "<center><h1>400 Bad Request</h1></center>" CRLF "<center>Request Header Or Cookie Too Large</center>" CRLF ; static char ngx_http_error_495_page[] = "<html>" CRLF "<head><title>400 The SSL certificate error</title></head>" CRLF "<body>" CRLF "<center><h1>400 Bad Request</h1></center>" CRLF "<center>The SSL certificate error</center>" CRLF ; static char ngx_http_error_496_page[] = "<html>" CRLF "<head><title>400 No required SSL certificate was sent</title></head>" CRLF "<body>" CRLF "<center><h1>400 Bad Request</h1></center>" CRLF "<center>No required SSL certificate was sent</center>" CRLF ; static char ngx_http_error_497_page[] = "<html>" CRLF "<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>" CRLF "<body>" CRLF "<center><h1>400 Bad Request</h1></center>" CRLF "<center>The plain HTTP request was sent to HTTPS port</center>" CRLF ; static char ngx_http_error_500_page[] = "<html>" CRLF "<head><title>500 Internal Server Error</title></head>" CRLF "<body>" CRLF "<center><h1>500 Internal Server Error</h1></center>" CRLF ; static char ngx_http_error_501_page[] = "<html>" CRLF "<head><title>501 Not Implemented</title></head>" CRLF "<body>" CRLF "<center><h1>501 Not Implemented</h1></center>" CRLF ; static char ngx_http_error_502_page[] = "<html>" CRLF "<head><title>502 Bad Gateway</title></head>" CRLF "<body>" CRLF "<center><h1>502 Bad Gateway</h1></center>" CRLF ; static char ngx_http_error_503_page[] = "<html>" CRLF "<head><title>503 Service Temporarily Unavailable</title></head>" CRLF "<body>" CRLF "<center><h1>503 Service Temporarily Unavailable</h1></center>" CRLF ; static char ngx_http_error_504_page[] = "<html>" CRLF "<head><title>504 Gateway Time-out</title></head>" CRLF "<body>" CRLF "<center><h1>504 Gateway Time-out</h1></center>" CRLF ; static char ngx_http_error_505_page[] = "<html>" CRLF "<head><title>505 HTTP Version Not Supported</title></head>" CRLF "<body>" CRLF "<center><h1>505 HTTP Version Not Supported</h1></center>" CRLF ; static char ngx_http_error_507_page[] = "<html>" CRLF "<head><title>507 Insufficient Storage</title></head>" CRLF "<body>" CRLF "<center><h1>507 Insufficient Storage</h1></center>" CRLF ; static ngx_str_t ngx_http_error_pages[] = { ngx_null_string, /* 201, 204 */ #define NGX_HTTP_LAST_2XX 202 #define NGX_HTTP_OFF_3XX (NGX_HTTP_LAST_2XX - 201) /* ngx_null_string, */ /* 300 */ ngx_string(ngx_http_error_301_page), ngx_string(ngx_http_error_302_page), ngx_string(ngx_http_error_303_page), ngx_null_string, /* 304 */ ngx_null_string, /* 305 */ ngx_null_string, /* 306 */ ngx_string(ngx_http_error_307_page), ngx_string(ngx_http_error_308_page), #define NGX_HTTP_LAST_3XX 309 #define NGX_HTTP_OFF_4XX (NGX_HTTP_LAST_3XX - 301 + NGX_HTTP_OFF_3XX) ngx_string(ngx_http_error_400_page), ngx_string(ngx_http_error_401_page), ngx_string(ngx_http_error_402_page), ngx_string(ngx_http_error_403_page), ngx_string(ngx_http_error_404_page), ngx_string(ngx_http_error_405_page), ngx_string(ngx_http_error_406_page), ngx_null_string, /* 407 */ ngx_string(ngx_http_error_408_page), ngx_string(ngx_http_error_409_page), ngx_string(ngx_http_error_410_page), ngx_string(ngx_http_error_411_page), ngx_string(ngx_http_error_412_page), ngx_string(ngx_http_error_413_page), ngx_string(ngx_http_error_414_page), ngx_string(ngx_http_error_415_page), ngx_string(ngx_http_error_416_page), ngx_null_string, /* 417 */ ngx_null_string, /* 418 */ ngx_null_string, /* 419 */ ngx_null_string, /* 420 */ ngx_string(ngx_http_error_421_page), ngx_null_string, /* 422 */ ngx_null_string, /* 423 */ ngx_null_string, /* 424 */ ngx_null_string, /* 425 */ ngx_null_string, /* 426 */ ngx_null_string, /* 427 */ ngx_null_string, /* 428 */ ngx_string(ngx_http_error_429_page), #define NGX_HTTP_LAST_4XX 430 #define NGX_HTTP_OFF_5XX (NGX_HTTP_LAST_4XX - 400 + NGX_HTTP_OFF_4XX) ngx_string(ngx_http_error_494_page), /* 494, request header too large */ ngx_string(ngx_http_error_495_page), /* 495, https certificate error */ ngx_string(ngx_http_error_496_page), /* 496, https no certificate */ ngx_string(ngx_http_error_497_page), /* 497, http to https */ ngx_string(ngx_http_error_404_page), /* 498, canceled */ ngx_null_string, /* 499, client has closed connection */ ngx_string(ngx_http_error_500_page), ngx_string(ngx_http_error_501_page), ngx_string(ngx_http_error_502_page), ngx_string(ngx_http_error_503_page), ngx_string(ngx_http_error_504_page), ngx_string(ngx_http_error_505_page), ngx_null_string, /* 506 */ ngx_string(ngx_http_error_507_page) #define NGX_HTTP_LAST_5XX 508 }; ngx_int_t ngx_http_special_response_handler(ngx_http_request_t *r, ngx_int_t error) { ngx_uint_t i, err; ngx_http_err_page_t *err_page; ngx_http_core_loc_conf_t *clcf; ngx_log_debug3(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "http special response: %i, \"%V?%V\"", error, &r->uri, &r->args); r->err_status = error; if (r->keepalive) { switch (error) { case NGX_HTTP_BAD_REQUEST: case NGX_HTTP_REQUEST_ENTITY_TOO_LARGE: case NGX_HTTP_REQUEST_URI_TOO_LARGE: case NGX_HTTP_TO_HTTPS: case NGX_HTTPS_CERT_ERROR: case NGX_HTTPS_NO_CERT: case NGX_HTTP_INTERNAL_SERVER_ERROR: case NGX_HTTP_NOT_IMPLEMENTED: r->keepalive = 0; } } if (r->lingering_close) { switch (error) { case NGX_HTTP_BAD_REQUEST: case NGX_HTTP_TO_HTTPS: case NGX_HTTPS_CERT_ERROR: case NGX_HTTPS_NO_CERT: r->lingering_close = 0; } } r->headers_out.content_type.len = 0; clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); if (!r->error_page && clcf->error_pages && r->uri_changes != 0) { if (clcf->recursive_error_pages == 0) { r->error_page = 1; } err_page = clcf->error_pages->elts; for (i = 0; i < clcf->error_pages->nelts; i++) { if (err_page[i].status == error) { return ngx_http_send_error_page(r, &err_page[i]); } } } r->expect_tested = 1; if (ngx_http_discard_request_body(r) != NGX_OK) { r->keepalive = 0; } if (clcf->msie_refresh && r->headers_in.msie && (error == NGX_HTTP_MOVED_PERMANENTLY || error == NGX_HTTP_MOVED_TEMPORARILY)) { return ngx_http_send_refresh(r); } if (error == NGX_HTTP_CREATED) { /* 201 */ err = 0; } else if (error == NGX_HTTP_NO_CONTENT) { /* 204 */ err = 0; } else if (error >= NGX_HTTP_MOVED_PERMANENTLY && error < NGX_HTTP_LAST_3XX) { /* 3XX */ err = error - NGX_HTTP_MOVED_PERMANENTLY + NGX_HTTP_OFF_3XX; } else if (error >= NGX_HTTP_BAD_REQUEST && error < NGX_HTTP_LAST_4XX) { /* 4XX */ err = error - NGX_HTTP_BAD_REQUEST + NGX_HTTP_OFF_4XX; } else if (error >= NGX_HTTP_NGINX_CODES && error < NGX_HTTP_LAST_5XX) { /* 49X, 5XX */ err = error - NGX_HTTP_NGINX_CODES + NGX_HTTP_OFF_5XX; switch (error) { case NGX_HTTP_TO_HTTPS: case NGX_HTTPS_CERT_ERROR: case NGX_HTTPS_NO_CERT: case NGX_HTTP_REQUEST_HEADER_TOO_LARGE: r->err_status = NGX_HTTP_BAD_REQUEST; } } else { /* unknown code, zero body */ err = 0; } return ngx_http_send_special_response(r, clcf, err); } ngx_int_t ngx_http_filter_finalize_request(ngx_http_request_t *r, ngx_module_t *m, ngx_int_t error) { void *ctx; ngx_int_t rc; ngx_http_clean_header(r); ctx = NULL; if (m) { ctx = r->ctx[m->ctx_index]; } /* clear the modules contexts */ ngx_memzero(r->ctx, sizeof(void *) * ngx_http_max_module); if (m) { r->ctx[m->ctx_index] = ctx; } r->filter_finalize = 1; rc = ngx_http_special_response_handler(r, error); /* NGX_ERROR resets any pending data */ switch (rc) { case NGX_OK: case NGX_DONE: return NGX_ERROR; default: return rc; } } void ngx_http_clean_header(ngx_http_request_t *r) { ngx_memzero(&r->headers_out.status, sizeof(ngx_http_headers_out_t) - offsetof(ngx_http_headers_out_t, status)); r->headers_out.headers.part.nelts = 0; r->headers_out.headers.part.next = NULL; r->headers_out.headers.last = &r->headers_out.headers.part; r->headers_out.content_length_n = -1; r->headers_out.last_modified_time = -1; } static ngx_int_t ngx_http_send_error_page(ngx_http_request_t *r, ngx_http_err_page_t *err_page) { ngx_int_t overwrite; ngx_str_t uri, args; ngx_table_elt_t *location; ngx_http_core_loc_conf_t *clcf; overwrite = err_page->overwrite; if (overwrite && overwrite != NGX_HTTP_OK) { r->expect_tested = 1; } if (overwrite >= 0) { r->err_status = overwrite; } if (ngx_http_complex_value(r, &err_page->value, &uri) != NGX_OK) { return NGX_ERROR; } if (uri.len && uri.data[0] == '/') { if (err_page->value.lengths) { ngx_http_split_args(r, &uri, &args); } else { args = err_page->args; } if (r->method != NGX_HTTP_HEAD) { r->method = NGX_HTTP_GET; r->method_name = ngx_http_core_get_method; } return ngx_http_internal_redirect(r, &uri, &args); } if (uri.len && uri.data[0] == '@') { return ngx_http_named_location(r, &uri); } r->expect_tested = 1; if (ngx_http_discard_request_body(r) != NGX_OK) { r->keepalive = 0; } location = ngx_list_push(&r->headers_out.headers); if (location == NULL) { return NGX_ERROR; } if (overwrite != NGX_HTTP_MOVED_PERMANENTLY && overwrite != NGX_HTTP_MOVED_TEMPORARILY && overwrite != NGX_HTTP_SEE_OTHER && overwrite != NGX_HTTP_TEMPORARY_REDIRECT && overwrite != NGX_HTTP_PERMANENT_REDIRECT) { r->err_status = NGX_HTTP_MOVED_TEMPORARILY; } location->hash = 1; ngx_str_set(&location->key, "Location"); location->value = uri; ngx_http_clear_location(r); r->headers_out.location = location; clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); if (clcf->msie_refresh && r->headers_in.msie) { return ngx_http_send_refresh(r); } return ngx_http_send_special_response(r, clcf, r->err_status - NGX_HTTP_MOVED_PERMANENTLY + NGX_HTTP_OFF_3XX); } static ngx_int_t ngx_http_send_special_response(ngx_http_request_t *r, ngx_http_core_loc_conf_t *clcf, ngx_uint_t err) { u_char *tail; size_t len; ngx_int_t rc; ngx_buf_t *b; ngx_uint_t msie_padding; ngx_chain_t out[3]; if (clcf->server_tokens == NGX_HTTP_SERVER_TOKENS_ON) { len = sizeof(ngx_http_error_full_tail) - 1; tail = ngx_http_error_full_tail; } else if (clcf->server_tokens == NGX_HTTP_SERVER_TOKENS_BUILD) { len = sizeof(ngx_http_error_build_tail) - 1; tail = ngx_http_error_build_tail; } else { len = sizeof(ngx_http_error_tail) - 1; tail = ngx_http_error_tail; } msie_padding = 0; if (ngx_http_error_pages[err].len) { r->headers_out.content_length_n = ngx_http_error_pages[err].len + len; if (clcf->msie_padding && (r->headers_in.msie || r->headers_in.chrome) && r->http_version >= NGX_HTTP_VERSION_10 && err >= NGX_HTTP_OFF_4XX) { r->headers_out.content_length_n += sizeof(ngx_http_msie_padding) - 1; msie_padding = 1; } r->headers_out.content_type_len = sizeof("text/html") - 1; ngx_str_set(&r->headers_out.content_type, "text/html"); r->headers_out.content_type_lowcase = NULL; } else { r->headers_out.content_length_n = 0; } if (r->headers_out.content_length) { r->headers_out.content_length->hash = 0; r->headers_out.content_length = NULL; } ngx_http_clear_accept_ranges(r); ngx_http_clear_last_modified(r); ngx_http_clear_etag(r); rc = ngx_http_send_header(r); if (rc == NGX_ERROR || r->header_only) { return rc; } if (ngx_http_error_pages[err].len == 0) { return ngx_http_send_special(r, NGX_HTTP_LAST); } b = ngx_calloc_buf(r->pool); if (b == NULL) { return NGX_ERROR; } b->memory = 1; b->pos = ngx_http_error_pages[err].data; b->last = ngx_http_error_pages[err].data + ngx_http_error_pages[err].len; out[0].buf = b; out[0].next = &out[1]; b = ngx_calloc_buf(r->pool); if (b == NULL) { return NGX_ERROR; } b->memory = 1; b->pos = tail; b->last = tail + len; out[1].buf = b; out[1].next = NULL; if (msie_padding) { b = ngx_calloc_buf(r->pool); if (b == NULL) { return NGX_ERROR; } b->memory = 1; b->pos = ngx_http_msie_padding; b->last = ngx_http_msie_padding + sizeof(ngx_http_msie_padding) - 1; out[1].next = &out[2]; out[2].buf = b; out[2].next = NULL; } if (r == r->main) { b->last_buf = 1; } b->last_in_chain = 1; return ngx_http_output_filter(r, &out[0]); } static ngx_int_t ngx_http_send_refresh(ngx_http_request_t *r) { u_char *p, *location; size_t len, size; uintptr_t escape; ngx_int_t rc; ngx_buf_t *b; ngx_chain_t out; len = r->headers_out.location->value.len; location = r->headers_out.location->value.data; escape = 2 * ngx_escape_uri(NULL, location, len, NGX_ESCAPE_REFRESH); size = sizeof(ngx_http_msie_refresh_head) - 1 + escape + len + sizeof(ngx_http_msie_refresh_tail) - 1; r->err_status = NGX_HTTP_OK; r->headers_out.content_type_len = sizeof("text/html") - 1; ngx_str_set(&r->headers_out.content_type, "text/html"); r->headers_out.content_type_lowcase = NULL; r->headers_out.location->hash = 0; r->headers_out.location = NULL; r->headers_out.content_length_n = size; if (r->headers_out.content_length) { r->headers_out.content_length->hash = 0; r->headers_out.content_length = NULL; } ngx_http_clear_accept_ranges(r); ngx_http_clear_last_modified(r); ngx_http_clear_etag(r); rc = ngx_http_send_header(r); if (rc == NGX_ERROR || r->header_only) { return rc; } b = ngx_create_temp_buf(r->pool, size); if (b == NULL) { return NGX_ERROR; } p = ngx_cpymem(b->pos, ngx_http_msie_refresh_head, sizeof(ngx_http_msie_refresh_head) - 1); if (escape == 0) { p = ngx_cpymem(p, location, len); } else { p = (u_char *) ngx_escape_uri(p, location, len, NGX_ESCAPE_REFRESH); } b->last = ngx_cpymem(p, ngx_http_msie_refresh_tail, sizeof(ngx_http_msie_refresh_tail) - 1); b->last_buf = (r == r->main) ? 1 : 0; b->last_in_chain = 1; out.buf = b; out.next = NULL; return ngx_http_output_filter(r, &out); }
./CrossVul/dataset_final_sorted/CWE-444/c/good_1353_0
crossvul-cpp_data_bad_3969_0
/* * Copyright (C) Xiaozhe Wang (chaoslawful) * Copyright (C) Yichun Zhang (agentzh) */ #ifndef DDEBUG #define DDEBUG 0 #endif #include "ddebug.h" #include "ngx_http_lua_subrequest.h" #include "ngx_http_lua_util.h" #include "ngx_http_lua_ctx.h" #include "ngx_http_lua_contentby.h" #include "ngx_http_lua_headers_in.h" #if defined(NGX_DTRACE) && NGX_DTRACE #include "ngx_http_probe.h" #endif #define NGX_HTTP_LUA_SHARE_ALL_VARS 0x01 #define NGX_HTTP_LUA_COPY_ALL_VARS 0x02 #define ngx_http_lua_method_name(m) { sizeof(m) - 1, (u_char *) m " " } ngx_str_t ngx_http_lua_get_method = ngx_http_lua_method_name("GET"); ngx_str_t ngx_http_lua_put_method = ngx_http_lua_method_name("PUT"); ngx_str_t ngx_http_lua_post_method = ngx_http_lua_method_name("POST"); ngx_str_t ngx_http_lua_head_method = ngx_http_lua_method_name("HEAD"); ngx_str_t ngx_http_lua_delete_method = ngx_http_lua_method_name("DELETE"); ngx_str_t ngx_http_lua_options_method = ngx_http_lua_method_name("OPTIONS"); ngx_str_t ngx_http_lua_copy_method = ngx_http_lua_method_name("COPY"); ngx_str_t ngx_http_lua_move_method = ngx_http_lua_method_name("MOVE"); ngx_str_t ngx_http_lua_lock_method = ngx_http_lua_method_name("LOCK"); ngx_str_t ngx_http_lua_mkcol_method = ngx_http_lua_method_name("MKCOL"); ngx_str_t ngx_http_lua_propfind_method = ngx_http_lua_method_name("PROPFIND"); ngx_str_t ngx_http_lua_proppatch_method = ngx_http_lua_method_name("PROPPATCH"); ngx_str_t ngx_http_lua_unlock_method = ngx_http_lua_method_name("UNLOCK"); ngx_str_t ngx_http_lua_patch_method = ngx_http_lua_method_name("PATCH"); ngx_str_t ngx_http_lua_trace_method = ngx_http_lua_method_name("TRACE"); static ngx_str_t ngx_http_lua_content_length_header_key = ngx_string("Content-Length"); static ngx_int_t ngx_http_lua_set_content_length_header(ngx_http_request_t *r, off_t len); static ngx_int_t ngx_http_lua_adjust_subrequest(ngx_http_request_t *sr, ngx_uint_t method, int forward_body, ngx_http_request_body_t *body, unsigned vars_action, ngx_array_t *extra_vars); static int ngx_http_lua_ngx_location_capture(lua_State *L); static int ngx_http_lua_ngx_location_capture_multi(lua_State *L); static void ngx_http_lua_process_vars_option(ngx_http_request_t *r, lua_State *L, int table, ngx_array_t **varsp); static ngx_int_t ngx_http_lua_subrequest_add_extra_vars(ngx_http_request_t *r, ngx_array_t *extra_vars); static ngx_int_t ngx_http_lua_subrequest(ngx_http_request_t *r, ngx_str_t *uri, ngx_str_t *args, ngx_http_request_t **psr, ngx_http_post_subrequest_t *ps, ngx_uint_t flags); static ngx_int_t ngx_http_lua_subrequest_resume(ngx_http_request_t *r); static void ngx_http_lua_handle_subreq_responses(ngx_http_request_t *r, ngx_http_lua_ctx_t *ctx); static void ngx_http_lua_cancel_subreq(ngx_http_request_t *r); static ngx_int_t ngx_http_post_request_to_head(ngx_http_request_t *r); static ngx_int_t ngx_http_lua_copy_in_file_request_body(ngx_http_request_t *r); static ngx_int_t ngx_http_lua_copy_request_headers(ngx_http_request_t *sr, ngx_http_request_t *r); enum { NGX_HTTP_LUA_SUBREQ_TRUNCATED = 1, }; /* ngx.location.capture is just a thin wrapper around * ngx.location.capture_multi */ static int ngx_http_lua_ngx_location_capture(lua_State *L) { int n; n = lua_gettop(L); if (n != 1 && n != 2) { return luaL_error(L, "expecting one or two arguments"); } lua_createtable(L, n, 0); /* uri opts? table */ lua_insert(L, 1); /* table uri opts? */ if (n == 1) { /* table uri */ lua_rawseti(L, 1, 1); /* table */ } else { /* table uri opts */ lua_rawseti(L, 1, 2); /* table uri */ lua_rawseti(L, 1, 1); /* table */ } lua_createtable(L, 1, 0); /* table table' */ lua_insert(L, 1); /* table' table */ lua_rawseti(L, 1, 1); /* table' */ return ngx_http_lua_ngx_location_capture_multi(L); } static int ngx_http_lua_ngx_location_capture_multi(lua_State *L) { ngx_http_request_t *r; ngx_http_request_t *sr = NULL; /* subrequest object */ ngx_http_post_subrequest_t *psr; ngx_http_lua_ctx_t *sr_ctx; ngx_http_lua_ctx_t *ctx; ngx_array_t *extra_vars; ngx_str_t uri; ngx_str_t args; ngx_str_t extra_args; ngx_uint_t flags; u_char *p; u_char *q; size_t len; size_t nargs; int rc; int n; int always_forward_body = 0; ngx_uint_t method; ngx_http_request_body_t *body; int type; ngx_buf_t *b; unsigned vars_action; ngx_uint_t nsubreqs; ngx_uint_t index; size_t sr_statuses_len; size_t sr_headers_len; size_t sr_bodies_len; size_t sr_flags_len; size_t ofs1, ofs2; unsigned custom_ctx; ngx_http_lua_co_ctx_t *coctx; ngx_http_lua_post_subrequest_data_t *psr_data; n = lua_gettop(L); if (n != 1) { return luaL_error(L, "only one argument is expected, but got %d", n); } luaL_checktype(L, 1, LUA_TTABLE); nsubreqs = lua_objlen(L, 1); if (nsubreqs == 0) { return luaL_error(L, "at least one subrequest should be specified"); } r = ngx_http_lua_get_req(L); if (r == NULL) { return luaL_error(L, "no request object found"); } #if (NGX_HTTP_V2) if (r->main->stream) { return luaL_error(L, "http2 requests not supported yet"); } #endif ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); if (ctx == NULL) { return luaL_error(L, "no ctx found"); } ngx_http_lua_check_context(L, ctx, NGX_HTTP_LUA_CONTEXT_REWRITE | NGX_HTTP_LUA_CONTEXT_ACCESS | NGX_HTTP_LUA_CONTEXT_CONTENT); coctx = ctx->cur_co_ctx; if (coctx == NULL) { return luaL_error(L, "no co ctx found"); } ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua location capture, uri:\"%V\" c:%ud", &r->uri, r->main->count); sr_statuses_len = nsubreqs * sizeof(ngx_int_t); sr_headers_len = nsubreqs * sizeof(ngx_http_headers_out_t *); sr_bodies_len = nsubreqs * sizeof(ngx_str_t); sr_flags_len = nsubreqs * sizeof(uint8_t); p = ngx_pcalloc(r->pool, sr_statuses_len + sr_headers_len + sr_bodies_len + sr_flags_len); if (p == NULL) { return luaL_error(L, "no memory"); } coctx->sr_statuses = (void *) p; p += sr_statuses_len; coctx->sr_headers = (void *) p; p += sr_headers_len; coctx->sr_bodies = (void *) p; p += sr_bodies_len; coctx->sr_flags = (void *) p; coctx->nsubreqs = nsubreqs; coctx->pending_subreqs = 0; extra_vars = NULL; for (index = 0; index < nsubreqs; index++) { coctx->pending_subreqs++; lua_rawgeti(L, 1, index + 1); if (lua_isnil(L, -1)) { return luaL_error(L, "only array-like tables are allowed"); } dd("queries query: top %d", lua_gettop(L)); if (lua_type(L, -1) != LUA_TTABLE) { return luaL_error(L, "the query argument %d is not a table, " "but a %s", index, lua_typename(L, lua_type(L, -1))); } nargs = lua_objlen(L, -1); if (nargs != 1 && nargs != 2) { return luaL_error(L, "query argument %d expecting one or " "two arguments", index); } lua_rawgeti(L, 2, 1); /* queries query uri */ dd("queries query uri: %d", lua_gettop(L)); dd("first arg in first query: %s", lua_typename(L, lua_type(L, -1))); body = NULL; ngx_str_null(&extra_args); if (extra_vars != NULL) { /* flush out existing elements in the array */ extra_vars->nelts = 0; } vars_action = 0; custom_ctx = 0; if (nargs == 2) { /* check out the options table */ lua_rawgeti(L, 2, 2); /* queries query uri opts */ dd("queries query uri opts: %d", lua_gettop(L)); if (lua_type(L, 4) != LUA_TTABLE) { return luaL_error(L, "expecting table as the 2nd argument for " "subrequest %d, but got %s", index, luaL_typename(L, 4)); } dd("queries query uri opts: %d", lua_gettop(L)); /* check the args option */ lua_getfield(L, 4, "args"); type = lua_type(L, -1); switch (type) { case LUA_TTABLE: ngx_http_lua_process_args_option(r, L, -1, &extra_args); break; case LUA_TNIL: /* do nothing */ break; case LUA_TNUMBER: case LUA_TSTRING: extra_args.data = (u_char *) lua_tolstring(L, -1, &len); extra_args.len = len; break; default: return luaL_error(L, "Bad args option value"); } lua_pop(L, 1); dd("queries query uri opts: %d", lua_gettop(L)); /* check the vars option */ lua_getfield(L, 4, "vars"); switch (lua_type(L, -1)) { case LUA_TTABLE: ngx_http_lua_process_vars_option(r, L, -1, &extra_vars); dd("post process vars top: %d", lua_gettop(L)); break; case LUA_TNIL: /* do nothing */ break; default: return luaL_error(L, "Bad vars option value"); } lua_pop(L, 1); dd("queries query uri opts: %d", lua_gettop(L)); /* check the share_all_vars option */ lua_getfield(L, 4, "share_all_vars"); switch (lua_type(L, -1)) { case LUA_TNIL: /* do nothing */ break; case LUA_TBOOLEAN: if (lua_toboolean(L, -1)) { vars_action |= NGX_HTTP_LUA_SHARE_ALL_VARS; } break; default: return luaL_error(L, "Bad share_all_vars option value"); } lua_pop(L, 1); dd("queries query uri opts: %d", lua_gettop(L)); /* check the copy_all_vars option */ lua_getfield(L, 4, "copy_all_vars"); switch (lua_type(L, -1)) { case LUA_TNIL: /* do nothing */ break; case LUA_TBOOLEAN: if (lua_toboolean(L, -1)) { vars_action |= NGX_HTTP_LUA_COPY_ALL_VARS; } break; default: return luaL_error(L, "Bad copy_all_vars option value"); } lua_pop(L, 1); dd("queries query uri opts: %d", lua_gettop(L)); /* check the "forward_body" option */ lua_getfield(L, 4, "always_forward_body"); always_forward_body = lua_toboolean(L, -1); lua_pop(L, 1); dd("always forward body: %d", always_forward_body); /* check the "method" option */ lua_getfield(L, 4, "method"); type = lua_type(L, -1); if (type == LUA_TNIL) { method = NGX_HTTP_GET; } else { if (type != LUA_TNUMBER) { return luaL_error(L, "Bad http request method"); } method = (ngx_uint_t) lua_tonumber(L, -1); } lua_pop(L, 1); dd("queries query uri opts: %d", lua_gettop(L)); /* check the "ctx" option */ lua_getfield(L, 4, "ctx"); type = lua_type(L, -1); if (type != LUA_TNIL) { if (type != LUA_TTABLE) { return luaL_error(L, "Bad ctx option value type %s, " "expected a Lua table", lua_typename(L, type)); } custom_ctx = 1; } else { lua_pop(L, 1); } dd("queries query uri opts ctx?: %d", lua_gettop(L)); /* check the "body" option */ lua_getfield(L, 4, "body"); type = lua_type(L, -1); if (type != LUA_TNIL) { if (type != LUA_TSTRING && type != LUA_TNUMBER) { return luaL_error(L, "Bad http request body"); } body = ngx_pcalloc(r->pool, sizeof(ngx_http_request_body_t)); if (body == NULL) { return luaL_error(L, "no memory"); } q = (u_char *) lua_tolstring(L, -1, &len); dd("request body: [%.*s]", (int) len, q); if (len) { b = ngx_create_temp_buf(r->pool, len); if (b == NULL) { return luaL_error(L, "no memory"); } b->last = ngx_copy(b->last, q, len); body->bufs = ngx_alloc_chain_link(r->pool); if (body->bufs == NULL) { return luaL_error(L, "no memory"); } body->bufs->buf = b; body->bufs->next = NULL; body->buf = b; } } lua_pop(L, 1); /* pop the body */ /* stack: queries query uri opts ctx? */ lua_remove(L, 4); /* stack: queries query uri ctx? */ dd("queries query uri ctx?: %d", lua_gettop(L)); } else { method = NGX_HTTP_GET; } /* stack: queries query uri ctx? */ p = (u_char *) luaL_checklstring(L, 3, &len); uri.data = ngx_palloc(r->pool, len); if (uri.data == NULL) { return luaL_error(L, "memory allocation error"); } ngx_memcpy(uri.data, p, len); uri.len = len; ngx_str_null(&args); flags = 0; rc = ngx_http_parse_unsafe_uri(r, &uri, &args, &flags); if (rc != NGX_OK) { dd("rc = %d", (int) rc); return luaL_error(L, "unsafe uri in argument #1: %s", p); } if (args.len == 0) { if (extra_args.len) { p = ngx_palloc(r->pool, extra_args.len); if (p == NULL) { return luaL_error(L, "no memory"); } ngx_memcpy(p, extra_args.data, extra_args.len); args.data = p; args.len = extra_args.len; } } else if (extra_args.len) { /* concatenate the two parts of args together */ len = args.len + (sizeof("&") - 1) + extra_args.len; p = ngx_palloc(r->pool, len); if (p == NULL) { return luaL_error(L, "no memory"); } q = ngx_copy(p, args.data, args.len); *q++ = '&'; ngx_memcpy(q, extra_args.data, extra_args.len); args.data = p; args.len = len; } ofs1 = ngx_align(sizeof(ngx_http_post_subrequest_t), sizeof(void *)); ofs2 = ngx_align(sizeof(ngx_http_lua_ctx_t), sizeof(void *)); p = ngx_palloc(r->pool, ofs1 + ofs2 + sizeof(ngx_http_lua_post_subrequest_data_t)); if (p == NULL) { return luaL_error(L, "no memory"); } psr = (ngx_http_post_subrequest_t *) p; p += ofs1; sr_ctx = (ngx_http_lua_ctx_t *) p; ngx_http_lua_assert((void *) sr_ctx == ngx_align_ptr(sr_ctx, sizeof(void *))); p += ofs2; psr_data = (ngx_http_lua_post_subrequest_data_t *) p; ngx_http_lua_assert((void *) psr_data == ngx_align_ptr(psr_data, sizeof(void *))); ngx_memzero(sr_ctx, sizeof(ngx_http_lua_ctx_t)); /* set by ngx_memzero: * sr_ctx->run_post_subrequest = 0 * sr_ctx->free = NULL * sr_ctx->body = NULL */ psr_data->ctx = sr_ctx; psr_data->pr_co_ctx = coctx; psr->handler = ngx_http_lua_post_subrequest; psr->data = psr_data; rc = ngx_http_lua_subrequest(r, &uri, &args, &sr, psr, 0); if (rc != NGX_OK) { return luaL_error(L, "failed to issue subrequest: %d", (int) rc); } ngx_http_lua_init_ctx(sr, sr_ctx); sr_ctx->capture = 1; sr_ctx->index = index; sr_ctx->last_body = &sr_ctx->body; sr_ctx->vm_state = ctx->vm_state; ngx_http_set_ctx(sr, sr_ctx, ngx_http_lua_module); rc = ngx_http_lua_adjust_subrequest(sr, method, always_forward_body, body, vars_action, extra_vars); if (rc != NGX_OK) { ngx_http_lua_cancel_subreq(sr); return luaL_error(L, "failed to adjust the subrequest: %d", (int) rc); } dd("queries query uri opts ctx? %d", lua_gettop(L)); /* stack: queries query uri ctx? */ if (custom_ctx) { ngx_http_lua_ngx_set_ctx_helper(L, sr, sr_ctx, -1); lua_pop(L, 3); } else { lua_pop(L, 2); } /* stack: queries */ } if (extra_vars) { ngx_array_destroy(extra_vars); } ctx->no_abort = 1; return lua_yield(L, 0); } static ngx_int_t ngx_http_lua_adjust_subrequest(ngx_http_request_t *sr, ngx_uint_t method, int always_forward_body, ngx_http_request_body_t *body, unsigned vars_action, ngx_array_t *extra_vars) { ngx_http_request_t *r; ngx_int_t rc; ngx_http_core_main_conf_t *cmcf; size_t size; r = sr->parent; sr->header_in = r->header_in; if (body) { sr->request_body = body; rc = ngx_http_lua_set_content_length_header(sr, body->buf ? ngx_buf_size(body->buf) : 0); if (rc != NGX_OK) { return NGX_ERROR; } } else if (!always_forward_body && method != NGX_HTTP_PUT && method != NGX_HTTP_POST && r->headers_in.content_length_n > 0) { rc = ngx_http_lua_set_content_length_header(sr, 0); if (rc != NGX_OK) { return NGX_ERROR; } #if 1 sr->request_body = NULL; #endif } else { if (ngx_http_lua_copy_request_headers(sr, r) != NGX_OK) { return NGX_ERROR; } if (sr->request_body) { /* deep-copy the request body */ if (sr->request_body->temp_file) { if (ngx_http_lua_copy_in_file_request_body(sr) != NGX_OK) { return NGX_ERROR; } } } } sr->method = method; switch (method) { case NGX_HTTP_GET: sr->method_name = ngx_http_lua_get_method; break; case NGX_HTTP_POST: sr->method_name = ngx_http_lua_post_method; break; case NGX_HTTP_PUT: sr->method_name = ngx_http_lua_put_method; break; case NGX_HTTP_HEAD: sr->method_name = ngx_http_lua_head_method; break; case NGX_HTTP_DELETE: sr->method_name = ngx_http_lua_delete_method; break; case NGX_HTTP_OPTIONS: sr->method_name = ngx_http_lua_options_method; break; case NGX_HTTP_MKCOL: sr->method_name = ngx_http_lua_mkcol_method; break; case NGX_HTTP_COPY: sr->method_name = ngx_http_lua_copy_method; break; case NGX_HTTP_MOVE: sr->method_name = ngx_http_lua_move_method; break; case NGX_HTTP_PROPFIND: sr->method_name = ngx_http_lua_propfind_method; break; case NGX_HTTP_PROPPATCH: sr->method_name = ngx_http_lua_proppatch_method; break; case NGX_HTTP_LOCK: sr->method_name = ngx_http_lua_lock_method; break; case NGX_HTTP_UNLOCK: sr->method_name = ngx_http_lua_unlock_method; break; case NGX_HTTP_PATCH: sr->method_name = ngx_http_lua_patch_method; break; case NGX_HTTP_TRACE: sr->method_name = ngx_http_lua_trace_method; break; default: ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "unsupported HTTP method: %u", (unsigned) method); return NGX_ERROR; } if (!(vars_action & NGX_HTTP_LUA_SHARE_ALL_VARS)) { /* we do not inherit the parent request's variables */ cmcf = ngx_http_get_module_main_conf(sr, ngx_http_core_module); size = cmcf->variables.nelts * sizeof(ngx_http_variable_value_t); if (vars_action & NGX_HTTP_LUA_COPY_ALL_VARS) { sr->variables = ngx_palloc(sr->pool, size); if (sr->variables == NULL) { return NGX_ERROR; } ngx_memcpy(sr->variables, r->variables, size); } else { /* we do not inherit the parent request's variables */ sr->variables = ngx_pcalloc(sr->pool, size); if (sr->variables == NULL) { return NGX_ERROR; } } } return ngx_http_lua_subrequest_add_extra_vars(sr, extra_vars); } static ngx_int_t ngx_http_lua_subrequest_add_extra_vars(ngx_http_request_t *sr, ngx_array_t *extra_vars) { ngx_http_core_main_conf_t *cmcf; ngx_http_variable_t *v; ngx_http_variable_value_t *vv; u_char *val; u_char *p; ngx_uint_t i, hash; ngx_str_t name; size_t len; ngx_hash_t *variables_hash; ngx_keyval_t *var; /* set any extra variables that were passed to the subrequest */ if (extra_vars == NULL || extra_vars->nelts == 0) { return NGX_OK; } cmcf = ngx_http_get_module_main_conf(sr, ngx_http_core_module); variables_hash = &cmcf->variables_hash; var = extra_vars->elts; for (i = 0; i < extra_vars->nelts; i++, var++) { /* copy the variable's name and value because they are allocated * by the lua VM */ len = var->key.len + var->value.len; p = ngx_pnalloc(sr->pool, len); if (p == NULL) { return NGX_ERROR; } name.data = p; name.len = var->key.len; p = ngx_copy(p, var->key.data, var->key.len); hash = ngx_hash_strlow(name.data, name.data, name.len); val = p; len = var->value.len; ngx_memcpy(p, var->value.data, len); v = ngx_hash_find(variables_hash, hash, name.data, name.len); if (v) { if (!(v->flags & NGX_HTTP_VAR_CHANGEABLE)) { ngx_log_error(NGX_LOG_ERR, sr->connection->log, 0, "variable \"%V\" not changeable", &name); return NGX_HTTP_INTERNAL_SERVER_ERROR; } if (v->set_handler) { vv = ngx_palloc(sr->pool, sizeof(ngx_http_variable_value_t)); if (vv == NULL) { return NGX_ERROR; } vv->valid = 1; vv->not_found = 0; vv->no_cacheable = 0; vv->data = val; vv->len = len; v->set_handler(sr, vv, v->data); ngx_log_debug2(NGX_LOG_DEBUG_HTTP, sr->connection->log, 0, "variable \"%V\" set to value \"%v\"", &name, vv); continue; } if (v->flags & NGX_HTTP_VAR_INDEXED) { vv = &sr->variables[v->index]; vv->valid = 1; vv->not_found = 0; vv->no_cacheable = 0; vv->data = val; vv->len = len; ngx_log_debug2(NGX_LOG_DEBUG_HTTP, sr->connection->log, 0, "variable \"%V\" set to value \"%v\"", &name, vv); continue; } } ngx_log_error(NGX_LOG_ERR, sr->connection->log, 0, "variable \"%V\" cannot be assigned a value (maybe you " "forgot to define it first?) ", &name); return NGX_ERROR; } return NGX_OK; } static void ngx_http_lua_process_vars_option(ngx_http_request_t *r, lua_State *L, int table, ngx_array_t **varsp) { ngx_array_t *vars; ngx_keyval_t *var; if (table < 0) { table = lua_gettop(L) + table + 1; } vars = *varsp; if (vars == NULL) { vars = ngx_array_create(r->pool, 4, sizeof(ngx_keyval_t)); if (vars == NULL) { dd("here"); luaL_error(L, "no memory"); return; } *varsp = vars; } lua_pushnil(L); while (lua_next(L, table) != 0) { if (lua_type(L, -2) != LUA_TSTRING) { luaL_error(L, "attempt to use a non-string key in the " "\"vars\" option table"); return; } if (!lua_isstring(L, -1)) { luaL_error(L, "attempt to use bad variable value type %s", luaL_typename(L, -1)); return; } var = ngx_array_push(vars); if (var == NULL) { dd("here"); luaL_error(L, "no memory"); return; } var->key.data = (u_char *) lua_tolstring(L, -2, &var->key.len); var->value.data = (u_char *) lua_tolstring(L, -1, &var->value.len); lua_pop(L, 1); } } ngx_int_t ngx_http_lua_post_subrequest(ngx_http_request_t *r, void *data, ngx_int_t rc) { ngx_http_request_t *pr; ngx_http_lua_ctx_t *pr_ctx; ngx_http_lua_ctx_t *ctx; /* subrequest ctx */ ngx_http_lua_co_ctx_t *pr_coctx; size_t len; ngx_str_t *body_str; u_char *p; ngx_chain_t *cl; ngx_http_lua_post_subrequest_data_t *psr_data = data; ctx = psr_data->ctx; if (ctx->run_post_subrequest) { if (r != r->connection->data) { r->connection->data = r; } return NGX_OK; } ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua run post subrequest handler, rc:%i c:%ud", rc, r->main->count); ctx->run_post_subrequest = 1; pr = r->parent; pr_ctx = ngx_http_get_module_ctx(pr, ngx_http_lua_module); if (pr_ctx == NULL) { return NGX_ERROR; } pr_coctx = psr_data->pr_co_ctx; pr_coctx->pending_subreqs--; if (pr_coctx->pending_subreqs == 0) { dd("all subrequests are done"); pr_ctx->no_abort = 0; pr_ctx->resume_handler = ngx_http_lua_subrequest_resume; pr_ctx->cur_co_ctx = pr_coctx; } if (pr_ctx->entered_content_phase) { ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua restoring write event handler"); pr->write_event_handler = ngx_http_lua_content_wev_handler; } else { pr->write_event_handler = ngx_http_core_run_phases; } dd("status rc = %d", (int) rc); dd("status headers_out.status = %d", (int) r->headers_out.status); dd("uri: %.*s", (int) r->uri.len, r->uri.data); /* capture subrequest response status */ pr_coctx->sr_statuses[ctx->index] = r->headers_out.status; if (pr_coctx->sr_statuses[ctx->index] == 0) { if (rc == NGX_OK) { rc = NGX_HTTP_OK; } if (rc == NGX_ERROR) { rc = NGX_HTTP_INTERNAL_SERVER_ERROR; } if (rc >= 100) { pr_coctx->sr_statuses[ctx->index] = rc; } } if (!ctx->seen_last_for_subreq) { pr_coctx->sr_flags[ctx->index] |= NGX_HTTP_LUA_SUBREQ_TRUNCATED; } dd("pr_coctx status: %d", (int) pr_coctx->sr_statuses[ctx->index]); /* copy subrequest response headers */ if (ctx->headers_set) { rc = ngx_http_lua_set_content_type(r, ctx); if (rc != NGX_OK) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "failed to set default content type: %i", rc); return NGX_ERROR; } } pr_coctx->sr_headers[ctx->index] = &r->headers_out; /* copy subrequest response body */ body_str = &pr_coctx->sr_bodies[ctx->index]; len = 0; for (cl = ctx->body; cl; cl = cl->next) { /* ignore all non-memory buffers */ len += cl->buf->last - cl->buf->pos; } body_str->len = len; if (len == 0) { body_str->data = NULL; } else { p = ngx_palloc(r->pool, len); if (p == NULL) { return NGX_ERROR; } body_str->data = p; /* copy from and then free the data buffers */ for (cl = ctx->body; cl; cl = cl->next) { p = ngx_copy(p, cl->buf->pos, cl->buf->last - cl->buf->pos); cl->buf->last = cl->buf->pos; #if 0 dd("free body chain link buf ASAP"); ngx_pfree(r->pool, cl->buf->start); #endif } } if (ctx->body) { ngx_chain_update_chains(r->pool, &pr_ctx->free_bufs, &pr_ctx->busy_bufs, &ctx->body, (ngx_buf_tag_t) &ngx_http_lua_module); dd("free bufs: %p", pr_ctx->free_bufs); } ngx_http_post_request_to_head(pr); if (r != r->connection->data) { r->connection->data = r; } if (rc == NGX_ERROR || rc == NGX_HTTP_CREATED || rc == NGX_HTTP_NO_CONTENT || (rc >= NGX_HTTP_SPECIAL_RESPONSE && rc != NGX_HTTP_CLOSE && rc != NGX_HTTP_REQUEST_TIME_OUT && rc != NGX_HTTP_CLIENT_CLOSED_REQUEST)) { /* emulate ngx_http_special_response_handler */ if (rc > NGX_OK) { r->err_status = rc; r->expect_tested = 1; r->headers_out.content_type.len = 0; r->headers_out.content_length_n = 0; ngx_http_clear_accept_ranges(r); ngx_http_clear_last_modified(r); rc = ngx_http_lua_send_header_if_needed(r, ctx); if (rc == NGX_ERROR) { return NGX_ERROR; } } return NGX_OK; } return rc; } static ngx_int_t ngx_http_lua_set_content_length_header(ngx_http_request_t *r, off_t len) { ngx_table_elt_t *h, *header; u_char *p; ngx_list_part_t *part; ngx_http_request_t *pr; ngx_uint_t i; r->headers_in.content_length_n = len; if (ngx_list_init(&r->headers_in.headers, r->pool, 20, sizeof(ngx_table_elt_t)) != NGX_OK) { return NGX_ERROR; } h = ngx_list_push(&r->headers_in.headers); if (h == NULL) { return NGX_ERROR; } h->key = ngx_http_lua_content_length_header_key; h->lowcase_key = ngx_pnalloc(r->pool, h->key.len); if (h->lowcase_key == NULL) { return NGX_ERROR; } ngx_strlow(h->lowcase_key, h->key.data, h->key.len); r->headers_in.content_length = h; p = ngx_palloc(r->pool, NGX_OFF_T_LEN); if (p == NULL) { return NGX_ERROR; } h->value.data = p; h->value.len = ngx_sprintf(h->value.data, "%O", len) - h->value.data; h->hash = ngx_http_lua_content_length_hash; #if 0 dd("content length hash: %lu == %lu", (unsigned long) h->hash, ngx_hash_key_lc((u_char *) "Content-Length", sizeof("Content-Length") - 1)); #endif dd("r content length: %.*s", (int) r->headers_in.content_length->value.len, r->headers_in.content_length->value.data); pr = r->parent; if (pr == NULL) { return NGX_OK; } /* forward the parent request's all other request headers */ part = &pr->headers_in.headers.part; header = part->elts; for (i = 0; /* void */; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; header = part->elts; i = 0; } if (header[i].key.len == sizeof("Content-Length") - 1 && ngx_strncasecmp(header[i].key.data, (u_char *) "Content-Length", sizeof("Content-Length") - 1) == 0) { continue; } if (ngx_http_lua_set_input_header(r, header[i].key, header[i].value, 0) == NGX_ERROR) { return NGX_ERROR; } } return NGX_OK; } static void ngx_http_lua_handle_subreq_responses(ngx_http_request_t *r, ngx_http_lua_ctx_t *ctx) { ngx_uint_t i, count; ngx_uint_t index; lua_State *co; ngx_str_t *body_str; ngx_table_elt_t *header; ngx_list_part_t *part; ngx_http_headers_out_t *sr_headers; ngx_http_lua_co_ctx_t *coctx; u_char buf[sizeof("Mon, 28 Sep 1970 06:00:00 GMT") - 1]; ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua handle subrequest responses"); coctx = ctx->cur_co_ctx; co = coctx->co; for (index = 0; index < coctx->nsubreqs; index++) { dd("summary: reqs %d, subquery %d, pending %d, req %.*s", (int) coctx->nsubreqs, (int) index, (int) coctx->pending_subreqs, (int) r->uri.len, r->uri.data); /* {{{ construct ret value */ lua_createtable(co, 0 /* narr */, 4 /* nrec */); /* copy captured status */ lua_pushinteger(co, coctx->sr_statuses[index]); lua_setfield(co, -2, "status"); dd("captured subrequest flags: %d", (int) coctx->sr_flags[index]); /* set truncated flag if truncation happens */ if (coctx->sr_flags[index] & NGX_HTTP_LUA_SUBREQ_TRUNCATED) { lua_pushboolean(co, 1); lua_setfield(co, -2, "truncated"); } else { lua_pushboolean(co, 0); lua_setfield(co, -2, "truncated"); } /* copy captured body */ body_str = &coctx->sr_bodies[index]; lua_pushlstring(co, (char *) body_str->data, body_str->len); lua_setfield(co, -2, "body"); if (body_str->data) { dd("free body buffer ASAP"); ngx_pfree(r->pool, body_str->data); } /* copy captured headers */ sr_headers = coctx->sr_headers[index]; part = &sr_headers->headers.part; count = part->nelts; while (part->next) { part = part->next; count += part->nelts; } lua_createtable(co, 0, count + 5); /* res.header */ dd("saving subrequest response headers"); part = &sr_headers->headers.part; header = part->elts; for (i = 0; /* void */; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; header = part->elts; i = 0; } dd("checking sr header %.*s", (int) header[i].key.len, header[i].key.data); #if 1 if (header[i].hash == 0) { continue; } #endif header[i].hash = 0; dd("pushing sr header %.*s", (int) header[i].key.len, header[i].key.data); lua_pushlstring(co, (char *) header[i].key.data, header[i].key.len); /* header key */ lua_pushvalue(co, -1); /* stack: table key key */ /* check if header already exists */ lua_rawget(co, -3); /* stack: table key value */ if (lua_isnil(co, -1)) { lua_pop(co, 1); /* stack: table key */ lua_pushlstring(co, (char *) header[i].value.data, header[i].value.len); /* stack: table key value */ lua_rawset(co, -3); /* stack: table */ } else { if (!lua_istable(co, -1)) { /* already inserted one value */ lua_createtable(co, 4, 0); /* stack: table key value table */ lua_insert(co, -2); /* stack: table key table value */ lua_rawseti(co, -2, 1); /* stack: table key table */ lua_pushlstring(co, (char *) header[i].value.data, header[i].value.len); /* stack: table key table value */ lua_rawseti(co, -2, lua_objlen(co, -2) + 1); /* stack: table key table */ lua_rawset(co, -3); /* stack: table */ } else { lua_pushlstring(co, (char *) header[i].value.data, header[i].value.len); /* stack: table key table value */ lua_rawseti(co, -2, lua_objlen(co, -2) + 1); /* stack: table key table */ lua_pop(co, 2); /* stack: table */ } } } if (sr_headers->content_type.len) { lua_pushliteral(co, "Content-Type"); /* header key */ lua_pushlstring(co, (char *) sr_headers->content_type.data, sr_headers->content_type.len); /* head key value */ lua_rawset(co, -3); /* head */ } if (sr_headers->content_length == NULL && sr_headers->content_length_n >= 0) { lua_pushliteral(co, "Content-Length"); /* header key */ lua_pushnumber(co, (lua_Number) sr_headers->content_length_n); /* head key value */ lua_rawset(co, -3); /* head */ } /* to work-around an issue in ngx_http_static_module * (github issue #41) */ if (sr_headers->location && sr_headers->location->value.len) { lua_pushliteral(co, "Location"); /* header key */ lua_pushlstring(co, (char *) sr_headers->location->value.data, sr_headers->location->value.len); /* head key value */ lua_rawset(co, -3); /* head */ } if (sr_headers->last_modified_time != -1) { if (sr_headers->status != NGX_HTTP_OK && sr_headers->status != NGX_HTTP_PARTIAL_CONTENT && sr_headers->status != NGX_HTTP_NOT_MODIFIED && sr_headers->status != NGX_HTTP_NO_CONTENT) { sr_headers->last_modified_time = -1; sr_headers->last_modified = NULL; } } if (sr_headers->last_modified == NULL && sr_headers->last_modified_time != -1) { (void) ngx_http_time(buf, sr_headers->last_modified_time); lua_pushliteral(co, "Last-Modified"); /* header key */ lua_pushlstring(co, (char *) buf, sizeof(buf)); /* head key value */ lua_rawset(co, -3); /* head */ } lua_setfield(co, -2, "header"); /* }}} */ } } void ngx_http_lua_inject_subrequest_api(lua_State *L) { lua_createtable(L, 0 /* narr */, 2 /* nrec */); /* .location */ lua_pushcfunction(L, ngx_http_lua_ngx_location_capture); lua_setfield(L, -2, "capture"); lua_pushcfunction(L, ngx_http_lua_ngx_location_capture_multi); lua_setfield(L, -2, "capture_multi"); lua_setfield(L, -2, "location"); } static ngx_int_t ngx_http_lua_subrequest(ngx_http_request_t *r, ngx_str_t *uri, ngx_str_t *args, ngx_http_request_t **psr, ngx_http_post_subrequest_t *ps, ngx_uint_t flags) { ngx_time_t *tp; ngx_connection_t *c; ngx_http_request_t *sr; ngx_http_core_srv_conf_t *cscf; #if (nginx_version >= 1009005) if (r->subrequests == 0) { #if defined(NGX_DTRACE) && NGX_DTRACE ngx_http_probe_subrequest_cycle(r, uri, args); #endif ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "lua subrequests cycle while processing \"%V\"", uri); return NGX_ERROR; } #else /* nginx_version <= 1009004 */ r->main->subrequests--; if (r->main->subrequests == 0) { #if defined(NGX_DTRACE) && NGX_DTRACE ngx_http_probe_subrequest_cycle(r, uri, args); #endif ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "lua subrequests cycle while processing \"%V\"", uri); r->main->subrequests = 1; return NGX_ERROR; } #endif sr = ngx_pcalloc(r->pool, sizeof(ngx_http_request_t)); if (sr == NULL) { return NGX_ERROR; } sr->signature = NGX_HTTP_MODULE; c = r->connection; sr->connection = c; sr->ctx = ngx_pcalloc(r->pool, sizeof(void *) * ngx_http_max_module); if (sr->ctx == NULL) { return NGX_ERROR; } if (ngx_list_init(&sr->headers_out.headers, r->pool, 20, sizeof(ngx_table_elt_t)) != NGX_OK) { return NGX_ERROR; } cscf = ngx_http_get_module_srv_conf(r, ngx_http_core_module); sr->main_conf = cscf->ctx->main_conf; sr->srv_conf = cscf->ctx->srv_conf; sr->loc_conf = cscf->ctx->loc_conf; sr->pool = r->pool; sr->headers_in.content_length_n = -1; sr->headers_in.keep_alive_n = -1; ngx_http_clear_content_length(sr); ngx_http_clear_accept_ranges(sr); ngx_http_clear_last_modified(sr); sr->request_body = r->request_body; #if (NGX_HTTP_SPDY) sr->spdy_stream = r->spdy_stream; #endif #if (NGX_HTTP_V2) sr->stream = r->stream; #endif #ifdef HAVE_ALLOW_REQUEST_BODY_UPDATING_PATCH sr->content_length_n = -1; #endif sr->method = NGX_HTTP_GET; sr->http_version = r->http_version; sr->request_line = r->request_line; sr->uri = *uri; if (args) { sr->args = *args; } ngx_log_debug2(NGX_LOG_DEBUG_HTTP, c->log, 0, "lua http subrequest \"%V?%V\"", uri, &sr->args); sr->subrequest_in_memory = (flags & NGX_HTTP_SUBREQUEST_IN_MEMORY) != 0; sr->waited = (flags & NGX_HTTP_SUBREQUEST_WAITED) != 0; sr->unparsed_uri = r->unparsed_uri; sr->method_name = ngx_http_core_get_method; sr->http_protocol = r->http_protocol; ngx_http_set_exten(sr); sr->main = r->main; sr->parent = r; sr->post_subrequest = ps; sr->read_event_handler = ngx_http_request_empty_handler; sr->write_event_handler = ngx_http_handler; sr->variables = r->variables; sr->log_handler = r->log_handler; sr->internal = 1; sr->discard_body = r->discard_body; sr->expect_tested = 1; sr->main_filter_need_in_memory = r->main_filter_need_in_memory; sr->uri_changes = NGX_HTTP_MAX_URI_CHANGES + 1; #if (nginx_version >= 1009005) sr->subrequests = r->subrequests - 1; #endif tp = ngx_timeofday(); sr->start_sec = tp->sec; sr->start_msec = tp->msec; r->main->count++; *psr = sr; #if defined(NGX_DTRACE) && NGX_DTRACE ngx_http_probe_subrequest_start(sr); #endif return ngx_http_post_request(sr, NULL); } static ngx_int_t ngx_http_lua_subrequest_resume(ngx_http_request_t *r) { lua_State *vm; ngx_int_t rc; ngx_uint_t nreqs; ngx_connection_t *c; ngx_http_lua_ctx_t *ctx; ngx_http_lua_co_ctx_t *coctx; ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); if (ctx == NULL) { return NGX_ERROR; } ctx->resume_handler = ngx_http_lua_wev_handler; ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua run subrequests done, resuming lua thread"); coctx = ctx->cur_co_ctx; dd("nsubreqs: %d", (int) coctx->nsubreqs); ngx_http_lua_handle_subreq_responses(r, ctx); dd("free sr_statues/headers/bodies memory ASAP"); #if 1 ngx_pfree(r->pool, coctx->sr_statuses); coctx->sr_statuses = NULL; coctx->sr_headers = NULL; coctx->sr_bodies = NULL; coctx->sr_flags = NULL; #endif c = r->connection; vm = ngx_http_lua_get_lua_vm(r, ctx); nreqs = c->requests; rc = ngx_http_lua_run_thread(vm, r, ctx, coctx->nsubreqs); ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua run thread returned %d", rc); if (rc == NGX_AGAIN) { return ngx_http_lua_run_posted_threads(c, vm, r, ctx, nreqs); } if (rc == NGX_DONE) { ngx_http_lua_finalize_request(r, NGX_DONE); return ngx_http_lua_run_posted_threads(c, vm, r, ctx, nreqs); } /* rc == NGX_ERROR || rc >= NGX_OK */ if (ctx->entered_content_phase) { ngx_http_lua_finalize_request(r, rc); return NGX_DONE; } return rc; } static void ngx_http_lua_cancel_subreq(ngx_http_request_t *r) { ngx_http_posted_request_t *pr; ngx_http_posted_request_t **p; #if 1 r->main->count--; r->main->subrequests++; #endif p = &r->main->posted_requests; for (pr = r->main->posted_requests; pr->next; pr = pr->next) { p = &pr->next; } *p = NULL; r->connection->data = r->parent; } static ngx_int_t ngx_http_post_request_to_head(ngx_http_request_t *r) { ngx_http_posted_request_t *pr; pr = ngx_palloc(r->pool, sizeof(ngx_http_posted_request_t)); if (pr == NULL) { return NGX_ERROR; } pr->request = r; pr->next = r->main->posted_requests; r->main->posted_requests = pr; return NGX_OK; } static ngx_int_t ngx_http_lua_copy_in_file_request_body(ngx_http_request_t *r) { ngx_temp_file_t *tf; ngx_http_request_body_t *body; tf = r->request_body->temp_file; if (!tf->persistent || !tf->clean) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "the request body was not read by ngx_lua"); return NGX_ERROR; } body = ngx_palloc(r->pool, sizeof(ngx_http_request_body_t)); if (body == NULL) { return NGX_ERROR; } ngx_memcpy(body, r->request_body, sizeof(ngx_http_request_body_t)); body->temp_file = ngx_palloc(r->pool, sizeof(ngx_temp_file_t)); if (body->temp_file == NULL) { return NGX_ERROR; } ngx_memcpy(body->temp_file, tf, sizeof(ngx_temp_file_t)); dd("file fd: %d", body->temp_file->file.fd); r->request_body = body; return NGX_OK; } static ngx_int_t ngx_http_lua_copy_request_headers(ngx_http_request_t *sr, ngx_http_request_t *r) { ngx_table_elt_t *header; ngx_list_part_t *part; ngx_uint_t i; if (ngx_list_init(&sr->headers_in.headers, sr->pool, 20, sizeof(ngx_table_elt_t)) != NGX_OK) { return NGX_ERROR; } dd("before: parent req headers count: %d", (int) r->headers_in.headers.part.nelts); part = &r->headers_in.headers.part; header = part->elts; for (i = 0; /* void */; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; header = part->elts; i = 0; } dd("setting request header %.*s: %.*s", (int) header[i].key.len, header[i].key.data, (int) header[i].value.len, header[i].value.data); if (ngx_http_lua_set_input_header(sr, header[i].key, header[i].value, 0) == NGX_ERROR) { return NGX_ERROR; } } dd("after: parent req headers count: %d", (int) r->headers_in.headers.part.nelts); return NGX_OK; } /* vi:set ft=c ts=4 sw=4 et fdm=marker: */
./CrossVul/dataset_final_sorted/CWE-444/c/bad_3969_0
crossvul-cpp_data_good_4617_3
// Copyright (c) 2018, Peter Ohler, All rights reserved. #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "debug.h" #include "http.h" #define BUCKET_SIZE 1024 #define BUCKET_MASK 1023 #define MAX_KEY_UNIQ 9 typedef struct _slot { struct _slot *next; const char *key; uint64_t hash; int klen; } *Slot; typedef struct _cache { Slot buckets[BUCKET_SIZE]; } *Cache; struct _cache key_cache; // The rack spec indicates the characters (),/:;<=>?@[]{} are invalid which // clearly is not consistent with RFC7230 so stick with the RFC. static char header_value_chars[256] = "\ xxxxxxxxxxoxxxxxxxxxxxxxxxxxxxxx\ oooooooooooooooooooooooooooooooo\ oooooooooooooooooooooooooooooooo\ ooooooooooooooooooooooooooooooox\ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; static const char *header_keys[] = { "A-IM", "ALPN", "ARC-Authentication-Results", "ARC-Message-Signature", "ARC-Seal", "Accept", "Accept-Additions", "Accept-Charset", "Accept-Datetime", "Accept-Encoding", "Accept-Features", "Accept-Language", "Accept-Patch", "Accept-Post", "Accept-Ranges", "Access-Control", "Access-Control-Allow-Credentials", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods", "Access-Control-Allow-Origin", "Access-Control-Max-Age", "Access-Control-Request-Headers", "Access-Control-Request-Method", "Age", "Allow", "Also-Control", "Alt-Svc", "Alt-Used", "Alternate-Recipient", "Alternates", "Apparently-To", "Apply-To-Redirect-Ref", "Approved", "Archive", "Archived-At", "Article-Names", "Article-Updates", "Authentication-Control", "Authentication-Info", "Authentication-Results", "Authorization", "Auto-Submitted", "Autoforwarded", "Autosubmitted", "Base", "Bcc", "Body", "C-Ext", "C-Man", "C-Opt", "C-PEP", "C-PEP-Info", "Cache-Control", "CalDAV-Timezones", "Cancel-Key", "Cancel-Lock", "Cc", "Close", "Comments", "Compliance", "Connection", "Content-Alternative", "Content-Base", "Content-Description", "Content-Disposition", "Content-Duration", "Content-Encoding", "Content-ID", "Content-Identifier", "Content-Language", "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Return", "Content-Script-Type", "Content-Style-Type", "Content-Transfer-Encoding", "Content-Translation-Type", "Content-Type", "Content-Version", "Content-features", "Control", "Conversion", "Conversion-With-Loss", "Cookie", "Cookie2", "Cost", "DASL", "DAV", "DKIM-Signature", "DL-Expansion-History", "DNT", "Date", "Date-Received", "Default-Style", "Deferred-Delivery", "Delivery-Date", "Delta-Base", "Depth", "Derived-From", "Destination", "Differential-ID", "Digest", "Discarded-X400-IPMS-Extensions", "Discarded-X400-MTS-Extensions", "Disclose-Recipients", "Disposition-Notification-Options", "Disposition-Notification-To", "Distribution", "Downgraded-Bcc", "Downgraded-Cc", "Downgraded-Disposition-Notification-To", "Downgraded-Final-Recipient", "Downgraded-From", "Downgraded-In-Reply-To", "Downgraded-Mail-From", "Downgraded-Message-Id", "Downgraded-Original-Recipient", "Downgraded-Rcpt-To", "Downgraded-References", "Downgraded-Reply-To", "Downgraded-Resent-Bcc", "Downgraded-Resent-Cc", "Downgraded-Resent-From", "Downgraded-Resent-Reply-To", "Downgraded-Resent-Sender", "Downgraded-Resent-To", "Downgraded-Return-Path", "Downgraded-Sender", "Downgraded-To", "EDIINT-Features", "ETag", "Eesst-Version", "Encoding", "Encrypted", "Errors-To", "Expect", "Expires", "Expiry-Date", "Ext", "Followup-To", "Form-Sub", "Forwarded", "From", "Front-End-Https", "Generate-Delivery-Report", "GetProfile", "HTTP2-Settings", "Hobareg", "Host", "IM", "If", "If-Match", "If-Modified-Since", "If-None-Match", "If-Range", "If-Schedule-Tag-Match", "If-Unmodified-Since", "Importance", "In-Reply-To", "Incomplete-Copy", "Injection-Date", "Injection-Info", "Jabber-ID", "Keep-Alive", "Keywords", "Label", "Language", "Last-Modified", "Latest-Delivery-Time", "Lines", "Link", "List-Archive", "List-Help", "List-ID", "List-Owner", "List-Post", "List-Subscribe", "List-Unsubscribe", "List-Unsubscribe-Post", "Location", "Lock-Token", "MIME-Version", "MMHS-Acp127-Message-Identifier", "MMHS-Authorizing-Users", "MMHS-Codress-Message-Indicator", "MMHS-Copy-Precedence", "MMHS-Exempted-Address", "MMHS-Extended-Authorisation-Info", "MMHS-Handling-Instructions", "MMHS-Message-Instructions", "MMHS-Message-Type", "MMHS-Originator-PLAD", "MMHS-Originator-Reference", "MMHS-Other-Recipients-Indicator-CC", "MMHS-Other-Recipients-Indicator-To", "MMHS-Primary-Precedence", "MMHS-Subject-Indicator-Codes", "MT-Priority", "Man", "Max-Forwards", "Memento-Datetime", "Message-Context", "Message-ID", "Message-Type", "Meter", "Method-Check", "Method-Check-Expires", "NNTP-Posting-Date", "NNTP-Posting-Host", "Negotiate", "Newsgroups", "Non-Compliance", "Obsoletes", "Opt", "Optional", "Optional-WWW-Authenticate", "Ordering-Type", "Organization", "Origin", "Original-Encoded-Information-Types", "Original-From", "Original-Message-ID", "Original-Recipient", "Original-Sender", "Original-Subject", "Originator-Return-Address", "Overwrite", "P3P", "PEP", "PICS-Label", "Path", "Pep-Info", "Position", "Posting-Version", "Pragma", "Prefer", "Preference-Applied", "Prevent-NonDelivery-Report", "Priority", "Privicon", "ProfileObject", "Protocol", "Protocol-Info", "Protocol-Query", "Protocol-Request", "Proxy-Authenticate", "Proxy-Authentication-Info", "Proxy-Authorization", "Proxy-Connection", "Proxy-Features", "Proxy-Instruction", "Public", "Public-Key-Pins", "Public-Key-Pins-Report-Only", "Range", "Received", "Received-SPF", "Redirect-Ref", "References", "Referer", "Referer-Root", "Relay-Version", "Reply-By", "Reply-To", "Require-Recipient-Valid-Since", "Resent-Bcc", "Resent-Cc", "Resent-Date", "Resent-From", "Resent-Message-ID", "Resent-Reply-To", "Resent-Sender", "Resent-To", "Resolution-Hint", "Resolver-Location", "Retry-After", "Return-Path", "SIO-Label", "SIO-Label-History", "SLUG", "Safe", "Save-Data", "Schedule-Reply", "Schedule-Tag", "Sec-WebSocket-Accept", "Sec-WebSocket-Extensions", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol", "Sec-WebSocket-Version", "Security-Scheme", "See-Also", "Sender", "Sender", "Sensitivity", "Server", "Set-Cookie", "Set-Cookie2", "SetProfile", "SoapAction", "Solicitation", "Status-URI", "Strict-Transport-Security", "SubOK", "Subject", "Subst", "Summary", "Supersedes", "Surrogate-Capability", "Surrogate-Control", "TCN", "TE", "TTL", "Timeout", "Title", "To", "Topic", "Trailer", "Transfer-Encoding", "UA-Color", "UA-Media", "UA-Pixels", "UA-Resolution", "UA-Windowpixels", "URI", "Upgrade", "Upgrade-Insecure-Requests", "Urgency", "User-Agent", "VBR-Info", "Variant-Vary", "Vary", "Version", "Via", "WWW-Authenticate", "Want-Digest", "Warning", "X-ATT-DeviceId", "X-Archived-At", "X-Content-Type-Options", "X-Correlation-ID", "X-Csrf-Token", "X-Device-Accept", "X-Device-Accept-Charset", "X-Device-Accept-Encoding", "X-Device-Accept-Language", "X-Device-User-Agent", "X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Proto", "X-Frame-Options", "X-Http-Method-Override", "X-Mittente", "X-PGP-Sig", "X-Request-ID", "X-Requested-With", "X-Ricevuta", "X-Riferimento-Message-ID", "X-TipoRicevuta", "X-Trasporto", "X-UIDH", "X-VerificaSicurezza", "X-Wap-Profile", "X-XSS-Protection", "X400-Content-Identifier", "X400-Content-Return", "X400-Content-Type", "X400-MTS-Identifier", "X400-Originator", "X400-Received", "X400-Recipients", "X400-Trace", "Xref", NULL }; static uint64_t calc_hash(const char *key, int *lenp) { int len = 0; int klen = *lenp; uint64_t h = 0; bool special = false; if (NULL != key) { const uint8_t *k = (const uint8_t*)key; for (; len < klen; k++) { // narrow to most used range of 0x4D (77) in size if (*k < 0x2D || 0x7A < *k) { special = true; } // fast, just spread it out h = 77 * h + ((*k | 0x20) - 0x2D); len++; } } if (special) { *lenp = -len; } else { *lenp = len; } return h; } static Slot* get_bucketp(uint64_t h) { return key_cache.buckets + (BUCKET_MASK & (h ^ (h << 5) ^ (h >> 7))); } static void key_set(const char *key) { int len = (int)strlen(key); int64_t h = calc_hash(key, &len); Slot *bucket = get_bucketp(h); Slot s; if (NULL != (s = (Slot)AGOO_MALLOC(sizeof(struct _slot)))) { s->hash = h; s->klen = len; s->key = key; s->next = *bucket; *bucket = s; } } void agoo_http_init() { const char **kp = header_keys; memset(&key_cache, 0, sizeof(struct _cache)); for (; NULL != *kp; kp++) { key_set(*kp); } } void agoo_http_cleanup() { Slot *sp = key_cache.buckets; Slot s; Slot n; int i; for (i = BUCKET_SIZE; 0 < i; i--, sp++) { for (s = *sp; NULL != s; s = n) { n = s->next; AGOO_FREE(s); } *sp = NULL; } } int agoo_http_header_ok(agooErr err, const char *key, int klen, const char *value, int vlen) { int len = klen; int64_t h = calc_hash(key, &len); Slot *bucket = get_bucketp(h); Slot s; bool found = false; for (s = *bucket; NULL != s; s = s->next) { if (h == (int64_t)s->hash && len == (int)s->klen && ((0 <= len && len <= MAX_KEY_UNIQ) || 0 == strncasecmp(s->key, key, klen))) { found = true; break; } } if (!found) { char buf[256]; if ((int)sizeof(buf) <= klen) { klen = sizeof(buf) - 1; } strncpy(buf, key, klen); buf[klen] = '\0'; return agoo_err_set(err, AGOO_ERR_ARG, "%s is not a valid HTTP header key.", buf); } // Now check the value. found = false; // reuse as indicator for in a quoted string for (; 0 < vlen; vlen--, value++) { if ('o' != header_value_chars[(uint8_t)*value]) { return agoo_err_set(err, AGOO_ERR_ARG, "%02x is not a valid HTTP header value character.", *value); } if ('"' == *value) { found = !found; } } if (found) { return agoo_err_set(err, AGOO_ERR_ARG, "HTTP header has unmatched quote."); } return AGOO_ERR_OK; } const char* agoo_http_code_message(int code) { const char *msg = ""; switch (code) { case 100: msg = "Continue"; break; case 101: msg = "Switching Protocols"; break; case 102: msg = "Processing"; break; case 200: msg = "OK"; break; case 201: msg = "Created"; break; case 202: msg = "Accepted"; break; case 203: msg = "Non-authoritative Information"; break; case 204: msg = "No Content"; break; case 205: msg = "Reset Content"; break; case 206: msg = "Partial Content"; break; case 207: msg = "Multi-Status"; break; case 208: msg = "Already Reported"; break; case 226: msg = "IM Used"; break; case 300: msg = "Multiple Choices"; break; case 301: msg = "Moved Permanently"; break; case 302: msg = "Found"; break; case 303: msg = "See Other"; break; case 304: msg = "Not Modified"; break; case 305: msg = "Use Proxy"; break; case 307: msg = "Temporary Redirect"; break; case 308: msg = "Permanent Redirect"; break; case 400: msg = "Bad Request"; break; case 401: msg = "Unauthorized"; break; case 402: msg = "Payment Required"; break; case 403: msg = "Forbidden"; break; case 404: msg = "Not Found"; break; case 405: msg = "Method Not Allowed"; break; case 406: msg = "Not Acceptable"; break; case 407: msg = "Proxy Authentication Required"; break; case 408: msg = "Request Timeout"; break; case 409: msg = "Conflict"; break; case 410: msg = "Gone"; break; case 411: msg = "Length Required"; break; case 412: msg = "Precondition Failed"; break; case 413: msg = "Payload Too Large"; break; case 414: msg = "Request-URI Too Long"; break; case 415: msg = "Unsupported Media Type"; break; case 416: msg = "Requested Range Not Satisfiable"; break; case 417: msg = "Expectation Failed"; break; case 418: msg = "I'm a teapot"; break; case 421: msg = "Misdirected Request"; break; case 422: msg = "Unprocessable Entity"; break; case 423: msg = "Locked"; break; case 424: msg = "Failed Dependency"; break; case 426: msg = "Upgrade Required"; break; case 428: msg = "Precondition Required"; break; case 429: msg = "Too Many Requests"; break; case 431: msg = "Request Header Fields Too Large"; break; case 444: msg = "Connection Closed Without Response"; break; case 451: msg = "Unavailable For Legal Reasons"; break; case 499: msg = "Client Closed Request"; break; case 500: msg = "Internal Server Error"; break; case 501: msg = "Not Implemented"; break; case 502: msg = "Bad Gateway"; break; case 503: msg = "Service Unavailable"; break; case 504: msg = "Gateway Timeout"; break; case 505: msg = "HTTP Version Not Supported"; break; case 506: msg = "Variant Also Negotiates"; break; case 507: msg = "Insufficient Storage"; break; case 508: msg = "Loop Detected"; break; case 510: msg = "Not Extended"; break; case 511: msg = "Network Authentication Required"; break; case 599: msg = "Network Connect Timeout Error"; break; default: break; } return msg; }
./CrossVul/dataset_final_sorted/CWE-444/c/good_4617_3
crossvul-cpp_data_good_4617_1
// Copyright (c) 2018, Peter Ohler, All rights reserved. #include <ctype.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include "bind.h" #include "con.h" #include "debug.h" #include "domain.h" #include "dtime.h" #include "hook.h" #include "gqlsub.h" #include "http.h" #include "log.h" #include "page.h" #include "pub.h" #include "ready.h" #include "res.h" #include "seg.h" #include "server.h" #include "sse.h" #include "subject.h" #include "upgraded.h" #include "websocket.h" #define CON_TIMEOUT 10.0 #define INITIAL_POLL_SIZE 1024 typedef enum { HEAD_AGAIN = 'A', HEAD_ERR = 'E', HEAD_OK = 'O', HEAD_HANDLED = 'H', } HeadReturn; static bool con_ws_read(agooCon c); static bool con_ws_write(agooCon c); static short con_ws_events(agooCon c); static bool con_sse_write(agooCon c); static short con_sse_events(agooCon c); static struct _agooBind ws_bind = { .kind = AGOO_CON_WS, .read = con_ws_read, .write = con_ws_write, .events = con_ws_events, }; static struct _agooBind sse_bind = { .kind = AGOO_CON_SSE, .read = NULL, .write = con_sse_write, .events = con_sse_events, }; agooCon agoo_con_create(agooErr err, int sock, uint64_t id, agooBind b) { agooCon c; if (NULL == (c = (agooCon)AGOO_CALLOC(1, sizeof(struct _agooCon)))) { AGOO_ERR_MEM(err, "Connection"); } else { // It would be better to get this information in server.c after // accept() but that does not work on macOS so instead a call to // getpeername() is used instead. struct sockaddr_storage addr; socklen_t len = sizeof(addr); getpeername(sock, (struct sockaddr*)&addr, &len); if (addr.ss_family == AF_INET) { struct sockaddr_in *s = (struct sockaddr_in*)&addr; inet_ntop(AF_INET, &s->sin_addr, c->remote, sizeof(c->remote)); } else { struct sockaddr_in6 *s = (struct sockaddr_in6*)&addr; inet_ntop(AF_INET6, &s->sin6_addr, c->remote, sizeof(c->remote)); } c->sock = sock; c->id = id; c->timeout = dtime() + CON_TIMEOUT; c->bind = b; c->loop = NULL; pthread_mutex_init(&c->res_lock, 0); } return c; } void agoo_con_destroy(agooCon c) { atomic_fetch_sub(&agoo_server.con_cnt, 1); if (AGOO_CON_WS == c->bind->kind || AGOO_CON_SSE == c->bind->kind) { agoo_ws_req_close(c); } if (0 < c->sock) { #ifdef HAVE_OPENSSL_SSL_H if (NULL != c->ssl) { SSL_free(c->ssl); c->ssl = NULL; } #endif close(c->sock); c->sock = 0; } if (NULL != c->req) { agoo_req_destroy(c->req); } if (NULL != c->up) { agoo_upgraded_release_con(c->up); c->up = NULL; } if (NULL != c->gsub) { agoo_server_del_gsub(c->gsub); gql_sub_destroy(c->gsub); c->gsub = NULL; } agoo_log_cat(&agoo_con_cat, "Connection %llu closed.", (unsigned long long)c->id); agooRes res; while (NULL != (res = c->res_head)) { c->res_head = res->next; AGOO_FREE(res); } pthread_mutex_destroy(&c->res_lock); AGOO_FREE(c); } void agoo_con_res_append(agooCon c, agooRes res) { pthread_mutex_lock(&c->res_lock); if (NULL == c->res_tail) { c->res_head = res; } else { c->res_tail->next = res; } c->res_tail = res; pthread_mutex_unlock(&c->res_lock); } static void agoo_con_res_prepend(agooCon c, agooRes res) { pthread_mutex_lock(&c->res_lock); res->next = c->res_head; c->res_head = res; if (NULL == c->res_tail) { c->res_tail = res; } pthread_mutex_unlock(&c->res_lock); } static agooRes agoo_con_res_pop(agooCon c) { agooRes res; pthread_mutex_lock(&c->res_lock); if (NULL != (res = c->res_head)) { c->res_head = res->next; if (res == c->res_tail) { c->res_tail = NULL; } } pthread_mutex_unlock(&c->res_lock); return res; } static agooRes agoo_con_res_peek(agooCon c) { agooRes res; pthread_mutex_lock(&c->res_lock); res = c->res_head; pthread_mutex_unlock(&c->res_lock); return res; } const char* agoo_con_header_value(const char *header, int hlen, const char *key, int *vlen) { // Search for \r then check for \n and then the key followed by a :. Keep // trying until the end of the header. const char *h = header; const char *hend = header + hlen; const char *value; int klen = (int)strlen(key); while (h < hend) { if (0 == strncasecmp(key, h, klen) && ':' == h[klen]) { h += klen + 1; for (; ' ' == *h; h++) { } value = h; for (; '\r' != *h && '\0' != *h; h++) { } *vlen = (int)(h - value); return value; } for (; h < hend; h++) { if ('\r' == *h && '\n' == *(h + 1)) { h += 2; break; } } } return NULL; } static HeadReturn bad_request(agooCon c, int status, int line) { agooRes res; const char *msg = agoo_http_code_message(status); if (NULL == (res = agoo_res_create(c))) { agoo_log_cat(&agoo_error_cat, "memory allocation of response failed on connection %llu @ %d.", (unsigned long long)c->id, line); } else { char buf[256]; int cnt = snprintf(buf, sizeof(buf), "HTTP/1.1 %d %s\r\nConnection: Close\r\nContent-Length: 0\r\n\r\n", status, msg); agooText message = agoo_text_create(buf, cnt); agoo_con_res_append(c, res); res->close = true; agoo_res_message_push(res, message); } return HEAD_ERR; } static bool should_close(const char *header, int hlen) { const char *v; int vlen = 0; if (NULL != (v = agoo_con_header_value(header, hlen, "Connection", &vlen))) { return (5 == vlen && 0 == strncasecmp("Close", v, 5)); } return false; } static bool page_response(agooCon c, agooPage p, char *hend) { agooRes res; char *b; if (NULL == (res = agoo_res_create(c))) { return true; } agoo_con_res_append(c, res); b = strstr(c->buf, "\r\n"); res->close = should_close(b, (int)(hend - b)); if (res->close) { c->closing = true; } agoo_res_message_push(res, p->resp); return false; } // rserver static void push_error(agooUpgraded up, const char *msg, int mlen) { if (NULL != up && agoo_server.ctx_nil_value != up->ctx && up->on_error) { agooReq req = agoo_req_create(mlen); if (NULL == req) { return; } memcpy(req->msg, msg, mlen); req->msg[mlen] = '\0'; req->up = up; req->method = AGOO_ON_ERROR; req->hook = agoo_hook_create(AGOO_NONE, NULL, up->ctx, PUSH_HOOK, &agoo_server.eval_queue); agoo_upgraded_ref(up); agoo_queue_push(&agoo_server.eval_queue, (void*)req); } } static HeadReturn con_header_read(agooCon c, size_t *mlenp) { char *hend = strstr(c->buf, "\r\n\r\n"); agooMethod method; struct _agooSeg path; char *query = NULL; char *qend; char *b; size_t clen = 0; long mlen; agooHook hook = NULL; agooPage p; struct _agooErr err = AGOO_ERR_INIT; if (NULL == hend) { if (sizeof(c->buf) - 1 <= c->bcnt) { return bad_request(c, 431, __LINE__); } return HEAD_AGAIN; } if (agoo_req_cat.on) { *hend = '\0'; agoo_log_cat(&agoo_req_cat, "%s %llu: %s", agoo_con_kind_str(c->bind->kind), (unsigned long long)c->id, c->buf); *hend = '\r'; } for (b = c->buf; ' ' != *b; b++) { if ('\0' == *b) { return bad_request(c, 400, __LINE__); } } switch (toupper(*c->buf)) { case 'G': if (3 != b - c->buf || 0 != strncmp("GET", c->buf, 3)) { return bad_request(c, 400, __LINE__); } method = AGOO_GET; break; case 'P': { const char *v; int vlen = 0; char *vend; if (3 == b - c->buf && 0 == strncmp("PUT", c->buf, 3)) { method = AGOO_PUT; } else if (4 == b - c->buf && 0 == strncmp("POST", c->buf, 4)) { method = AGOO_POST; } else { return bad_request(c, 400, __LINE__); } if (NULL == (v = agoo_con_header_value(c->buf, (int)(hend - c->buf), "Content-Length", &vlen))) { return bad_request(c, 411, __LINE__); } clen = (size_t)strtoul(v, &vend, 10); if (vend != v + vlen) { return bad_request(c, 411, __LINE__); } break; } case 'D': if (6 != b - c->buf || 0 != strncmp("DELETE", c->buf, 6)) { return bad_request(c, 400, __LINE__); } method = AGOO_DELETE; break; case 'H': if (4 != b - c->buf || 0 != strncmp("HEAD", c->buf, 4)) { return bad_request(c, 400, __LINE__); } method = AGOO_HEAD; break; case 'O': if (7 != b - c->buf || 0 != strncmp("OPTIONS", c->buf, 7)) { return bad_request(c, 400, __LINE__); } method = AGOO_OPTIONS; break; case 'C': if (7 != b - c->buf || 0 != strncmp("CONNECT", c->buf, 7)) { return bad_request(c, 400, __LINE__); } method = AGOO_CONNECT; break; default: return bad_request(c, 400, __LINE__); } for (; ' ' == *b; b++) { if ('\0' == *b) { return bad_request(c, 400, __LINE__); } } path.start = b; for (; ' ' != *b; b++) { switch (*b) { case '?': path.end = b; query = b + 1; break; case '\0': return bad_request(c, 400, __LINE__); default: break; } } if (NULL == query) { path.end = b; query = b; qend = b; } else { qend = b; } mlen = hend - c->buf + 4 + clen; *mlenp = mlen; if (AGOO_GET == method) { char root_buf[20148]; const char *root = NULL; if (NULL != (p = agoo_group_get(&err, path.start, (int)(path.end - path.start)))) { if (page_response(c, p, hend)) { return bad_request(c, 500, __LINE__); } return HEAD_HANDLED; } if (agoo_domain_use()) { const char *host; int vlen = 0; if (NULL == (host = agoo_con_header_value(c->buf, (int)(hend - c->buf), "Host", &vlen))) { return bad_request(c, 411, __LINE__); } ((char*)host)[vlen] = '\0'; root = agoo_domain_resolve(host, root_buf, sizeof(root_buf)); ((char*)host)[vlen] = '\r'; } if (agoo_server.root_first && NULL != (p = agoo_page_get(&err, path.start, (int)(path.end - path.start), root))) { if (page_response(c, p, hend)) { return bad_request(c, 500, __LINE__); } return HEAD_HANDLED; } if (NULL == (hook = agoo_hook_find(agoo_server.hooks, method, &path))) { if (NULL != (p = agoo_page_get(&err, path.start, (int)(path.end - path.start), root))) { if (page_response(c, p, hend)) { return bad_request(c, 500, __LINE__); } return HEAD_HANDLED; } if (NULL == agoo_server.hook404) { return bad_request(c, 404, __LINE__); } hook = agoo_server.hook404; } } else if (NULL == (hook = agoo_hook_find(agoo_server.hooks, method, &path))) { return bad_request(c, 404, __LINE__); } // Create request and populate. if (NULL == (c->req = agoo_req_create(mlen))) { return bad_request(c, 413, __LINE__); } if ((long)c->bcnt <= mlen) { memcpy(c->req->msg, c->buf, c->bcnt); if ((long)c->bcnt < mlen) { memset(c->req->msg + c->bcnt, 0, mlen - c->bcnt); } } else { memcpy(c->req->msg, c->buf, mlen); } c->req->msg[mlen] = '\0'; c->req->method = method; c->req->upgrade = AGOO_UP_NONE; c->req->up = NULL; memcpy(c->req->remote, c->remote, sizeof(c->remote)); c->req->path.start = c->req->msg + (path.start - c->buf); c->req->path.len = (int)(path.end - path.start); c->req->query.start = c->req->msg + (query - c->buf); c->req->query.len = (int)(qend - query); c->req->query.start[c->req->query.len] = '\0'; c->req->body.start = c->req->msg + (hend - c->buf + 4); c->req->body.len = (unsigned int)clen; b = strstr(b, "\r\n"); c->req->header.start = c->req->msg + (b + 2 - c->buf); if (b < hend) { c->req->header.len = (unsigned int)(hend - b - 2); } else { c->req->header.len = 0; } c->req->res = NULL; c->req->hook = hook; return HEAD_OK; } static void check_upgrade(agooCon c) { const char *v; int vlen = 0; if (NULL == c->req) { return; } if (NULL != (v = agoo_con_header_value(c->req->header.start, c->req->header.len, "Connection", &vlen))) { if (NULL != strstr(v, "Upgrade")) { if (NULL != (v = agoo_con_header_value(c->req->header.start, c->req->header.len, "Upgrade", &vlen))) { if (0 == strncasecmp("WebSocket", v, vlen)) { c->res_tail->close = false; c->res_tail->con_kind = AGOO_CON_WS; return; } } } } if (NULL != (v = agoo_con_header_value(c->req->header.start, c->req->header.len, "Accept", &vlen))) { if (0 == strncasecmp("text/event-stream", v, vlen)) { c->res_tail->close = false; c->res_tail->con_kind = AGOO_CON_SSE; return; } } } #ifdef HAVE_OPENSSL_SSL_H static void con_ssl_error(agooCon c, const char *what, unsigned long e, const char *filename, int line) { char buf[224]; if (0 == e) { e = ERR_get_error(); } c->dead = true; ERR_error_string_n(e, buf, sizeof(buf)); agoo_log_cat(&agoo_error_cat, "%s %s at %s:%d", what, buf, filename, line); } #endif bool agoo_con_http_read(agooCon c) { ssize_t cnt = 0; if (c->dead || 0 == c->sock || c->closing) { return true; } if (AGOO_CON_HTTPS == c->bind->kind) { #ifdef HAVE_OPENSSL_SSL_H if (NULL != c->req) { cnt = SSL_read(c->ssl, c->req->msg + c->bcnt, (int)(c->req->mlen - c->bcnt)); } else { cnt = SSL_read(c->ssl, c->buf + c->bcnt, (int)(sizeof(c->buf) - c->bcnt - 1)); } if (0 > cnt) { //unsigned long e = ERR_get_error(); int e = (int)ERR_get_error(); if (0 == e) { return false; } else { con_ssl_error(c, "read", (unsigned long)e, __FILE__, __LINE__); c->dead = true; return true; } } #else agoo_log_cat(&agoo_error_cat, "SSL not included in the build."); c->dead = true; #endif } else { if (NULL != c->req) { cnt = recv(c->sock, c->req->msg + c->bcnt, c->req->mlen - c->bcnt, 0); } else { cnt = recv(c->sock, c->buf + c->bcnt, sizeof(c->buf) - c->bcnt - 1, 0); } } c->timeout = dtime() + CON_TIMEOUT; if (0 >= cnt) { // If nothing read then no need to complain. Just close. if (0 < c->bcnt) { if (0 == cnt) { agoo_log_cat(&agoo_warn_cat, "Nothing to read. Client closed socket on connection %llu.", (unsigned long long)c->id); } else { agoo_log_cat(&agoo_warn_cat, "Failed to read request. %s.", strerror(errno)); } } c->dead = true; return true; } c->bcnt += cnt; while (true) { if (NULL == c->req) { size_t mlen; switch (con_header_read(c, &mlen)) { case HEAD_AGAIN: // Try again the next time. Didn't read enough. return false; case HEAD_OK: // req was created break; case HEAD_HANDLED: if (mlen < c->bcnt) { memmove(c->buf, c->buf + mlen, c->bcnt - mlen); c->bcnt -= mlen; // req is NULL so try to ready the header on the next request. continue; } else { c->bcnt = 0; *c->buf = '\0'; return false; } break; case HEAD_ERR: default: c->bcnt = 0; *c->buf = '\0'; return false; } } if (NULL != c->req) { if (c->req->mlen <= c->bcnt) { agooReq req; agooRes res; long mlen; if (agoo_debug_cat.on && NULL != c->req && NULL != c->req->body.start) { agoo_log_cat(&agoo_debug_cat, "%s request on %llu: %s", agoo_con_kind_str(c->bind->kind), (unsigned long long)c->id, c->req->body.start); } if (NULL == (res = agoo_res_create(c))) { c->req = NULL; agoo_log_cat(&agoo_error_cat, "memory allocation of response failed on connection %llu.", (unsigned long long)c->id); return bad_request(c, 500, __LINE__); } else { agoo_con_res_append(c, res); res->close = should_close(c->req->header.start, c->req->header.len); if (res->close) { c->closing = true; } } c->req->res = res; mlen = c->req->mlen; check_upgrade(c); req = c->req; c->req = NULL; if (req->hook->no_queue && FUNC_HOOK == req->hook->type) { req->hook->func(req); agoo_req_destroy(req); } else { agoo_queue_push(req->hook->queue, (void*)req); } if (mlen < (long)c->bcnt) { memmove(c->buf, c->buf + mlen, c->bcnt - mlen); c->bcnt -= mlen; } else { c->bcnt = 0; *c->buf = '\0'; break; } continue; } } break; } return false; } // return false to remove/close connection bool agoo_con_http_write(agooCon c) { agooRes res = agoo_con_res_pop(c); agooText message = agoo_res_message_peek(res); ssize_t cnt = 0; if (NULL == message) { return true; } c->timeout = dtime() + CON_TIMEOUT; if (0 == c->wcnt) { if (agoo_resp_cat.on) { char buf[4096]; char *hend = strstr(message->text, "\r\n\r\n"); if (NULL == hend) { hend = message->text + message->len; } if ((long)sizeof(buf) <= hend - message->text) { hend = message->text + sizeof(buf) - 1; } memcpy(buf, message->text, hend - message->text); buf[hend - message->text] = '\0'; agoo_log_cat(&agoo_resp_cat, "%s %llu: %s", agoo_con_kind_str(c->bind->kind), (unsigned long long)c->id, buf); } if (agoo_debug_cat.on) { agoo_log_cat(&agoo_debug_cat, "%s response on %llu: %s", agoo_con_kind_str(c->bind->kind), (unsigned long long)c->id, message->text); } } if (AGOO_CON_HTTPS == c->bind->kind) { #ifdef HAVE_OPENSSL_SSL_H if (0 >= (cnt = SSL_write(c->ssl, message->text + c->wcnt, (int)(message->len - c->wcnt)))) { unsigned long e = ERR_get_error(); if (0 == e) { return true; } con_ssl_error(c, "write", (unsigned long)e, __FILE__, __LINE__); c->dead = true; return false; } #else agoo_log_cat(&agoo_error_cat, "SSL not included in the build."); c->dead = true; #endif } else { if (0 > (cnt = send(c->sock, message->text + c->wcnt, message->len - c->wcnt, MSG_DONTWAIT))) { if (EAGAIN == errno) { return true; } agoo_log_cat(&agoo_error_cat, "Socket error @ %llu.", (unsigned long long)c->id); c->dead = true; return false; } } c->wcnt += cnt; if (c->wcnt == message->len) { // finished agooText next = agoo_res_message_next(res); c->wcnt = 0; if (NULL == next && res->final) { bool done = res->close; agoo_res_destroy(res); return !done; } } agoo_con_res_prepend(c, res); return true; } static bool con_ws_read(agooCon c) { ssize_t cnt; uint8_t *b; uint8_t op; long mlen; if (NULL != c->req) { cnt = recv(c->sock, c->req->msg + c->bcnt, c->req->mlen - c->bcnt, 0); } else { cnt = recv(c->sock, c->buf + c->bcnt, sizeof(c->buf) - c->bcnt - 1, 0); } c->timeout = dtime() + CON_TIMEOUT; if (0 >= cnt) { // If nothing read then no need to complain. Just close. if (0 < c->bcnt) { if (0 == cnt) { agoo_log_cat(&agoo_warn_cat, "Nothing to read. Client closed socket on connection %llu.", (unsigned long long)c->id); } else { char msg[1024]; int len = snprintf(msg, sizeof(msg) - 1, "Failed to read WebSocket message. %s.", strerror(errno)); push_error(c->up, msg, len); agoo_log_cat(&agoo_warn_cat, "Failed to read WebSocket message. %s.", strerror(errno)); } } return true; } c->bcnt += cnt; while (true) { if (NULL == c->req) { if (c->bcnt < 2) { return false; // Try again. } b = (uint8_t*)c->buf; if (0 >= (mlen = agoo_ws_calc_len(c, b, c->bcnt))) { return (mlen < 0); } op = 0x0F & *b; switch (op) { case AGOO_WS_OP_TEXT: case AGOO_WS_OP_BIN: if (NULL != c->gsub) { // GraphQL subscriptions do not accept input on the // connection. break; } if (agoo_ws_create_req(c, mlen)) { return true; } break; case AGOO_WS_OP_CLOSE: return true; case AGOO_WS_OP_PING: if (mlen == (long)c->bcnt) { agoo_ws_pong(c); c->bcnt = 0; } break; case AGOO_WS_OP_PONG: // ignore if (mlen == (long)c->bcnt) { c->bcnt = 0; } break; case AGOO_WS_OP_CONT: default: { char msg[1024]; int len = snprintf(msg, sizeof(msg) - 1, "WebSocket op 0x%02x not supported on %llu.", op, (unsigned long long)c->id); push_error(c->up, msg, len); agoo_log_cat(&agoo_error_cat, "WebSocket op 0x%02x not supported on %llu.", op, (unsigned long long)c->id); return true; } } } if (NULL != c->req) { mlen = c->req->mlen; c->req->mlen = agoo_ws_decode(c->req->msg, c->req->mlen); if (mlen <= (long)c->bcnt) { if (agoo_debug_cat.on) { if (AGOO_ON_MSG == c->req->method) { agoo_log_cat(&agoo_debug_cat, "WebSocket message on %llu: %s", (unsigned long long)c->id, c->req->msg); } else { agoo_log_cat(&agoo_debug_cat, "WebSocket binary message on %llu", (unsigned long long)c->id); } } } agoo_upgraded_ref(c->up); agoo_queue_push(&agoo_server.eval_queue, (void*)c->req); if (mlen < (long)c->bcnt) { memmove(c->buf, c->buf + mlen, c->bcnt - mlen); c->bcnt -= mlen; } else { c->bcnt = 0; *c->buf = '\0'; c->req = NULL; break; } c->req = NULL; continue; } break; } return false; } static const char ping_msg[] = "\x89\x00"; static const char pong_msg[] = "\x8a\x00"; static bool con_ws_write(agooCon c) { agooRes res = agoo_con_res_pop(c); agooText message = agoo_res_message_peek(res); ssize_t cnt; if (NULL == message) { if (res->ping) { if (0 > (cnt = send(c->sock, ping_msg, sizeof(ping_msg) - 1, 0))) { char msg[1024]; int len; if (EAGAIN == errno) { return true; } len = snprintf(msg, sizeof(msg) - 1, "Socket error @ %llu.", (unsigned long long)c->id); push_error(c->up, msg, len); agoo_log_cat(&agoo_error_cat, "Socket error @ %llu.", (unsigned long long)c->id); agoo_ws_req_close(c); agoo_res_destroy(res); return false; } } else if (res->pong) { if (0 > (cnt = send(c->sock, pong_msg, sizeof(pong_msg) - 1, 0))) { char msg[1024]; int len; if (EAGAIN == errno) { return true; } len = snprintf(msg, sizeof(msg) - 1, "Socket error @ %llu.", (unsigned long long)c->id); push_error(c->up, msg, len); agoo_log_cat(&agoo_error_cat, "Socket error @ %llu.", (unsigned long long)c->id); agoo_ws_req_close(c); agoo_res_destroy(res); return false; } } else { agoo_ws_req_close(c); agoo_res_destroy(res); return false; } return true; } c->timeout = dtime() + CON_TIMEOUT; if (0 == c->wcnt) { agooText t; if (agoo_push_cat.on) { if (message->bin) { agoo_log_cat(&agoo_push_cat, "%llu binary", (unsigned long long)c->id); } else { agoo_log_cat(&agoo_push_cat, "%llu: %s", (unsigned long long)c->id, message->text); } } t = agoo_ws_expand(message); if (t != message) { agoo_res_message_push(res, t); message = t; } } if (0 > (cnt = send(c->sock, message->text + c->wcnt, message->len - c->wcnt, 0))) { char msg[1024]; int len; if (EAGAIN == errno) { return true; } len = snprintf(msg, sizeof(msg) - 1, "Socket error @ %llu.", (unsigned long long)c->id); push_error(c->up, msg, len); agoo_log_cat(&agoo_error_cat, "Socket error @ %llu.", (unsigned long long)c->id); agoo_ws_req_close(c); return false; } c->wcnt += cnt; if (c->wcnt == message->len) { // finished agooText next = agoo_res_message_next(res); c->wcnt = 0; if (NULL == next && res->final) { bool done = res->close; agoo_res_destroy(res); return !done; } } agoo_con_res_prepend(c, res); return true; } static bool con_sse_write(agooCon c) { agooRes res = agoo_con_res_pop(c); agooText message = agoo_res_message_peek(res); ssize_t cnt; if (NULL == message) { agoo_res_destroy(res); return false; } c->timeout = dtime() + CON_TIMEOUT *2; if (0 == c->wcnt) { agooText t; if (agoo_push_cat.on) { agoo_log_cat(&agoo_push_cat, "%llu: %s %p", (unsigned long long)c->id, message->text, (void*)res); } t = agoo_sse_expand(message); if (t != message) { agoo_res_message_push(res, t); message = t; } } if (0 > (cnt = send(c->sock, message->text + c->wcnt, message->len - c->wcnt, 0))) { char msg[1024]; int len; if (EAGAIN == errno) { return true; } len = snprintf(msg, sizeof(msg) - 1, "Socket error @ %llu.", (unsigned long long)c->id); push_error(c->up, msg, len); agoo_log_cat(&agoo_error_cat, "Socket error @ %llu.", (unsigned long long)c->id); return false; } c->wcnt += cnt; if (c->wcnt == message->len) { // finished agooText next = agoo_res_message_next(res); c->wcnt = 0; if (NULL == next) { bool done = res->close; agoo_res_destroy(res); return !done; } } agoo_con_res_prepend(c, res); return true; } static void publish_pub(agooPub pub, agooConLoop loop) { agooUpgraded up; const char *sub = pub->subject->pattern; int cnt = 0; for (up = agoo_server.up_list; NULL != up; up = up->next) { if (NULL != up->con && up->con->loop == loop && agoo_upgraded_match(up, sub)) { agooRes res = agoo_res_create(up->con); if (NULL != res) { agoo_con_res_append(up->con, res); res->con_kind = AGOO_CON_ANY; agoo_res_message_push(res, agoo_text_dup(pub->msg)); cnt++; } } } } static void unsubscribe_pub(agooPub pub) { if (NULL == pub->up) { agooUpgraded up; for (up = agoo_server.up_list; NULL != up; up = up->next) { agoo_upgraded_del_subject(up, pub->subject); } } else { agoo_upgraded_del_subject(pub->up, pub->subject); } } static void process_pub_con(agooPub pub, agooConLoop loop) { agooUpgraded up = pub->up; if (NULL != up && NULL != up->con && up->con->loop == loop) { int pending; // TBD Change pending to be based on length of con queue if (1 == (pending = atomic_fetch_sub(&up->pending, 1))) { if (NULL != up && agoo_server.ctx_nil_value != up->ctx && up->on_empty) { agooReq req = agoo_req_create(0); req->up = up; req->method = AGOO_ON_EMPTY; req->hook = agoo_hook_create(AGOO_NONE, NULL, up->ctx, PUSH_HOOK, &agoo_server.eval_queue); agoo_upgraded_ref(up); agoo_queue_push(&agoo_server.eval_queue, (void*)req); } } } switch (pub->kind) { case AGOO_PUB_CLOSE: // A close after already closed is used to decrement the reference // count on the upgraded so it can be destroyed in the con loop // threads. if (NULL != up->con && up->con->loop == loop) { agooRes res = agoo_res_create(up->con); if (NULL != res) { agoo_con_res_append(up->con, res); res->con_kind = up->con->bind->kind; res->close = true; } } break; case AGOO_PUB_WRITE: { if (NULL == up->con) { agoo_log_cat(&agoo_warn_cat, "Connection already closed. WebSocket write failed."); } else if (up->con->loop == loop) { agooRes res = agoo_res_create(up->con); if (NULL != res) { agoo_con_res_append(up->con, res); res->con_kind = AGOO_CON_ANY; agoo_res_message_push(res, pub->msg); } } break; case AGOO_PUB_SUB: if (NULL != up && up->con->loop == loop) { agoo_upgraded_add_subject(pub->up, pub->subject); pub->subject = NULL; } break; case AGOO_PUB_UN: if (NULL != up && up->con->loop == loop) { unsubscribe_pub(pub); } break; case AGOO_PUB_MSG: publish_pub(pub, loop); break; } default: break; } agoo_pub_destroy(pub); } short agoo_con_http_events(agooCon c) { short events = 0; agooRes res = agoo_con_res_peek(c); if (NULL != res && NULL != res->message) { events = POLLIN | POLLOUT; } else if (!c->closing) { events = POLLIN; } return events; } static short con_ws_events(agooCon c) { short events = 0; agooRes res = agoo_con_res_peek(c); if (NULL != res && (res->close || res->ping || NULL != res->message)) { events = POLLIN | POLLOUT; } else if (!c->closing) { events = POLLIN; } return events; } static short con_sse_events(agooCon c) { short events = 0; agooRes res = agoo_con_res_peek(c); if (NULL != res && NULL != res->message) { events = POLLOUT; } return events; } static bool remove_dead_res(agooCon c) { agooRes res; bool empty; pthread_mutex_lock(&c->res_lock); while (NULL != (res = c->res_head)) { if (NULL == agoo_res_message_peek(c->res_head) && !c->res_head->close && !c->res_head->ping) { break; } c->res_head = res->next; if (res == c->res_tail) { c->res_tail = NULL; } agoo_res_destroy(res); } empty = NULL == c->res_head; pthread_mutex_unlock(&c->res_lock); return empty; } static agooReadyIO con_ready_io(void *ctx) { agooCon c = (agooCon)ctx; if (NULL != c->bind && !c->dead && 0 != c->sock) { switch (c->bind->events(c)) { case POLLIN: return AGOO_READY_IN; case POLLOUT: return AGOO_READY_OUT; case POLLIN | POLLOUT: return AGOO_READY_BOTH; default: break; } } return AGOO_READY_NONE; } // Ready to close check. True if ready to close. static bool con_ready_check(void *ctx, double now) { agooCon c = (agooCon)ctx; if (c->dead || 0 == c->sock) { if (remove_dead_res(c)) { return true; } } else if (0.0 == c->timeout || now < c->timeout) { return false; } else if (c->closing) { if (remove_dead_res(c)) { return true; } } else if (AGOO_CON_WS == c->bind->kind || AGOO_CON_SSE == c->bind->kind) { c->timeout = dtime() + CON_TIMEOUT; if (AGOO_CON_WS == c->bind->kind) { agoo_ws_ping(c); } return false; } else { c->closing = true; c->timeout = now + 0.5; } return false; } static bool con_ready_read(agooReady ready, void *ctx) { agooCon c = (agooCon)ctx; if (NULL != c->bind->read) { if (!c->bind->read(c)) { return true; } } else { return true; // not an error, just ignore } c->dead = true; return false; } static bool con_ready_write(void *ctx) { agooCon c = (agooCon)ctx; agooRes res = agoo_con_res_peek(c); if (NULL != res) { agooConKind kind = res->con_kind; if (NULL != c->bind->write) { if (c->bind->write(c)) { //if (kind != c->kind && AGOO_CON_ANY != kind) { if (AGOO_CON_ANY != kind) { switch (kind) { case AGOO_CON_WS: c->bind = &ws_bind; break; case AGOO_CON_SSE: c->bind = &sse_bind; break; default: break; } } return true; } } } c->dead = true; return false; } static void con_ready_destroy(void *ctx) { agoo_con_destroy((agooCon)ctx); } static void con_ready_error(void *ctx) { ((agooCon)ctx)->dead = true; } static struct _agooHandler con_handler = { .io = con_ready_io, .check = con_ready_check, .read = con_ready_read, .write = con_ready_write, .error = con_ready_error, .destroy = con_ready_destroy, }; static agooReadyIO queue_ready_io(void *ctx) { return AGOO_READY_IN; } static void con_ssl_setup(agooCon c) { #ifdef HAVE_OPENSSL_SSL_H if (NULL == (c->ssl = SSL_new(agoo_server.ssl_ctx))) { con_ssl_error(c, "new SSL", 0, __FILE__, __LINE__); } if (!SSL_set_fd(c->ssl, c->sock)) { con_ssl_error(c, "SSL set fd", 0, __FILE__, __LINE__); } if (!SSL_accept(c->ssl)) { con_ssl_error(c, "SSL accept", 0, __FILE__, __LINE__); } #else agoo_log_cat(&agoo_error_cat, "SSL not included in the build."); c->dead = true; #endif } static bool con_queue_ready_read(agooReady ready, void *ctx) { agooConLoop loop = (agooConLoop)ctx; struct _agooErr err = AGOO_ERR_INIT; agooCon c; agoo_queue_release(&agoo_server.con_queue); while (NULL != (c = (agooCon)agoo_queue_pop(&agoo_server.con_queue, 0.0))) { c->loop = loop; if (AGOO_ERR_OK != agoo_ready_add(&err, ready, c->sock, &con_handler, c)) { agoo_log_cat(&agoo_error_cat, "Failed to add connection to manager. %s", err.msg); agoo_err_clear(&err); } if (AGOO_CON_HTTPS == c->bind->kind) { con_ssl_setup(c); } } return true; } static struct _agooHandler con_queue_handler = { .io = queue_ready_io, .check = NULL, .read = con_queue_ready_read, .write = NULL, .error = NULL, .destroy = NULL, }; static bool pub_queue_ready_read(agooReady ready, void *ctx) { agooConLoop loop = (agooConLoop)ctx; agooPub pub; agoo_queue_release(&loop->pub_queue); while (NULL != (pub = (agooPub)agoo_queue_pop(&loop->pub_queue, 0.0))) { process_pub_con(pub, loop); } return true; } static struct _agooHandler pub_queue_handler = { .io = queue_ready_io, .check = NULL, .read = pub_queue_ready_read, .write = NULL, .error = NULL, .destroy = NULL, }; void* agoo_con_loop(void *x) { agooConLoop loop = (agooConLoop)x; struct _agooErr err = AGOO_ERR_INIT; agooReady ready = agoo_ready_create(&err); agooPub pub; agooCon c; int con_queue_fd = agoo_queue_listen(&agoo_server.con_queue); int pub_queue_fd = agoo_queue_listen(&loop->pub_queue); if (NULL == ready) { agoo_log_cat(&agoo_error_cat, "Failed to create connection manager. %s", err.msg); exit(EXIT_FAILURE); return NULL; } if (AGOO_ERR_OK != agoo_ready_add(&err, ready, con_queue_fd, &con_queue_handler, loop) || AGOO_ERR_OK != agoo_ready_add(&err, ready, pub_queue_fd, &pub_queue_handler, loop)) { agoo_log_cat(&agoo_error_cat, "Failed to add queue connection to manager. %s", err.msg); exit(EXIT_FAILURE); return NULL; } atomic_fetch_add(&agoo_server.running, 1); while (agoo_server.active) { while (NULL != (c = (agooCon)agoo_queue_pop(&agoo_server.con_queue, 0.0))) { c->loop = loop; if (AGOO_ERR_OK != agoo_ready_add(&err, ready, c->sock, &con_handler, c)) { agoo_log_cat(&agoo_error_cat, "Failed to add connection to manager. %s", err.msg); agoo_err_clear(&err); } if (AGOO_CON_HTTPS == c->bind->kind) { con_ssl_setup(c); } } while (NULL != (pub = (agooPub)agoo_queue_pop(&loop->pub_queue, 0.0))) { process_pub_con(pub, loop); } if (AGOO_ERR_OK != agoo_ready_go(&err, ready)) { agoo_log_cat(&agoo_error_cat, "IO error. %s", err.msg); agoo_err_clear(&err); } } agoo_ready_destroy(ready); atomic_fetch_sub(&agoo_server.running, 1); return NULL; } agooConLoop agoo_conloop_create(agooErr err, int id) { agooConLoop loop; if (NULL == (loop = (agooConLoop)AGOO_MALLOC(sizeof(struct _agooConLoop)))) { AGOO_ERR_MEM(err, "connection thread"); } else { int stat; loop->next = NULL; if (AGOO_ERR_OK != agoo_queue_multi_init(err, &loop->pub_queue, 256, true, false)) { AGOO_FREE(loop); return NULL; } loop->id = id; loop->res_head = NULL; loop->res_tail = NULL; if (0 != pthread_mutex_init(&loop->lock, 0)) { AGOO_FREE(loop); agoo_err_no(err, "Failed to initialize loop mutex."); return NULL; } if (0 != (stat = pthread_create(&loop->thread, NULL, agoo_con_loop, loop))) { agoo_err_set(err, stat, "Failed to create connection loop. %s", strerror(stat)); return NULL; } } return loop; } void agoo_conloop_destroy(agooConLoop loop) { agooRes res; agoo_queue_cleanup(&loop->pub_queue); while (NULL != (res = loop->res_head)) { loop->res_head = res->next; AGOO_FREE(res); } AGOO_FREE(loop); }
./CrossVul/dataset_final_sorted/CWE-444/c/good_4617_1
crossvul-cpp_data_good_3969_0
/* * Copyright (C) Xiaozhe Wang (chaoslawful) * Copyright (C) Yichun Zhang (agentzh) */ #ifndef DDEBUG #define DDEBUG 0 #endif #include "ddebug.h" #include "ngx_http_lua_subrequest.h" #include "ngx_http_lua_util.h" #include "ngx_http_lua_ctx.h" #include "ngx_http_lua_contentby.h" #include "ngx_http_lua_headers_in.h" #if defined(NGX_DTRACE) && NGX_DTRACE #include "ngx_http_probe.h" #endif #define NGX_HTTP_LUA_SHARE_ALL_VARS 0x01 #define NGX_HTTP_LUA_COPY_ALL_VARS 0x02 #define ngx_http_lua_method_name(m) { sizeof(m) - 1, (u_char *) m " " } ngx_str_t ngx_http_lua_get_method = ngx_http_lua_method_name("GET"); ngx_str_t ngx_http_lua_put_method = ngx_http_lua_method_name("PUT"); ngx_str_t ngx_http_lua_post_method = ngx_http_lua_method_name("POST"); ngx_str_t ngx_http_lua_head_method = ngx_http_lua_method_name("HEAD"); ngx_str_t ngx_http_lua_delete_method = ngx_http_lua_method_name("DELETE"); ngx_str_t ngx_http_lua_options_method = ngx_http_lua_method_name("OPTIONS"); ngx_str_t ngx_http_lua_copy_method = ngx_http_lua_method_name("COPY"); ngx_str_t ngx_http_lua_move_method = ngx_http_lua_method_name("MOVE"); ngx_str_t ngx_http_lua_lock_method = ngx_http_lua_method_name("LOCK"); ngx_str_t ngx_http_lua_mkcol_method = ngx_http_lua_method_name("MKCOL"); ngx_str_t ngx_http_lua_propfind_method = ngx_http_lua_method_name("PROPFIND"); ngx_str_t ngx_http_lua_proppatch_method = ngx_http_lua_method_name("PROPPATCH"); ngx_str_t ngx_http_lua_unlock_method = ngx_http_lua_method_name("UNLOCK"); ngx_str_t ngx_http_lua_patch_method = ngx_http_lua_method_name("PATCH"); ngx_str_t ngx_http_lua_trace_method = ngx_http_lua_method_name("TRACE"); static ngx_str_t ngx_http_lua_content_length_header_key = ngx_string("Content-Length"); static ngx_int_t ngx_http_lua_adjust_subrequest(ngx_http_request_t *sr, ngx_uint_t method, int forward_body, ngx_http_request_body_t *body, unsigned vars_action, ngx_array_t *extra_vars); static int ngx_http_lua_ngx_location_capture(lua_State *L); static int ngx_http_lua_ngx_location_capture_multi(lua_State *L); static void ngx_http_lua_process_vars_option(ngx_http_request_t *r, lua_State *L, int table, ngx_array_t **varsp); static ngx_int_t ngx_http_lua_subrequest_add_extra_vars(ngx_http_request_t *r, ngx_array_t *extra_vars); static ngx_int_t ngx_http_lua_subrequest(ngx_http_request_t *r, ngx_str_t *uri, ngx_str_t *args, ngx_http_request_t **psr, ngx_http_post_subrequest_t *ps, ngx_uint_t flags); static ngx_int_t ngx_http_lua_subrequest_resume(ngx_http_request_t *r); static void ngx_http_lua_handle_subreq_responses(ngx_http_request_t *r, ngx_http_lua_ctx_t *ctx); static void ngx_http_lua_cancel_subreq(ngx_http_request_t *r); static ngx_int_t ngx_http_post_request_to_head(ngx_http_request_t *r); static ngx_int_t ngx_http_lua_copy_in_file_request_body(ngx_http_request_t *r); static ngx_int_t ngx_http_lua_copy_request_headers(ngx_http_request_t *sr, ngx_http_request_t *pr, int pr_not_chunked); enum { NGX_HTTP_LUA_SUBREQ_TRUNCATED = 1, }; /* ngx.location.capture is just a thin wrapper around * ngx.location.capture_multi */ static int ngx_http_lua_ngx_location_capture(lua_State *L) { int n; n = lua_gettop(L); if (n != 1 && n != 2) { return luaL_error(L, "expecting one or two arguments"); } lua_createtable(L, n, 0); /* uri opts? table */ lua_insert(L, 1); /* table uri opts? */ if (n == 1) { /* table uri */ lua_rawseti(L, 1, 1); /* table */ } else { /* table uri opts */ lua_rawseti(L, 1, 2); /* table uri */ lua_rawseti(L, 1, 1); /* table */ } lua_createtable(L, 1, 0); /* table table' */ lua_insert(L, 1); /* table' table */ lua_rawseti(L, 1, 1); /* table' */ return ngx_http_lua_ngx_location_capture_multi(L); } static int ngx_http_lua_ngx_location_capture_multi(lua_State *L) { ngx_http_request_t *r; ngx_http_request_t *sr = NULL; /* subrequest object */ ngx_http_post_subrequest_t *psr; ngx_http_lua_ctx_t *sr_ctx; ngx_http_lua_ctx_t *ctx; ngx_array_t *extra_vars; ngx_str_t uri; ngx_str_t args; ngx_str_t extra_args; ngx_uint_t flags; u_char *p; u_char *q; size_t len; size_t nargs; int rc; int n; int always_forward_body = 0; ngx_uint_t method; ngx_http_request_body_t *body; int type; ngx_buf_t *b; unsigned vars_action; ngx_uint_t nsubreqs; ngx_uint_t index; size_t sr_statuses_len; size_t sr_headers_len; size_t sr_bodies_len; size_t sr_flags_len; size_t ofs1, ofs2; unsigned custom_ctx; ngx_http_lua_co_ctx_t *coctx; ngx_http_lua_post_subrequest_data_t *psr_data; n = lua_gettop(L); if (n != 1) { return luaL_error(L, "only one argument is expected, but got %d", n); } luaL_checktype(L, 1, LUA_TTABLE); nsubreqs = lua_objlen(L, 1); if (nsubreqs == 0) { return luaL_error(L, "at least one subrequest should be specified"); } r = ngx_http_lua_get_req(L); if (r == NULL) { return luaL_error(L, "no request object found"); } #if (NGX_HTTP_V2) if (r->main->stream) { return luaL_error(L, "http2 requests not supported yet"); } #endif ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); if (ctx == NULL) { return luaL_error(L, "no ctx found"); } ngx_http_lua_check_context(L, ctx, NGX_HTTP_LUA_CONTEXT_REWRITE | NGX_HTTP_LUA_CONTEXT_ACCESS | NGX_HTTP_LUA_CONTEXT_CONTENT); coctx = ctx->cur_co_ctx; if (coctx == NULL) { return luaL_error(L, "no co ctx found"); } ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua location capture, uri:\"%V\" c:%ud", &r->uri, r->main->count); sr_statuses_len = nsubreqs * sizeof(ngx_int_t); sr_headers_len = nsubreqs * sizeof(ngx_http_headers_out_t *); sr_bodies_len = nsubreqs * sizeof(ngx_str_t); sr_flags_len = nsubreqs * sizeof(uint8_t); p = ngx_pcalloc(r->pool, sr_statuses_len + sr_headers_len + sr_bodies_len + sr_flags_len); if (p == NULL) { return luaL_error(L, "no memory"); } coctx->sr_statuses = (void *) p; p += sr_statuses_len; coctx->sr_headers = (void *) p; p += sr_headers_len; coctx->sr_bodies = (void *) p; p += sr_bodies_len; coctx->sr_flags = (void *) p; coctx->nsubreqs = nsubreqs; coctx->pending_subreqs = 0; extra_vars = NULL; for (index = 0; index < nsubreqs; index++) { coctx->pending_subreqs++; lua_rawgeti(L, 1, index + 1); if (lua_isnil(L, -1)) { return luaL_error(L, "only array-like tables are allowed"); } dd("queries query: top %d", lua_gettop(L)); if (lua_type(L, -1) != LUA_TTABLE) { return luaL_error(L, "the query argument %d is not a table, " "but a %s", index, lua_typename(L, lua_type(L, -1))); } nargs = lua_objlen(L, -1); if (nargs != 1 && nargs != 2) { return luaL_error(L, "query argument %d expecting one or " "two arguments", index); } lua_rawgeti(L, 2, 1); /* queries query uri */ dd("queries query uri: %d", lua_gettop(L)); dd("first arg in first query: %s", lua_typename(L, lua_type(L, -1))); body = NULL; ngx_str_null(&extra_args); if (extra_vars != NULL) { /* flush out existing elements in the array */ extra_vars->nelts = 0; } vars_action = 0; custom_ctx = 0; if (nargs == 2) { /* check out the options table */ lua_rawgeti(L, 2, 2); /* queries query uri opts */ dd("queries query uri opts: %d", lua_gettop(L)); if (lua_type(L, 4) != LUA_TTABLE) { return luaL_error(L, "expecting table as the 2nd argument for " "subrequest %d, but got %s", index, luaL_typename(L, 4)); } dd("queries query uri opts: %d", lua_gettop(L)); /* check the args option */ lua_getfield(L, 4, "args"); type = lua_type(L, -1); switch (type) { case LUA_TTABLE: ngx_http_lua_process_args_option(r, L, -1, &extra_args); break; case LUA_TNIL: /* do nothing */ break; case LUA_TNUMBER: case LUA_TSTRING: extra_args.data = (u_char *) lua_tolstring(L, -1, &len); extra_args.len = len; break; default: return luaL_error(L, "Bad args option value"); } lua_pop(L, 1); dd("queries query uri opts: %d", lua_gettop(L)); /* check the vars option */ lua_getfield(L, 4, "vars"); switch (lua_type(L, -1)) { case LUA_TTABLE: ngx_http_lua_process_vars_option(r, L, -1, &extra_vars); dd("post process vars top: %d", lua_gettop(L)); break; case LUA_TNIL: /* do nothing */ break; default: return luaL_error(L, "Bad vars option value"); } lua_pop(L, 1); dd("queries query uri opts: %d", lua_gettop(L)); /* check the share_all_vars option */ lua_getfield(L, 4, "share_all_vars"); switch (lua_type(L, -1)) { case LUA_TNIL: /* do nothing */ break; case LUA_TBOOLEAN: if (lua_toboolean(L, -1)) { vars_action |= NGX_HTTP_LUA_SHARE_ALL_VARS; } break; default: return luaL_error(L, "Bad share_all_vars option value"); } lua_pop(L, 1); dd("queries query uri opts: %d", lua_gettop(L)); /* check the copy_all_vars option */ lua_getfield(L, 4, "copy_all_vars"); switch (lua_type(L, -1)) { case LUA_TNIL: /* do nothing */ break; case LUA_TBOOLEAN: if (lua_toboolean(L, -1)) { vars_action |= NGX_HTTP_LUA_COPY_ALL_VARS; } break; default: return luaL_error(L, "Bad copy_all_vars option value"); } lua_pop(L, 1); dd("queries query uri opts: %d", lua_gettop(L)); /* check the "forward_body" option */ lua_getfield(L, 4, "always_forward_body"); always_forward_body = lua_toboolean(L, -1); lua_pop(L, 1); dd("always forward body: %d", always_forward_body); /* check the "method" option */ lua_getfield(L, 4, "method"); type = lua_type(L, -1); if (type == LUA_TNIL) { method = NGX_HTTP_GET; } else { if (type != LUA_TNUMBER) { return luaL_error(L, "Bad http request method"); } method = (ngx_uint_t) lua_tonumber(L, -1); } lua_pop(L, 1); dd("queries query uri opts: %d", lua_gettop(L)); /* check the "ctx" option */ lua_getfield(L, 4, "ctx"); type = lua_type(L, -1); if (type != LUA_TNIL) { if (type != LUA_TTABLE) { return luaL_error(L, "Bad ctx option value type %s, " "expected a Lua table", lua_typename(L, type)); } custom_ctx = 1; } else { lua_pop(L, 1); } dd("queries query uri opts ctx?: %d", lua_gettop(L)); /* check the "body" option */ lua_getfield(L, 4, "body"); type = lua_type(L, -1); if (type != LUA_TNIL) { if (type != LUA_TSTRING && type != LUA_TNUMBER) { return luaL_error(L, "Bad http request body"); } body = ngx_pcalloc(r->pool, sizeof(ngx_http_request_body_t)); if (body == NULL) { return luaL_error(L, "no memory"); } q = (u_char *) lua_tolstring(L, -1, &len); dd("request body: [%.*s]", (int) len, q); if (len) { b = ngx_create_temp_buf(r->pool, len); if (b == NULL) { return luaL_error(L, "no memory"); } b->last = ngx_copy(b->last, q, len); body->bufs = ngx_alloc_chain_link(r->pool); if (body->bufs == NULL) { return luaL_error(L, "no memory"); } body->bufs->buf = b; body->bufs->next = NULL; body->buf = b; } } lua_pop(L, 1); /* pop the body */ /* stack: queries query uri opts ctx? */ lua_remove(L, 4); /* stack: queries query uri ctx? */ dd("queries query uri ctx?: %d", lua_gettop(L)); } else { method = NGX_HTTP_GET; } /* stack: queries query uri ctx? */ p = (u_char *) luaL_checklstring(L, 3, &len); uri.data = ngx_palloc(r->pool, len); if (uri.data == NULL) { return luaL_error(L, "memory allocation error"); } ngx_memcpy(uri.data, p, len); uri.len = len; ngx_str_null(&args); flags = 0; rc = ngx_http_parse_unsafe_uri(r, &uri, &args, &flags); if (rc != NGX_OK) { dd("rc = %d", (int) rc); return luaL_error(L, "unsafe uri in argument #1: %s", p); } if (args.len == 0) { if (extra_args.len) { p = ngx_palloc(r->pool, extra_args.len); if (p == NULL) { return luaL_error(L, "no memory"); } ngx_memcpy(p, extra_args.data, extra_args.len); args.data = p; args.len = extra_args.len; } } else if (extra_args.len) { /* concatenate the two parts of args together */ len = args.len + (sizeof("&") - 1) + extra_args.len; p = ngx_palloc(r->pool, len); if (p == NULL) { return luaL_error(L, "no memory"); } q = ngx_copy(p, args.data, args.len); *q++ = '&'; ngx_memcpy(q, extra_args.data, extra_args.len); args.data = p; args.len = len; } ofs1 = ngx_align(sizeof(ngx_http_post_subrequest_t), sizeof(void *)); ofs2 = ngx_align(sizeof(ngx_http_lua_ctx_t), sizeof(void *)); p = ngx_palloc(r->pool, ofs1 + ofs2 + sizeof(ngx_http_lua_post_subrequest_data_t)); if (p == NULL) { return luaL_error(L, "no memory"); } psr = (ngx_http_post_subrequest_t *) p; p += ofs1; sr_ctx = (ngx_http_lua_ctx_t *) p; ngx_http_lua_assert((void *) sr_ctx == ngx_align_ptr(sr_ctx, sizeof(void *))); p += ofs2; psr_data = (ngx_http_lua_post_subrequest_data_t *) p; ngx_http_lua_assert((void *) psr_data == ngx_align_ptr(psr_data, sizeof(void *))); ngx_memzero(sr_ctx, sizeof(ngx_http_lua_ctx_t)); /* set by ngx_memzero: * sr_ctx->run_post_subrequest = 0 * sr_ctx->free = NULL * sr_ctx->body = NULL */ psr_data->ctx = sr_ctx; psr_data->pr_co_ctx = coctx; psr->handler = ngx_http_lua_post_subrequest; psr->data = psr_data; rc = ngx_http_lua_subrequest(r, &uri, &args, &sr, psr, 0); if (rc != NGX_OK) { return luaL_error(L, "failed to issue subrequest: %d", (int) rc); } ngx_http_lua_init_ctx(sr, sr_ctx); sr_ctx->capture = 1; sr_ctx->index = index; sr_ctx->last_body = &sr_ctx->body; sr_ctx->vm_state = ctx->vm_state; ngx_http_set_ctx(sr, sr_ctx, ngx_http_lua_module); rc = ngx_http_lua_adjust_subrequest(sr, method, always_forward_body, body, vars_action, extra_vars); if (rc != NGX_OK) { ngx_http_lua_cancel_subreq(sr); return luaL_error(L, "failed to adjust the subrequest: %d", (int) rc); } dd("queries query uri opts ctx? %d", lua_gettop(L)); /* stack: queries query uri ctx? */ if (custom_ctx) { ngx_http_lua_ngx_set_ctx_helper(L, sr, sr_ctx, -1); lua_pop(L, 3); } else { lua_pop(L, 2); } /* stack: queries */ } if (extra_vars) { ngx_array_destroy(extra_vars); } ctx->no_abort = 1; return lua_yield(L, 0); } static ngx_int_t ngx_http_lua_adjust_subrequest(ngx_http_request_t *sr, ngx_uint_t method, int always_forward_body, ngx_http_request_body_t *body, unsigned vars_action, ngx_array_t *extra_vars) { ngx_http_request_t *r; ngx_http_core_main_conf_t *cmcf; int pr_not_chunked = 0; size_t size; r = sr->parent; sr->header_in = r->header_in; if (body) { sr->request_body = body; } else if (!always_forward_body && method != NGX_HTTP_PUT && method != NGX_HTTP_POST && r->headers_in.content_length_n > 0) { sr->request_body = NULL; } else { if (!r->headers_in.chunked) { pr_not_chunked = 1; } if (sr->request_body && sr->request_body->temp_file) { /* deep-copy the request body */ if (ngx_http_lua_copy_in_file_request_body(sr) != NGX_OK) { return NGX_ERROR; } } } if (ngx_http_lua_copy_request_headers(sr, r, pr_not_chunked) != NGX_OK) { return NGX_ERROR; } sr->method = method; switch (method) { case NGX_HTTP_GET: sr->method_name = ngx_http_lua_get_method; break; case NGX_HTTP_POST: sr->method_name = ngx_http_lua_post_method; break; case NGX_HTTP_PUT: sr->method_name = ngx_http_lua_put_method; break; case NGX_HTTP_HEAD: sr->method_name = ngx_http_lua_head_method; break; case NGX_HTTP_DELETE: sr->method_name = ngx_http_lua_delete_method; break; case NGX_HTTP_OPTIONS: sr->method_name = ngx_http_lua_options_method; break; case NGX_HTTP_MKCOL: sr->method_name = ngx_http_lua_mkcol_method; break; case NGX_HTTP_COPY: sr->method_name = ngx_http_lua_copy_method; break; case NGX_HTTP_MOVE: sr->method_name = ngx_http_lua_move_method; break; case NGX_HTTP_PROPFIND: sr->method_name = ngx_http_lua_propfind_method; break; case NGX_HTTP_PROPPATCH: sr->method_name = ngx_http_lua_proppatch_method; break; case NGX_HTTP_LOCK: sr->method_name = ngx_http_lua_lock_method; break; case NGX_HTTP_UNLOCK: sr->method_name = ngx_http_lua_unlock_method; break; case NGX_HTTP_PATCH: sr->method_name = ngx_http_lua_patch_method; break; case NGX_HTTP_TRACE: sr->method_name = ngx_http_lua_trace_method; break; default: ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "unsupported HTTP method: %u", (unsigned) method); return NGX_ERROR; } if (!(vars_action & NGX_HTTP_LUA_SHARE_ALL_VARS)) { /* we do not inherit the parent request's variables */ cmcf = ngx_http_get_module_main_conf(sr, ngx_http_core_module); size = cmcf->variables.nelts * sizeof(ngx_http_variable_value_t); if (vars_action & NGX_HTTP_LUA_COPY_ALL_VARS) { sr->variables = ngx_palloc(sr->pool, size); if (sr->variables == NULL) { return NGX_ERROR; } ngx_memcpy(sr->variables, r->variables, size); } else { /* we do not inherit the parent request's variables */ sr->variables = ngx_pcalloc(sr->pool, size); if (sr->variables == NULL) { return NGX_ERROR; } } } return ngx_http_lua_subrequest_add_extra_vars(sr, extra_vars); } static ngx_int_t ngx_http_lua_subrequest_add_extra_vars(ngx_http_request_t *sr, ngx_array_t *extra_vars) { ngx_http_core_main_conf_t *cmcf; ngx_http_variable_t *v; ngx_http_variable_value_t *vv; u_char *val; u_char *p; ngx_uint_t i, hash; ngx_str_t name; size_t len; ngx_hash_t *variables_hash; ngx_keyval_t *var; /* set any extra variables that were passed to the subrequest */ if (extra_vars == NULL || extra_vars->nelts == 0) { return NGX_OK; } cmcf = ngx_http_get_module_main_conf(sr, ngx_http_core_module); variables_hash = &cmcf->variables_hash; var = extra_vars->elts; for (i = 0; i < extra_vars->nelts; i++, var++) { /* copy the variable's name and value because they are allocated * by the lua VM */ len = var->key.len + var->value.len; p = ngx_pnalloc(sr->pool, len); if (p == NULL) { return NGX_ERROR; } name.data = p; name.len = var->key.len; p = ngx_copy(p, var->key.data, var->key.len); hash = ngx_hash_strlow(name.data, name.data, name.len); val = p; len = var->value.len; ngx_memcpy(p, var->value.data, len); v = ngx_hash_find(variables_hash, hash, name.data, name.len); if (v) { if (!(v->flags & NGX_HTTP_VAR_CHANGEABLE)) { ngx_log_error(NGX_LOG_ERR, sr->connection->log, 0, "variable \"%V\" not changeable", &name); return NGX_HTTP_INTERNAL_SERVER_ERROR; } if (v->set_handler) { vv = ngx_palloc(sr->pool, sizeof(ngx_http_variable_value_t)); if (vv == NULL) { return NGX_ERROR; } vv->valid = 1; vv->not_found = 0; vv->no_cacheable = 0; vv->data = val; vv->len = len; v->set_handler(sr, vv, v->data); ngx_log_debug2(NGX_LOG_DEBUG_HTTP, sr->connection->log, 0, "variable \"%V\" set to value \"%v\"", &name, vv); continue; } if (v->flags & NGX_HTTP_VAR_INDEXED) { vv = &sr->variables[v->index]; vv->valid = 1; vv->not_found = 0; vv->no_cacheable = 0; vv->data = val; vv->len = len; ngx_log_debug2(NGX_LOG_DEBUG_HTTP, sr->connection->log, 0, "variable \"%V\" set to value \"%v\"", &name, vv); continue; } } ngx_log_error(NGX_LOG_ERR, sr->connection->log, 0, "variable \"%V\" cannot be assigned a value (maybe you " "forgot to define it first?) ", &name); return NGX_ERROR; } return NGX_OK; } static void ngx_http_lua_process_vars_option(ngx_http_request_t *r, lua_State *L, int table, ngx_array_t **varsp) { ngx_array_t *vars; ngx_keyval_t *var; if (table < 0) { table = lua_gettop(L) + table + 1; } vars = *varsp; if (vars == NULL) { vars = ngx_array_create(r->pool, 4, sizeof(ngx_keyval_t)); if (vars == NULL) { dd("here"); luaL_error(L, "no memory"); return; } *varsp = vars; } lua_pushnil(L); while (lua_next(L, table) != 0) { if (lua_type(L, -2) != LUA_TSTRING) { luaL_error(L, "attempt to use a non-string key in the " "\"vars\" option table"); return; } if (!lua_isstring(L, -1)) { luaL_error(L, "attempt to use bad variable value type %s", luaL_typename(L, -1)); return; } var = ngx_array_push(vars); if (var == NULL) { dd("here"); luaL_error(L, "no memory"); return; } var->key.data = (u_char *) lua_tolstring(L, -2, &var->key.len); var->value.data = (u_char *) lua_tolstring(L, -1, &var->value.len); lua_pop(L, 1); } } ngx_int_t ngx_http_lua_post_subrequest(ngx_http_request_t *r, void *data, ngx_int_t rc) { ngx_http_request_t *pr; ngx_http_lua_ctx_t *pr_ctx; ngx_http_lua_ctx_t *ctx; /* subrequest ctx */ ngx_http_lua_co_ctx_t *pr_coctx; size_t len; ngx_str_t *body_str; u_char *p; ngx_chain_t *cl; ngx_http_lua_post_subrequest_data_t *psr_data = data; ctx = psr_data->ctx; if (ctx->run_post_subrequest) { if (r != r->connection->data) { r->connection->data = r; } return NGX_OK; } ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua run post subrequest handler, rc:%i c:%ud", rc, r->main->count); ctx->run_post_subrequest = 1; pr = r->parent; pr_ctx = ngx_http_get_module_ctx(pr, ngx_http_lua_module); if (pr_ctx == NULL) { return NGX_ERROR; } pr_coctx = psr_data->pr_co_ctx; pr_coctx->pending_subreqs--; if (pr_coctx->pending_subreqs == 0) { dd("all subrequests are done"); pr_ctx->no_abort = 0; pr_ctx->resume_handler = ngx_http_lua_subrequest_resume; pr_ctx->cur_co_ctx = pr_coctx; } if (pr_ctx->entered_content_phase) { ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua restoring write event handler"); pr->write_event_handler = ngx_http_lua_content_wev_handler; } else { pr->write_event_handler = ngx_http_core_run_phases; } dd("status rc = %d", (int) rc); dd("status headers_out.status = %d", (int) r->headers_out.status); dd("uri: %.*s", (int) r->uri.len, r->uri.data); /* capture subrequest response status */ pr_coctx->sr_statuses[ctx->index] = r->headers_out.status; if (pr_coctx->sr_statuses[ctx->index] == 0) { if (rc == NGX_OK) { rc = NGX_HTTP_OK; } if (rc == NGX_ERROR) { rc = NGX_HTTP_INTERNAL_SERVER_ERROR; } if (rc >= 100) { pr_coctx->sr_statuses[ctx->index] = rc; } } if (!ctx->seen_last_for_subreq) { pr_coctx->sr_flags[ctx->index] |= NGX_HTTP_LUA_SUBREQ_TRUNCATED; } dd("pr_coctx status: %d", (int) pr_coctx->sr_statuses[ctx->index]); /* copy subrequest response headers */ if (ctx->headers_set) { rc = ngx_http_lua_set_content_type(r, ctx); if (rc != NGX_OK) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "failed to set default content type: %i", rc); return NGX_ERROR; } } pr_coctx->sr_headers[ctx->index] = &r->headers_out; /* copy subrequest response body */ body_str = &pr_coctx->sr_bodies[ctx->index]; len = 0; for (cl = ctx->body; cl; cl = cl->next) { /* ignore all non-memory buffers */ len += cl->buf->last - cl->buf->pos; } body_str->len = len; if (len == 0) { body_str->data = NULL; } else { p = ngx_palloc(r->pool, len); if (p == NULL) { return NGX_ERROR; } body_str->data = p; /* copy from and then free the data buffers */ for (cl = ctx->body; cl; cl = cl->next) { p = ngx_copy(p, cl->buf->pos, cl->buf->last - cl->buf->pos); cl->buf->last = cl->buf->pos; #if 0 dd("free body chain link buf ASAP"); ngx_pfree(r->pool, cl->buf->start); #endif } } if (ctx->body) { ngx_chain_update_chains(r->pool, &pr_ctx->free_bufs, &pr_ctx->busy_bufs, &ctx->body, (ngx_buf_tag_t) &ngx_http_lua_module); dd("free bufs: %p", pr_ctx->free_bufs); } ngx_http_post_request_to_head(pr); if (r != r->connection->data) { r->connection->data = r; } if (rc == NGX_ERROR || rc == NGX_HTTP_CREATED || rc == NGX_HTTP_NO_CONTENT || (rc >= NGX_HTTP_SPECIAL_RESPONSE && rc != NGX_HTTP_CLOSE && rc != NGX_HTTP_REQUEST_TIME_OUT && rc != NGX_HTTP_CLIENT_CLOSED_REQUEST)) { /* emulate ngx_http_special_response_handler */ if (rc > NGX_OK) { r->err_status = rc; r->expect_tested = 1; r->headers_out.content_type.len = 0; r->headers_out.content_length_n = 0; ngx_http_clear_accept_ranges(r); ngx_http_clear_last_modified(r); rc = ngx_http_lua_send_header_if_needed(r, ctx); if (rc == NGX_ERROR) { return NGX_ERROR; } } return NGX_OK; } return rc; } static void ngx_http_lua_handle_subreq_responses(ngx_http_request_t *r, ngx_http_lua_ctx_t *ctx) { ngx_uint_t i, count; ngx_uint_t index; lua_State *co; ngx_str_t *body_str; ngx_table_elt_t *header; ngx_list_part_t *part; ngx_http_headers_out_t *sr_headers; ngx_http_lua_co_ctx_t *coctx; u_char buf[sizeof("Mon, 28 Sep 1970 06:00:00 GMT") - 1]; ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua handle subrequest responses"); coctx = ctx->cur_co_ctx; co = coctx->co; for (index = 0; index < coctx->nsubreqs; index++) { dd("summary: reqs %d, subquery %d, pending %d, req %.*s", (int) coctx->nsubreqs, (int) index, (int) coctx->pending_subreqs, (int) r->uri.len, r->uri.data); /* {{{ construct ret value */ lua_createtable(co, 0 /* narr */, 4 /* nrec */); /* copy captured status */ lua_pushinteger(co, coctx->sr_statuses[index]); lua_setfield(co, -2, "status"); dd("captured subrequest flags: %d", (int) coctx->sr_flags[index]); /* set truncated flag if truncation happens */ if (coctx->sr_flags[index] & NGX_HTTP_LUA_SUBREQ_TRUNCATED) { lua_pushboolean(co, 1); lua_setfield(co, -2, "truncated"); } else { lua_pushboolean(co, 0); lua_setfield(co, -2, "truncated"); } /* copy captured body */ body_str = &coctx->sr_bodies[index]; lua_pushlstring(co, (char *) body_str->data, body_str->len); lua_setfield(co, -2, "body"); if (body_str->data) { dd("free body buffer ASAP"); ngx_pfree(r->pool, body_str->data); } /* copy captured headers */ sr_headers = coctx->sr_headers[index]; part = &sr_headers->headers.part; count = part->nelts; while (part->next) { part = part->next; count += part->nelts; } lua_createtable(co, 0, count + 5); /* res.header */ dd("saving subrequest response headers"); part = &sr_headers->headers.part; header = part->elts; for (i = 0; /* void */; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; header = part->elts; i = 0; } dd("checking sr header %.*s", (int) header[i].key.len, header[i].key.data); #if 1 if (header[i].hash == 0) { continue; } #endif header[i].hash = 0; dd("pushing sr header %.*s", (int) header[i].key.len, header[i].key.data); lua_pushlstring(co, (char *) header[i].key.data, header[i].key.len); /* header key */ lua_pushvalue(co, -1); /* stack: table key key */ /* check if header already exists */ lua_rawget(co, -3); /* stack: table key value */ if (lua_isnil(co, -1)) { lua_pop(co, 1); /* stack: table key */ lua_pushlstring(co, (char *) header[i].value.data, header[i].value.len); /* stack: table key value */ lua_rawset(co, -3); /* stack: table */ } else { if (!lua_istable(co, -1)) { /* already inserted one value */ lua_createtable(co, 4, 0); /* stack: table key value table */ lua_insert(co, -2); /* stack: table key table value */ lua_rawseti(co, -2, 1); /* stack: table key table */ lua_pushlstring(co, (char *) header[i].value.data, header[i].value.len); /* stack: table key table value */ lua_rawseti(co, -2, lua_objlen(co, -2) + 1); /* stack: table key table */ lua_rawset(co, -3); /* stack: table */ } else { lua_pushlstring(co, (char *) header[i].value.data, header[i].value.len); /* stack: table key table value */ lua_rawseti(co, -2, lua_objlen(co, -2) + 1); /* stack: table key table */ lua_pop(co, 2); /* stack: table */ } } } if (sr_headers->content_type.len) { lua_pushliteral(co, "Content-Type"); /* header key */ lua_pushlstring(co, (char *) sr_headers->content_type.data, sr_headers->content_type.len); /* head key value */ lua_rawset(co, -3); /* head */ } if (sr_headers->content_length == NULL && sr_headers->content_length_n >= 0) { lua_pushliteral(co, "Content-Length"); /* header key */ lua_pushnumber(co, (lua_Number) sr_headers->content_length_n); /* head key value */ lua_rawset(co, -3); /* head */ } /* to work-around an issue in ngx_http_static_module * (github issue #41) */ if (sr_headers->location && sr_headers->location->value.len) { lua_pushliteral(co, "Location"); /* header key */ lua_pushlstring(co, (char *) sr_headers->location->value.data, sr_headers->location->value.len); /* head key value */ lua_rawset(co, -3); /* head */ } if (sr_headers->last_modified_time != -1) { if (sr_headers->status != NGX_HTTP_OK && sr_headers->status != NGX_HTTP_PARTIAL_CONTENT && sr_headers->status != NGX_HTTP_NOT_MODIFIED && sr_headers->status != NGX_HTTP_NO_CONTENT) { sr_headers->last_modified_time = -1; sr_headers->last_modified = NULL; } } if (sr_headers->last_modified == NULL && sr_headers->last_modified_time != -1) { (void) ngx_http_time(buf, sr_headers->last_modified_time); lua_pushliteral(co, "Last-Modified"); /* header key */ lua_pushlstring(co, (char *) buf, sizeof(buf)); /* head key value */ lua_rawset(co, -3); /* head */ } lua_setfield(co, -2, "header"); /* }}} */ } } void ngx_http_lua_inject_subrequest_api(lua_State *L) { lua_createtable(L, 0 /* narr */, 2 /* nrec */); /* .location */ lua_pushcfunction(L, ngx_http_lua_ngx_location_capture); lua_setfield(L, -2, "capture"); lua_pushcfunction(L, ngx_http_lua_ngx_location_capture_multi); lua_setfield(L, -2, "capture_multi"); lua_setfield(L, -2, "location"); } static ngx_int_t ngx_http_lua_subrequest(ngx_http_request_t *r, ngx_str_t *uri, ngx_str_t *args, ngx_http_request_t **psr, ngx_http_post_subrequest_t *ps, ngx_uint_t flags) { ngx_time_t *tp; ngx_connection_t *c; ngx_http_request_t *sr; ngx_http_core_srv_conf_t *cscf; #if (nginx_version >= 1009005) if (r->subrequests == 0) { #if defined(NGX_DTRACE) && NGX_DTRACE ngx_http_probe_subrequest_cycle(r, uri, args); #endif ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "lua subrequests cycle while processing \"%V\"", uri); return NGX_ERROR; } #else /* nginx_version <= 1009004 */ r->main->subrequests--; if (r->main->subrequests == 0) { #if defined(NGX_DTRACE) && NGX_DTRACE ngx_http_probe_subrequest_cycle(r, uri, args); #endif ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "lua subrequests cycle while processing \"%V\"", uri); r->main->subrequests = 1; return NGX_ERROR; } #endif sr = ngx_pcalloc(r->pool, sizeof(ngx_http_request_t)); if (sr == NULL) { return NGX_ERROR; } sr->signature = NGX_HTTP_MODULE; c = r->connection; sr->connection = c; sr->ctx = ngx_pcalloc(r->pool, sizeof(void *) * ngx_http_max_module); if (sr->ctx == NULL) { return NGX_ERROR; } if (ngx_list_init(&sr->headers_out.headers, r->pool, 20, sizeof(ngx_table_elt_t)) != NGX_OK) { return NGX_ERROR; } cscf = ngx_http_get_module_srv_conf(r, ngx_http_core_module); sr->main_conf = cscf->ctx->main_conf; sr->srv_conf = cscf->ctx->srv_conf; sr->loc_conf = cscf->ctx->loc_conf; sr->pool = r->pool; sr->headers_in.content_length_n = -1; sr->headers_in.keep_alive_n = -1; ngx_http_clear_content_length(sr); ngx_http_clear_accept_ranges(sr); ngx_http_clear_last_modified(sr); sr->request_body = r->request_body; #if (NGX_HTTP_SPDY) sr->spdy_stream = r->spdy_stream; #endif #if (NGX_HTTP_V2) sr->stream = r->stream; #endif #ifdef HAVE_ALLOW_REQUEST_BODY_UPDATING_PATCH sr->content_length_n = -1; #endif sr->method = NGX_HTTP_GET; sr->http_version = r->http_version; sr->request_line = r->request_line; sr->uri = *uri; if (args) { sr->args = *args; } ngx_log_debug2(NGX_LOG_DEBUG_HTTP, c->log, 0, "lua http subrequest \"%V?%V\"", uri, &sr->args); sr->subrequest_in_memory = (flags & NGX_HTTP_SUBREQUEST_IN_MEMORY) != 0; sr->waited = (flags & NGX_HTTP_SUBREQUEST_WAITED) != 0; sr->unparsed_uri = r->unparsed_uri; sr->method_name = ngx_http_core_get_method; sr->http_protocol = r->http_protocol; ngx_http_set_exten(sr); sr->main = r->main; sr->parent = r; sr->post_subrequest = ps; sr->read_event_handler = ngx_http_request_empty_handler; sr->write_event_handler = ngx_http_handler; sr->variables = r->variables; sr->log_handler = r->log_handler; sr->internal = 1; sr->discard_body = r->discard_body; sr->expect_tested = 1; sr->main_filter_need_in_memory = r->main_filter_need_in_memory; sr->uri_changes = NGX_HTTP_MAX_URI_CHANGES + 1; #if (nginx_version >= 1009005) sr->subrequests = r->subrequests - 1; #endif tp = ngx_timeofday(); sr->start_sec = tp->sec; sr->start_msec = tp->msec; r->main->count++; *psr = sr; #if defined(NGX_DTRACE) && NGX_DTRACE ngx_http_probe_subrequest_start(sr); #endif return ngx_http_post_request(sr, NULL); } static ngx_int_t ngx_http_lua_subrequest_resume(ngx_http_request_t *r) { lua_State *vm; ngx_int_t rc; ngx_uint_t nreqs; ngx_connection_t *c; ngx_http_lua_ctx_t *ctx; ngx_http_lua_co_ctx_t *coctx; ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); if (ctx == NULL) { return NGX_ERROR; } ctx->resume_handler = ngx_http_lua_wev_handler; ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua run subrequests done, resuming lua thread"); coctx = ctx->cur_co_ctx; dd("nsubreqs: %d", (int) coctx->nsubreqs); ngx_http_lua_handle_subreq_responses(r, ctx); dd("free sr_statues/headers/bodies memory ASAP"); #if 1 ngx_pfree(r->pool, coctx->sr_statuses); coctx->sr_statuses = NULL; coctx->sr_headers = NULL; coctx->sr_bodies = NULL; coctx->sr_flags = NULL; #endif c = r->connection; vm = ngx_http_lua_get_lua_vm(r, ctx); nreqs = c->requests; rc = ngx_http_lua_run_thread(vm, r, ctx, coctx->nsubreqs); ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua run thread returned %d", rc); if (rc == NGX_AGAIN) { return ngx_http_lua_run_posted_threads(c, vm, r, ctx, nreqs); } if (rc == NGX_DONE) { ngx_http_lua_finalize_request(r, NGX_DONE); return ngx_http_lua_run_posted_threads(c, vm, r, ctx, nreqs); } /* rc == NGX_ERROR || rc >= NGX_OK */ if (ctx->entered_content_phase) { ngx_http_lua_finalize_request(r, rc); return NGX_DONE; } return rc; } static void ngx_http_lua_cancel_subreq(ngx_http_request_t *r) { ngx_http_posted_request_t *pr; ngx_http_posted_request_t **p; #if 1 r->main->count--; r->main->subrequests++; #endif p = &r->main->posted_requests; for (pr = r->main->posted_requests; pr->next; pr = pr->next) { p = &pr->next; } *p = NULL; r->connection->data = r->parent; } static ngx_int_t ngx_http_post_request_to_head(ngx_http_request_t *r) { ngx_http_posted_request_t *pr; pr = ngx_palloc(r->pool, sizeof(ngx_http_posted_request_t)); if (pr == NULL) { return NGX_ERROR; } pr->request = r; pr->next = r->main->posted_requests; r->main->posted_requests = pr; return NGX_OK; } static ngx_int_t ngx_http_lua_copy_in_file_request_body(ngx_http_request_t *r) { ngx_temp_file_t *tf; ngx_http_request_body_t *body; tf = r->request_body->temp_file; if (!tf->persistent || !tf->clean) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "the request body was not read by ngx_lua"); return NGX_ERROR; } body = ngx_palloc(r->pool, sizeof(ngx_http_request_body_t)); if (body == NULL) { return NGX_ERROR; } ngx_memcpy(body, r->request_body, sizeof(ngx_http_request_body_t)); body->temp_file = ngx_palloc(r->pool, sizeof(ngx_temp_file_t)); if (body->temp_file == NULL) { return NGX_ERROR; } ngx_memcpy(body->temp_file, tf, sizeof(ngx_temp_file_t)); dd("file fd: %d", body->temp_file->file.fd); r->request_body = body; return NGX_OK; } static ngx_int_t ngx_http_lua_copy_request_headers(ngx_http_request_t *sr, ngx_http_request_t *pr, int pr_not_chunked) { ngx_table_elt_t *clh, *header; ngx_list_part_t *part; ngx_uint_t i; u_char *p; off_t len; dd("before: parent req headers count: %d", (int) pr->headers_in.headers.part.nelts); if (ngx_list_init(&sr->headers_in.headers, sr->pool, 20, sizeof(ngx_table_elt_t)) != NGX_OK) { return NGX_ERROR; } if (sr->request_body && !pr_not_chunked) { /* craft our own Content-Length */ len = sr->request_body->buf ? ngx_buf_size(sr->request_body->buf) : 0; clh = ngx_list_push(&sr->headers_in.headers); if (clh == NULL) { return NGX_ERROR; } clh->hash = ngx_http_lua_content_length_hash; clh->key = ngx_http_lua_content_length_header_key; clh->lowcase_key = ngx_pnalloc(sr->pool, clh->key.len); if (clh->lowcase_key == NULL) { return NGX_ERROR; } ngx_strlow(clh->lowcase_key, clh->key.data, clh->key.len); p = ngx_palloc(sr->pool, NGX_OFF_T_LEN); if (p == NULL) { return NGX_ERROR; } clh->value.data = p; clh->value.len = ngx_sprintf(clh->value.data, "%O", len) - clh->value.data; sr->headers_in.content_length = clh; sr->headers_in.content_length_n = len; dd("sr crafted content-length: %.*s", (int) sr->headers_in.content_length->value.len, sr->headers_in.content_length->value.data); } /* copy the parent request's headers */ part = &pr->headers_in.headers.part; header = part->elts; for (i = 0; /* void */; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; header = part->elts; i = 0; } if (!pr_not_chunked && header[i].key.len == sizeof("Content-Length") - 1 && ngx_strncasecmp(header[i].key.data, (u_char *) "Content-Length", sizeof("Content-Length") - 1) == 0) { continue; } dd("sr copied req header %.*s: %.*s", (int) header[i].key.len, header[i].key.data, (int) header[i].value.len, header[i].value.data); if (ngx_http_lua_set_input_header(sr, header[i].key, header[i].value, 0) == NGX_ERROR) { return NGX_ERROR; } } dd("after: parent req headers count: %d", (int) pr->headers_in.headers.part.nelts); return NGX_OK; } /* vi:set ft=c ts=4 sw=4 et fdm=marker: */
./CrossVul/dataset_final_sorted/CWE-444/c/good_3969_0
crossvul-cpp_data_bad_4617_3
// Copyright (c) 2018, Peter Ohler, All rights reserved. #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "debug.h" #include "http.h" #define BUCKET_SIZE 1024 #define BUCKET_MASK 1023 #define MAX_KEY_UNIQ 9 typedef struct _slot { struct _slot *next; const char *key; uint64_t hash; int klen; } *Slot; typedef struct _cache { Slot buckets[BUCKET_SIZE]; } *Cache; struct _cache key_cache; // The rack spec indicates the characters (),/:;<=>?@[]{} are invalid which // clearly is not consisten with RFC7230 so stick with the RFC. static char header_value_chars[256] = "\ xxxxxxxxxxoxxxxxxxxxxxxxxxxxxxxx\ oooooooooooooooooooooooooooooooo\ oooooooooooooooooooooooooooooooo\ ooooooooooooooooooooooooooooooox\ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; static const char *header_keys[] = { "A-IM", "ALPN", "ARC-Authentication-Results", "ARC-Message-Signature", "ARC-Seal", "Accept", "Accept-Additions", "Accept-Charset", "Accept-Datetime", "Accept-Encoding", "Accept-Features", "Accept-Language", "Accept-Language", "Accept-Patch", "Accept-Post", "Accept-Ranges", "Access-Control", "Access-Control-Allow-Credentials", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods", "Access-Control-Allow-Origin", "Access-Control-Max-Age", "Access-Control-Request-Headers", "Access-Control-Request-Method", "Age", "Allow", "Also-Control", "Alt-Svc", "Alt-Used", "Alternate-Recipient", "Alternates", "Apparently-To", "Apply-To-Redirect-Ref", "Approved", "Archive", "Archived-At", "Archived-At", "Article-Names", "Article-Updates", "Authentication-Control", "Authentication-Info", "Authentication-Results", "Authorization", "Auto-Submitted", "Autoforwarded", "Autosubmitted", "Base", "Bcc", "Body", "C-Ext", "C-Man", "C-Opt", "C-PEP", "C-PEP-Info", "Cache-Control", "CalDAV-Timezones", "Cancel-Key", "Cancel-Lock", "Cc", "Close", "Comments", "Comments", "Compliance", "Connection", "Content-Alternative", "Content-Base", "Content-Base", "Content-Description", "Content-Disposition", "Content-Disposition", "Content-Duration", "Content-Encoding", "Content-ID", "Content-ID", "Content-Identifier", "Content-Language", "Content-Language", "Content-Length", "Content-Location", "Content-Location", "Content-MD5", "Content-MD5", "Content-Range", "Content-Return", "Content-Script-Type", "Content-Style-Type", "Content-Transfer-Encoding", "Content-Transfer-Encoding", "Content-Translation-Type", "Content-Type", "Content-Type", "Content-Version", "Content-features", "Control", "Conversion", "Conversion-With-Loss", "Cookie", "Cookie2", "Cost", "DASL", "DAV", "DKIM-Signature", "DL-Expansion-History", "Date", "Date", "Date", "Date-Received", "Default-Style", "Deferred-Delivery", "Delivery-Date", "Delta-Base", "Depth", "Derived-From", "Destination", "Differential-ID", "Digest", "Discarded-X400-IPMS-Extensions", "Discarded-X400-MTS-Extensions", "Disclose-Recipients", "Disposition-Notification-Options", "Disposition-Notification-To", "Distribution", "Downgraded-Bcc", "Downgraded-Cc", "Downgraded-Disposition-Notification-To", "Downgraded-Final-Recipient", "Downgraded-From", "Downgraded-In-Reply-To", "Downgraded-Mail-From", "Downgraded-Message-Id", "Downgraded-Original-Recipient", "Downgraded-Rcpt-To", "Downgraded-References", "Downgraded-Reply-To", "Downgraded-Resent-Bcc", "Downgraded-Resent-Cc", "Downgraded-Resent-From", "Downgraded-Resent-Reply-To", "Downgraded-Resent-Sender", "Downgraded-Resent-To", "Downgraded-Return-Path", "Downgraded-Sender", "Downgraded-To", "EDIINT-Features", "EDIINT-Features", "ETag", "Eesst-Version", "Encoding", "Encrypted", "Errors-To", "Expect", "Expires", "Expires", "Expires", "Expiry-Date", "Ext", "Followup-To", "Form-Sub", "Forwarded", "From", "From", "From", "Generate-Delivery-Report", "GetProfile", "HTTP2-Settings", "Hobareg", "Host", "IM", "If", "If-Match", "If-Modified-Since", "If-None-Match", "If-Range", "If-Schedule-Tag-Match", "If-Unmodified-Since", "Importance", "In-Reply-To", "Incomplete-Copy", "Injection-Date", "Injection-Info", "Jabber-ID", "Jabber-ID", "Keep-Alive", "Keywords", "Keywords", "Label", "Language", "Last-Modified", "Latest-Delivery-Time", "Lines", "Link", "List-Archive", "List-Help", "List-ID", "List-Owner", "List-Post", "List-Subscribe", "List-Unsubscribe", "List-Unsubscribe-Post", "Location", "Lock-Token", "MIME-Version", "MIME-Version", "MMHS-Acp127-Message-Identifier", "MMHS-Authorizing-Users", "MMHS-Codress-Message-Indicator", "MMHS-Copy-Precedence", "MMHS-Exempted-Address", "MMHS-Extended-Authorisation-Info", "MMHS-Handling-Instructions", "MMHS-Message-Instructions", "MMHS-Message-Type", "MMHS-Originator-PLAD", "MMHS-Originator-Reference", "MMHS-Other-Recipients-Indicator-CC", "MMHS-Other-Recipients-Indicator-To", "MMHS-Primary-Precedence", "MMHS-Subject-Indicator-Codes", "MT-Priority", "Man", "Max-Forwards", "Memento-Datetime", "Message-Context", "Message-ID", "Message-ID", "Message-ID", "Message-Type", "Meter", "Method-Check", "Method-Check-Expires", "NNTP-Posting-Date", "NNTP-Posting-Host", "Negotiate", "Newsgroups", "Non-Compliance", "Obsoletes", "Opt", "Optional", "Optional-WWW-Authenticate", "Ordering-Type", "Organization", "Organization", "Origin", "Original-Encoded-Information-Types", "Original-From", "Original-Message-ID", "Original-Recipient", "Original-Sender", "Original-Subject", "Originator-Return-Address", "Overwrite", "P3P", "PEP", "PICS-Label", "PICS-Label", "Path", "Pep-Info", "Position", "Posting-Version", "Pragma", "Prefer", "Preference-Applied", "Prevent-NonDelivery-Report", "Priority", "Privicon", "ProfileObject", "Protocol", "Protocol-Info", "Protocol-Query", "Protocol-Request", "Proxy-Authenticate", "Proxy-Authentication-Info", "Proxy-Authorization", "Proxy-Features", "Proxy-Instruction", "Public", "Public-Key-Pins", "Public-Key-Pins-Report-Only", "Range", "Received", "Received-SPF", "Redirect-Ref", "References", "References", "Referer", "Referer-Root", "Relay-Version", "Reply-By", "Reply-To", "Reply-To", "Require-Recipient-Valid-Since", "Resent-Bcc", "Resent-Cc", "Resent-Date", "Resent-From", "Resent-Message-ID", "Resent-Reply-To", "Resent-Sender", "Resent-To", "Resolution-Hint", "Resolver-Location", "Retry-After", "Return-Path", "SIO-Label", "SIO-Label-History", "SLUG", "Safe", "Schedule-Reply", "Schedule-Tag", "Sec-WebSocket-Accept", "Sec-WebSocket-Extensions", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol", "Sec-WebSocket-Version", "Security-Scheme", "See-Also", "Sender", "Sender", "Sensitivity", "Server", "Set-Cookie", "Set-Cookie2", "SetProfile", "SoapAction", "Solicitation", "Status-URI", "Strict-Transport-Security", "SubOK", "Subject", "Subject", "Subst", "Summary", "Supersedes", "Supersedes", "Surrogate-Capability", "Surrogate-Control", "TCN", "TE", "TTL", "Timeout", "Title", "To", "Topic", "Trailer", "Transfer-Encoding", "UA-Color", "UA-Media", "UA-Pixels", "UA-Resolution", "UA-Windowpixels", "URI", "Upgrade", "Urgency", "User-Agent", "User-Agent", "VBR-Info", "Variant-Vary", "Vary", "Version", "Via", "WWW-Authenticate", "Want-Digest", "Warning", "X-Archived-At", "X-Archived-At", "X-Content-Type-Options", "X-Device-Accept", "X-Device-Accept-Charset", "X-Device-Accept-Encoding", "X-Device-Accept-Language", "X-Device-User-Agent", "X-Frame-Options", "X-Mittente", "X-PGP-Sig", "X-Ricevuta", "X-Riferimento-Message-ID", "X-TipoRicevuta", "X-Trasporto", "X-VerificaSicurezza", "X-XSS-Protection", "X400-Content-Identifier", "X400-Content-Return", "X400-Content-Type", "X400-MTS-Identifier", "X400-Originator", "X400-Received", "X400-Recipients", "X400-Trace", "Xref", NULL }; static uint64_t calc_hash(const char *key, int *lenp) { int len = 0; int klen = *lenp; uint64_t h = 0; bool special = false; if (NULL != key) { const uint8_t *k = (const uint8_t*)key; for (; len < klen; k++) { // narrow to most used range of 0x4D (77) in size if (*k < 0x2D || 0x7A < *k) { special = true; } // fast, just spread it out h = 77 * h + ((*k | 0x20) - 0x2D); len++; } } if (special) { *lenp = -len; } else { *lenp = len; } return h; } static Slot* get_bucketp(uint64_t h) { return key_cache.buckets + (BUCKET_MASK & (h ^ (h << 5) ^ (h >> 7))); } static void key_set(const char *key) { int len = (int)strlen(key); int64_t h = calc_hash(key, &len); Slot *bucket = get_bucketp(h); Slot s; if (NULL != (s = (Slot)AGOO_MALLOC(sizeof(struct _slot)))) { s->hash = h; s->klen = len; s->key = key; s->next = *bucket; *bucket = s; } } void agoo_http_init() { const char **kp = header_keys; memset(&key_cache, 0, sizeof(struct _cache)); for (; NULL != *kp; kp++) { key_set(*kp); } } void agoo_http_cleanup() { Slot *sp = key_cache.buckets; Slot s; Slot n; int i; for (i = BUCKET_SIZE; 0 < i; i--, sp++) { for (s = *sp; NULL != s; s = n) { n = s->next; AGOO_FREE(s); } *sp = NULL; } } int agoo_http_header_ok(agooErr err, const char *key, int klen, const char *value, int vlen) { int len = klen; int64_t h = calc_hash(key, &len); Slot *bucket = get_bucketp(h); Slot s; bool found = false; for (s = *bucket; NULL != s; s = s->next) { if (h == (int64_t)s->hash && len == (int)s->klen && ((0 <= len && len <= MAX_KEY_UNIQ) || 0 == strncasecmp(s->key, key, klen))) { found = true; break; } } if (!found) { char buf[256]; if ((int)sizeof(buf) <= klen) { klen = sizeof(buf) - 1; } strncpy(buf, key, klen); buf[klen] = '\0'; return agoo_err_set(err, AGOO_ERR_ARG, "%s is not a valid HTTP header key.", buf); } // Now check the value. found = false; // reuse as indicator for in a quoted string for (; 0 < vlen; vlen--, value++) { if ('o' != header_value_chars[(uint8_t)*value]) { return agoo_err_set(err, AGOO_ERR_ARG, "%02x is not a valid HTTP header value character.", *value); } if ('"' == *value) { found = !found; } } if (found) { return agoo_err_set(err, AGOO_ERR_ARG, "HTTP header has unmatched quote."); } return AGOO_ERR_OK; } const char* agoo_http_code_message(int code) { const char *msg = ""; switch (code) { case 100: msg = "Continue"; break; case 101: msg = "Switching Protocols"; break; case 102: msg = "Processing"; break; case 200: msg = "OK"; break; case 201: msg = "Created"; break; case 202: msg = "Accepted"; break; case 203: msg = "Non-authoritative Information"; break; case 204: msg = "No Content"; break; case 205: msg = "Reset Content"; break; case 206: msg = "Partial Content"; break; case 207: msg = "Multi-Status"; break; case 208: msg = "Already Reported"; break; case 226: msg = "IM Used"; break; case 300: msg = "Multiple Choices"; break; case 301: msg = "Moved Permanently"; break; case 302: msg = "Found"; break; case 303: msg = "See Other"; break; case 304: msg = "Not Modified"; break; case 305: msg = "Use Proxy"; break; case 307: msg = "Temporary Redirect"; break; case 308: msg = "Permanent Redirect"; break; case 400: msg = "Bad Request"; break; case 401: msg = "Unauthorized"; break; case 402: msg = "Payment Required"; break; case 403: msg = "Forbidden"; break; case 404: msg = "Not Found"; break; case 405: msg = "Method Not Allowed"; break; case 406: msg = "Not Acceptable"; break; case 407: msg = "Proxy Authentication Required"; break; case 408: msg = "Request Timeout"; break; case 409: msg = "Conflict"; break; case 410: msg = "Gone"; break; case 411: msg = "Length Required"; break; case 412: msg = "Precondition Failed"; break; case 413: msg = "Payload Too Large"; break; case 414: msg = "Request-URI Too Long"; break; case 415: msg = "Unsupported Media Type"; break; case 416: msg = "Requested Range Not Satisfiable"; break; case 417: msg = "Expectation Failed"; break; case 418: msg = "I'm a teapot"; break; case 421: msg = "Misdirected Request"; break; case 422: msg = "Unprocessable Entity"; break; case 423: msg = "Locked"; break; case 424: msg = "Failed Dependency"; break; case 426: msg = "Upgrade Required"; break; case 428: msg = "Precondition Required"; break; case 429: msg = "Too Many Requests"; break; case 431: msg = "Request Header Fields Too Large"; break; case 444: msg = "Connection Closed Without Response"; break; case 451: msg = "Unavailable For Legal Reasons"; break; case 499: msg = "Client Closed Request"; break; case 500: msg = "Internal Server Error"; break; case 501: msg = "Not Implemented"; break; case 502: msg = "Bad Gateway"; break; case 503: msg = "Service Unavailable"; break; case 504: msg = "Gateway Timeout"; break; case 505: msg = "HTTP Version Not Supported"; break; case 506: msg = "Variant Also Negotiates"; break; case 507: msg = "Insufficient Storage"; break; case 508: msg = "Loop Detected"; break; case 510: msg = "Not Extended"; break; case 511: msg = "Network Authentication Required"; break; case 599: msg = "Network Connect Timeout Error"; break; default: break; } return msg; }
./CrossVul/dataset_final_sorted/CWE-444/c/bad_4617_3
crossvul-cpp_data_bad_1353_0
/* * Copyright (C) Igor Sysoev * Copyright (C) Nginx, Inc. */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> #include <nginx.h> static ngx_int_t ngx_http_send_error_page(ngx_http_request_t *r, ngx_http_err_page_t *err_page); static ngx_int_t ngx_http_send_special_response(ngx_http_request_t *r, ngx_http_core_loc_conf_t *clcf, ngx_uint_t err); static ngx_int_t ngx_http_send_refresh(ngx_http_request_t *r); static u_char ngx_http_error_full_tail[] = "<hr><center>" NGINX_VER "</center>" CRLF "</body>" CRLF "</html>" CRLF ; static u_char ngx_http_error_build_tail[] = "<hr><center>" NGINX_VER_BUILD "</center>" CRLF "</body>" CRLF "</html>" CRLF ; static u_char ngx_http_error_tail[] = "<hr><center>nginx</center>" CRLF "</body>" CRLF "</html>" CRLF ; static u_char ngx_http_msie_padding[] = "<!-- a padding to disable MSIE and Chrome friendly error page -->" CRLF "<!-- a padding to disable MSIE and Chrome friendly error page -->" CRLF "<!-- a padding to disable MSIE and Chrome friendly error page -->" CRLF "<!-- a padding to disable MSIE and Chrome friendly error page -->" CRLF "<!-- a padding to disable MSIE and Chrome friendly error page -->" CRLF "<!-- a padding to disable MSIE and Chrome friendly error page -->" CRLF ; static u_char ngx_http_msie_refresh_head[] = "<html><head><meta http-equiv=\"Refresh\" content=\"0; URL="; static u_char ngx_http_msie_refresh_tail[] = "\"></head><body></body></html>" CRLF; static char ngx_http_error_301_page[] = "<html>" CRLF "<head><title>301 Moved Permanently</title></head>" CRLF "<body>" CRLF "<center><h1>301 Moved Permanently</h1></center>" CRLF ; static char ngx_http_error_302_page[] = "<html>" CRLF "<head><title>302 Found</title></head>" CRLF "<body>" CRLF "<center><h1>302 Found</h1></center>" CRLF ; static char ngx_http_error_303_page[] = "<html>" CRLF "<head><title>303 See Other</title></head>" CRLF "<body>" CRLF "<center><h1>303 See Other</h1></center>" CRLF ; static char ngx_http_error_307_page[] = "<html>" CRLF "<head><title>307 Temporary Redirect</title></head>" CRLF "<body>" CRLF "<center><h1>307 Temporary Redirect</h1></center>" CRLF ; static char ngx_http_error_308_page[] = "<html>" CRLF "<head><title>308 Permanent Redirect</title></head>" CRLF "<body>" CRLF "<center><h1>308 Permanent Redirect</h1></center>" CRLF ; static char ngx_http_error_400_page[] = "<html>" CRLF "<head><title>400 Bad Request</title></head>" CRLF "<body>" CRLF "<center><h1>400 Bad Request</h1></center>" CRLF ; static char ngx_http_error_401_page[] = "<html>" CRLF "<head><title>401 Authorization Required</title></head>" CRLF "<body>" CRLF "<center><h1>401 Authorization Required</h1></center>" CRLF ; static char ngx_http_error_402_page[] = "<html>" CRLF "<head><title>402 Payment Required</title></head>" CRLF "<body>" CRLF "<center><h1>402 Payment Required</h1></center>" CRLF ; static char ngx_http_error_403_page[] = "<html>" CRLF "<head><title>403 Forbidden</title></head>" CRLF "<body>" CRLF "<center><h1>403 Forbidden</h1></center>" CRLF ; static char ngx_http_error_404_page[] = "<html>" CRLF "<head><title>404 Not Found</title></head>" CRLF "<body>" CRLF "<center><h1>404 Not Found</h1></center>" CRLF ; static char ngx_http_error_405_page[] = "<html>" CRLF "<head><title>405 Not Allowed</title></head>" CRLF "<body>" CRLF "<center><h1>405 Not Allowed</h1></center>" CRLF ; static char ngx_http_error_406_page[] = "<html>" CRLF "<head><title>406 Not Acceptable</title></head>" CRLF "<body>" CRLF "<center><h1>406 Not Acceptable</h1></center>" CRLF ; static char ngx_http_error_408_page[] = "<html>" CRLF "<head><title>408 Request Time-out</title></head>" CRLF "<body>" CRLF "<center><h1>408 Request Time-out</h1></center>" CRLF ; static char ngx_http_error_409_page[] = "<html>" CRLF "<head><title>409 Conflict</title></head>" CRLF "<body>" CRLF "<center><h1>409 Conflict</h1></center>" CRLF ; static char ngx_http_error_410_page[] = "<html>" CRLF "<head><title>410 Gone</title></head>" CRLF "<body>" CRLF "<center><h1>410 Gone</h1></center>" CRLF ; static char ngx_http_error_411_page[] = "<html>" CRLF "<head><title>411 Length Required</title></head>" CRLF "<body>" CRLF "<center><h1>411 Length Required</h1></center>" CRLF ; static char ngx_http_error_412_page[] = "<html>" CRLF "<head><title>412 Precondition Failed</title></head>" CRLF "<body>" CRLF "<center><h1>412 Precondition Failed</h1></center>" CRLF ; static char ngx_http_error_413_page[] = "<html>" CRLF "<head><title>413 Request Entity Too Large</title></head>" CRLF "<body>" CRLF "<center><h1>413 Request Entity Too Large</h1></center>" CRLF ; static char ngx_http_error_414_page[] = "<html>" CRLF "<head><title>414 Request-URI Too Large</title></head>" CRLF "<body>" CRLF "<center><h1>414 Request-URI Too Large</h1></center>" CRLF ; static char ngx_http_error_415_page[] = "<html>" CRLF "<head><title>415 Unsupported Media Type</title></head>" CRLF "<body>" CRLF "<center><h1>415 Unsupported Media Type</h1></center>" CRLF ; static char ngx_http_error_416_page[] = "<html>" CRLF "<head><title>416 Requested Range Not Satisfiable</title></head>" CRLF "<body>" CRLF "<center><h1>416 Requested Range Not Satisfiable</h1></center>" CRLF ; static char ngx_http_error_421_page[] = "<html>" CRLF "<head><title>421 Misdirected Request</title></head>" CRLF "<body>" CRLF "<center><h1>421 Misdirected Request</h1></center>" CRLF ; static char ngx_http_error_429_page[] = "<html>" CRLF "<head><title>429 Too Many Requests</title></head>" CRLF "<body>" CRLF "<center><h1>429 Too Many Requests</h1></center>" CRLF ; static char ngx_http_error_494_page[] = "<html>" CRLF "<head><title>400 Request Header Or Cookie Too Large</title></head>" CRLF "<body>" CRLF "<center><h1>400 Bad Request</h1></center>" CRLF "<center>Request Header Or Cookie Too Large</center>" CRLF ; static char ngx_http_error_495_page[] = "<html>" CRLF "<head><title>400 The SSL certificate error</title></head>" CRLF "<body>" CRLF "<center><h1>400 Bad Request</h1></center>" CRLF "<center>The SSL certificate error</center>" CRLF ; static char ngx_http_error_496_page[] = "<html>" CRLF "<head><title>400 No required SSL certificate was sent</title></head>" CRLF "<body>" CRLF "<center><h1>400 Bad Request</h1></center>" CRLF "<center>No required SSL certificate was sent</center>" CRLF ; static char ngx_http_error_497_page[] = "<html>" CRLF "<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>" CRLF "<body>" CRLF "<center><h1>400 Bad Request</h1></center>" CRLF "<center>The plain HTTP request was sent to HTTPS port</center>" CRLF ; static char ngx_http_error_500_page[] = "<html>" CRLF "<head><title>500 Internal Server Error</title></head>" CRLF "<body>" CRLF "<center><h1>500 Internal Server Error</h1></center>" CRLF ; static char ngx_http_error_501_page[] = "<html>" CRLF "<head><title>501 Not Implemented</title></head>" CRLF "<body>" CRLF "<center><h1>501 Not Implemented</h1></center>" CRLF ; static char ngx_http_error_502_page[] = "<html>" CRLF "<head><title>502 Bad Gateway</title></head>" CRLF "<body>" CRLF "<center><h1>502 Bad Gateway</h1></center>" CRLF ; static char ngx_http_error_503_page[] = "<html>" CRLF "<head><title>503 Service Temporarily Unavailable</title></head>" CRLF "<body>" CRLF "<center><h1>503 Service Temporarily Unavailable</h1></center>" CRLF ; static char ngx_http_error_504_page[] = "<html>" CRLF "<head><title>504 Gateway Time-out</title></head>" CRLF "<body>" CRLF "<center><h1>504 Gateway Time-out</h1></center>" CRLF ; static char ngx_http_error_505_page[] = "<html>" CRLF "<head><title>505 HTTP Version Not Supported</title></head>" CRLF "<body>" CRLF "<center><h1>505 HTTP Version Not Supported</h1></center>" CRLF ; static char ngx_http_error_507_page[] = "<html>" CRLF "<head><title>507 Insufficient Storage</title></head>" CRLF "<body>" CRLF "<center><h1>507 Insufficient Storage</h1></center>" CRLF ; static ngx_str_t ngx_http_error_pages[] = { ngx_null_string, /* 201, 204 */ #define NGX_HTTP_LAST_2XX 202 #define NGX_HTTP_OFF_3XX (NGX_HTTP_LAST_2XX - 201) /* ngx_null_string, */ /* 300 */ ngx_string(ngx_http_error_301_page), ngx_string(ngx_http_error_302_page), ngx_string(ngx_http_error_303_page), ngx_null_string, /* 304 */ ngx_null_string, /* 305 */ ngx_null_string, /* 306 */ ngx_string(ngx_http_error_307_page), ngx_string(ngx_http_error_308_page), #define NGX_HTTP_LAST_3XX 309 #define NGX_HTTP_OFF_4XX (NGX_HTTP_LAST_3XX - 301 + NGX_HTTP_OFF_3XX) ngx_string(ngx_http_error_400_page), ngx_string(ngx_http_error_401_page), ngx_string(ngx_http_error_402_page), ngx_string(ngx_http_error_403_page), ngx_string(ngx_http_error_404_page), ngx_string(ngx_http_error_405_page), ngx_string(ngx_http_error_406_page), ngx_null_string, /* 407 */ ngx_string(ngx_http_error_408_page), ngx_string(ngx_http_error_409_page), ngx_string(ngx_http_error_410_page), ngx_string(ngx_http_error_411_page), ngx_string(ngx_http_error_412_page), ngx_string(ngx_http_error_413_page), ngx_string(ngx_http_error_414_page), ngx_string(ngx_http_error_415_page), ngx_string(ngx_http_error_416_page), ngx_null_string, /* 417 */ ngx_null_string, /* 418 */ ngx_null_string, /* 419 */ ngx_null_string, /* 420 */ ngx_string(ngx_http_error_421_page), ngx_null_string, /* 422 */ ngx_null_string, /* 423 */ ngx_null_string, /* 424 */ ngx_null_string, /* 425 */ ngx_null_string, /* 426 */ ngx_null_string, /* 427 */ ngx_null_string, /* 428 */ ngx_string(ngx_http_error_429_page), #define NGX_HTTP_LAST_4XX 430 #define NGX_HTTP_OFF_5XX (NGX_HTTP_LAST_4XX - 400 + NGX_HTTP_OFF_4XX) ngx_string(ngx_http_error_494_page), /* 494, request header too large */ ngx_string(ngx_http_error_495_page), /* 495, https certificate error */ ngx_string(ngx_http_error_496_page), /* 496, https no certificate */ ngx_string(ngx_http_error_497_page), /* 497, http to https */ ngx_string(ngx_http_error_404_page), /* 498, canceled */ ngx_null_string, /* 499, client has closed connection */ ngx_string(ngx_http_error_500_page), ngx_string(ngx_http_error_501_page), ngx_string(ngx_http_error_502_page), ngx_string(ngx_http_error_503_page), ngx_string(ngx_http_error_504_page), ngx_string(ngx_http_error_505_page), ngx_null_string, /* 506 */ ngx_string(ngx_http_error_507_page) #define NGX_HTTP_LAST_5XX 508 }; ngx_int_t ngx_http_special_response_handler(ngx_http_request_t *r, ngx_int_t error) { ngx_uint_t i, err; ngx_http_err_page_t *err_page; ngx_http_core_loc_conf_t *clcf; ngx_log_debug3(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "http special response: %i, \"%V?%V\"", error, &r->uri, &r->args); r->err_status = error; if (r->keepalive) { switch (error) { case NGX_HTTP_BAD_REQUEST: case NGX_HTTP_REQUEST_ENTITY_TOO_LARGE: case NGX_HTTP_REQUEST_URI_TOO_LARGE: case NGX_HTTP_TO_HTTPS: case NGX_HTTPS_CERT_ERROR: case NGX_HTTPS_NO_CERT: case NGX_HTTP_INTERNAL_SERVER_ERROR: case NGX_HTTP_NOT_IMPLEMENTED: r->keepalive = 0; } } if (r->lingering_close) { switch (error) { case NGX_HTTP_BAD_REQUEST: case NGX_HTTP_TO_HTTPS: case NGX_HTTPS_CERT_ERROR: case NGX_HTTPS_NO_CERT: r->lingering_close = 0; } } r->headers_out.content_type.len = 0; clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); if (!r->error_page && clcf->error_pages && r->uri_changes != 0) { if (clcf->recursive_error_pages == 0) { r->error_page = 1; } err_page = clcf->error_pages->elts; for (i = 0; i < clcf->error_pages->nelts; i++) { if (err_page[i].status == error) { return ngx_http_send_error_page(r, &err_page[i]); } } } r->expect_tested = 1; if (ngx_http_discard_request_body(r) != NGX_OK) { r->keepalive = 0; } if (clcf->msie_refresh && r->headers_in.msie && (error == NGX_HTTP_MOVED_PERMANENTLY || error == NGX_HTTP_MOVED_TEMPORARILY)) { return ngx_http_send_refresh(r); } if (error == NGX_HTTP_CREATED) { /* 201 */ err = 0; } else if (error == NGX_HTTP_NO_CONTENT) { /* 204 */ err = 0; } else if (error >= NGX_HTTP_MOVED_PERMANENTLY && error < NGX_HTTP_LAST_3XX) { /* 3XX */ err = error - NGX_HTTP_MOVED_PERMANENTLY + NGX_HTTP_OFF_3XX; } else if (error >= NGX_HTTP_BAD_REQUEST && error < NGX_HTTP_LAST_4XX) { /* 4XX */ err = error - NGX_HTTP_BAD_REQUEST + NGX_HTTP_OFF_4XX; } else if (error >= NGX_HTTP_NGINX_CODES && error < NGX_HTTP_LAST_5XX) { /* 49X, 5XX */ err = error - NGX_HTTP_NGINX_CODES + NGX_HTTP_OFF_5XX; switch (error) { case NGX_HTTP_TO_HTTPS: case NGX_HTTPS_CERT_ERROR: case NGX_HTTPS_NO_CERT: case NGX_HTTP_REQUEST_HEADER_TOO_LARGE: r->err_status = NGX_HTTP_BAD_REQUEST; } } else { /* unknown code, zero body */ err = 0; } return ngx_http_send_special_response(r, clcf, err); } ngx_int_t ngx_http_filter_finalize_request(ngx_http_request_t *r, ngx_module_t *m, ngx_int_t error) { void *ctx; ngx_int_t rc; ngx_http_clean_header(r); ctx = NULL; if (m) { ctx = r->ctx[m->ctx_index]; } /* clear the modules contexts */ ngx_memzero(r->ctx, sizeof(void *) * ngx_http_max_module); if (m) { r->ctx[m->ctx_index] = ctx; } r->filter_finalize = 1; rc = ngx_http_special_response_handler(r, error); /* NGX_ERROR resets any pending data */ switch (rc) { case NGX_OK: case NGX_DONE: return NGX_ERROR; default: return rc; } } void ngx_http_clean_header(ngx_http_request_t *r) { ngx_memzero(&r->headers_out.status, sizeof(ngx_http_headers_out_t) - offsetof(ngx_http_headers_out_t, status)); r->headers_out.headers.part.nelts = 0; r->headers_out.headers.part.next = NULL; r->headers_out.headers.last = &r->headers_out.headers.part; r->headers_out.content_length_n = -1; r->headers_out.last_modified_time = -1; } static ngx_int_t ngx_http_send_error_page(ngx_http_request_t *r, ngx_http_err_page_t *err_page) { ngx_int_t overwrite; ngx_str_t uri, args; ngx_table_elt_t *location; ngx_http_core_loc_conf_t *clcf; overwrite = err_page->overwrite; if (overwrite && overwrite != NGX_HTTP_OK) { r->expect_tested = 1; } if (overwrite >= 0) { r->err_status = overwrite; } if (ngx_http_complex_value(r, &err_page->value, &uri) != NGX_OK) { return NGX_ERROR; } if (uri.len && uri.data[0] == '/') { if (err_page->value.lengths) { ngx_http_split_args(r, &uri, &args); } else { args = err_page->args; } if (r->method != NGX_HTTP_HEAD) { r->method = NGX_HTTP_GET; r->method_name = ngx_http_core_get_method; } return ngx_http_internal_redirect(r, &uri, &args); } if (uri.len && uri.data[0] == '@') { return ngx_http_named_location(r, &uri); } location = ngx_list_push(&r->headers_out.headers); if (location == NULL) { return NGX_ERROR; } if (overwrite != NGX_HTTP_MOVED_PERMANENTLY && overwrite != NGX_HTTP_MOVED_TEMPORARILY && overwrite != NGX_HTTP_SEE_OTHER && overwrite != NGX_HTTP_TEMPORARY_REDIRECT && overwrite != NGX_HTTP_PERMANENT_REDIRECT) { r->err_status = NGX_HTTP_MOVED_TEMPORARILY; } location->hash = 1; ngx_str_set(&location->key, "Location"); location->value = uri; ngx_http_clear_location(r); r->headers_out.location = location; clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); if (clcf->msie_refresh && r->headers_in.msie) { return ngx_http_send_refresh(r); } return ngx_http_send_special_response(r, clcf, r->err_status - NGX_HTTP_MOVED_PERMANENTLY + NGX_HTTP_OFF_3XX); } static ngx_int_t ngx_http_send_special_response(ngx_http_request_t *r, ngx_http_core_loc_conf_t *clcf, ngx_uint_t err) { u_char *tail; size_t len; ngx_int_t rc; ngx_buf_t *b; ngx_uint_t msie_padding; ngx_chain_t out[3]; if (clcf->server_tokens == NGX_HTTP_SERVER_TOKENS_ON) { len = sizeof(ngx_http_error_full_tail) - 1; tail = ngx_http_error_full_tail; } else if (clcf->server_tokens == NGX_HTTP_SERVER_TOKENS_BUILD) { len = sizeof(ngx_http_error_build_tail) - 1; tail = ngx_http_error_build_tail; } else { len = sizeof(ngx_http_error_tail) - 1; tail = ngx_http_error_tail; } msie_padding = 0; if (ngx_http_error_pages[err].len) { r->headers_out.content_length_n = ngx_http_error_pages[err].len + len; if (clcf->msie_padding && (r->headers_in.msie || r->headers_in.chrome) && r->http_version >= NGX_HTTP_VERSION_10 && err >= NGX_HTTP_OFF_4XX) { r->headers_out.content_length_n += sizeof(ngx_http_msie_padding) - 1; msie_padding = 1; } r->headers_out.content_type_len = sizeof("text/html") - 1; ngx_str_set(&r->headers_out.content_type, "text/html"); r->headers_out.content_type_lowcase = NULL; } else { r->headers_out.content_length_n = 0; } if (r->headers_out.content_length) { r->headers_out.content_length->hash = 0; r->headers_out.content_length = NULL; } ngx_http_clear_accept_ranges(r); ngx_http_clear_last_modified(r); ngx_http_clear_etag(r); rc = ngx_http_send_header(r); if (rc == NGX_ERROR || r->header_only) { return rc; } if (ngx_http_error_pages[err].len == 0) { return ngx_http_send_special(r, NGX_HTTP_LAST); } b = ngx_calloc_buf(r->pool); if (b == NULL) { return NGX_ERROR; } b->memory = 1; b->pos = ngx_http_error_pages[err].data; b->last = ngx_http_error_pages[err].data + ngx_http_error_pages[err].len; out[0].buf = b; out[0].next = &out[1]; b = ngx_calloc_buf(r->pool); if (b == NULL) { return NGX_ERROR; } b->memory = 1; b->pos = tail; b->last = tail + len; out[1].buf = b; out[1].next = NULL; if (msie_padding) { b = ngx_calloc_buf(r->pool); if (b == NULL) { return NGX_ERROR; } b->memory = 1; b->pos = ngx_http_msie_padding; b->last = ngx_http_msie_padding + sizeof(ngx_http_msie_padding) - 1; out[1].next = &out[2]; out[2].buf = b; out[2].next = NULL; } if (r == r->main) { b->last_buf = 1; } b->last_in_chain = 1; return ngx_http_output_filter(r, &out[0]); } static ngx_int_t ngx_http_send_refresh(ngx_http_request_t *r) { u_char *p, *location; size_t len, size; uintptr_t escape; ngx_int_t rc; ngx_buf_t *b; ngx_chain_t out; len = r->headers_out.location->value.len; location = r->headers_out.location->value.data; escape = 2 * ngx_escape_uri(NULL, location, len, NGX_ESCAPE_REFRESH); size = sizeof(ngx_http_msie_refresh_head) - 1 + escape + len + sizeof(ngx_http_msie_refresh_tail) - 1; r->err_status = NGX_HTTP_OK; r->headers_out.content_type_len = sizeof("text/html") - 1; ngx_str_set(&r->headers_out.content_type, "text/html"); r->headers_out.content_type_lowcase = NULL; r->headers_out.location->hash = 0; r->headers_out.location = NULL; r->headers_out.content_length_n = size; if (r->headers_out.content_length) { r->headers_out.content_length->hash = 0; r->headers_out.content_length = NULL; } ngx_http_clear_accept_ranges(r); ngx_http_clear_last_modified(r); ngx_http_clear_etag(r); rc = ngx_http_send_header(r); if (rc == NGX_ERROR || r->header_only) { return rc; } b = ngx_create_temp_buf(r->pool, size); if (b == NULL) { return NGX_ERROR; } p = ngx_cpymem(b->pos, ngx_http_msie_refresh_head, sizeof(ngx_http_msie_refresh_head) - 1); if (escape == 0) { p = ngx_cpymem(p, location, len); } else { p = (u_char *) ngx_escape_uri(p, location, len, NGX_ESCAPE_REFRESH); } b->last = ngx_cpymem(p, ngx_http_msie_refresh_tail, sizeof(ngx_http_msie_refresh_tail) - 1); b->last_buf = (r == r->main) ? 1 : 0; b->last_in_chain = 1; out.buf = b; out.next = NULL; return ngx_http_output_filter(r, &out); }
./CrossVul/dataset_final_sorted/CWE-444/c/bad_1353_0
crossvul-cpp_data_good_4008_0
/* Copyright (C) 2011 the GSS-PROXY contributors, see COPYING for license */ #include "config.h" #include <pthread.h> #include <stdint.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include "gp_proxy.h" #define DEFAULT_WORKER_THREADS_NUM 5 #define GP_QUERY_IN 0 #define GP_QUERY_OUT 1 #define GP_QUERY_ERR 2 struct gp_query { struct gp_query *next; struct gp_conn *conn; uint8_t *buffer; size_t buflen; int status; }; struct gp_thread { struct gp_thread *prev; struct gp_thread *next; struct gp_workers *pool; pthread_t tid; struct gp_query *query; pthread_mutex_t cond_mutex; pthread_cond_t cond_wakeup; }; struct gp_workers { pthread_mutex_t lock; struct gssproxy_ctx *gpctx; bool shutdown; struct gp_query *wait_list; struct gp_query *reply_list; struct gp_thread *free_list; struct gp_thread *busy_list; int num_threads; int sig_pipe[2]; }; static void *gp_worker_main(void *pvt); static void gp_handle_query(struct gp_workers *w, struct gp_query *q); static void gp_handle_reply(verto_ctx *vctx, verto_ev *ev); /** DISPATCHER FUNCTIONS **/ int gp_workers_init(struct gssproxy_ctx *gpctx) { struct gp_workers *w; struct gp_thread *t; pthread_attr_t attr; verto_ev *ev; int vflags; int ret; int i; w = calloc(1, sizeof(struct gp_workers)); if (!w) { return ENOMEM; } w->gpctx = gpctx; /* init global queue mutex */ ret = pthread_mutex_init(&w->lock, NULL); if (ret) { free(w); return ENOMEM; } if (gpctx->config->num_workers > 0) { w->num_threads = gpctx->config->num_workers; } else { w->num_threads = DEFAULT_WORKER_THREADS_NUM; } /* make thread joinable (portability) */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); /* init all workers */ for (i = 0; i < w->num_threads; i++) { t = calloc(1, sizeof(struct gp_thread)); if (!t) { ret = -1; goto done; } t->pool = w; ret = pthread_cond_init(&t->cond_wakeup, NULL); if (ret) { free(t); goto done; } ret = pthread_mutex_init(&t->cond_mutex, NULL); if (ret) { free(t); goto done; } ret = pthread_create(&t->tid, &attr, gp_worker_main, t); if (ret) { free(t); goto done; } LIST_ADD(w->free_list, t); } /* add wakeup pipe, so that threads can hand back replies to the * dispatcher */ ret = pipe2(w->sig_pipe, O_NONBLOCK | O_CLOEXEC); if (ret == -1) { goto done; } vflags = VERTO_EV_FLAG_PERSIST | VERTO_EV_FLAG_IO_READ; ev = verto_add_io(gpctx->vctx, vflags, gp_handle_reply, w->sig_pipe[0]); if (!ev) { ret = -1; goto done; } verto_set_private(ev, w, NULL); gpctx->workers = w; ret = 0; done: if (ret) { gp_workers_free(w); } return ret; } void gp_workers_free(struct gp_workers *w) { struct gp_thread *t; void *retval; /* ======> POOL LOCK */ pthread_mutex_lock(&w->lock); w->shutdown = true; /* <====== POOL LOCK */ pthread_mutex_unlock(&w->lock); /* we do not run the following operations within * the lock, or deadlocks may arise for threads * that are just finishing doing some work */ /* we guarantee nobody is touching these lists by * preventing workers from touching the free/busy * lists when a 'shutdown' is in progress */ while (w->free_list) { /* pick threads one by one */ t = w->free_list; LIST_DEL(w->free_list, t); /* wake up threads, then join them */ /* ======> COND_MUTEX */ pthread_mutex_lock(&t->cond_mutex); pthread_cond_signal(&t->cond_wakeup); /* <====== COND_MUTEX */ pthread_mutex_unlock(&t->cond_mutex); pthread_join(t->tid, &retval); pthread_mutex_destroy(&t->cond_mutex); pthread_cond_destroy(&t->cond_wakeup); free(t); } /* do the same with the busy list */ while (w->busy_list) { /* pick threads one by one */ t = w->busy_list; LIST_DEL(w->free_list, t); /* wake up threads, then join them */ /* ======> COND_MUTEX */ pthread_mutex_lock(&t->cond_mutex); pthread_cond_signal(&t->cond_wakeup); /* <====== COND_MUTEX */ pthread_mutex_unlock(&t->cond_mutex); pthread_join(t->tid, &retval); pthread_mutex_destroy(&t->cond_mutex); pthread_cond_destroy(&t->cond_wakeup); free(t); } close(w->sig_pipe[0]); close(w->sig_pipe[1]); pthread_mutex_destroy(&w->lock); free(w); } static void gp_query_assign(struct gp_workers *w, struct gp_query *q) { struct gp_thread *t = NULL; /* then either find a free thread or queue in the wait list */ /* ======> POOL LOCK */ pthread_mutex_lock(&w->lock); if (w->free_list) { t = w->free_list; LIST_DEL(w->free_list, t); LIST_ADD(w->busy_list, t); } /* <====== POOL LOCK */ pthread_mutex_unlock(&w->lock); if (t) { /* found free thread, assign work */ /* ======> COND_MUTEX */ pthread_mutex_lock(&t->cond_mutex); /* hand over the query */ t->query = q; pthread_cond_signal(&t->cond_wakeup); /* <====== COND_MUTEX */ pthread_mutex_unlock(&t->cond_mutex); } else { /* all threads are busy, store in wait list */ /* only the dispatcher handles wait_list * so we do not need to lock around it */ q->next = w->wait_list; w->wait_list = q; } } static void gp_query_free(struct gp_query *q, bool free_buffer) { if (!q) { return; } if (free_buffer) { free(q->buffer); } free(q); } int gp_query_new(struct gp_workers *w, struct gp_conn *conn, uint8_t *buffer, size_t buflen) { struct gp_query *q; /* create query struct */ q = calloc(1, sizeof(struct gp_query)); if (!q) { return ENOMEM; } q->conn = conn; q->buffer = buffer; q->buflen = buflen; gp_query_assign(w, q); return 0; } static void gp_handle_reply(verto_ctx *vctx, verto_ev *ev) { struct gp_workers *w; struct gp_query *q = NULL; char dummy; int ret; w = verto_get_private(ev); /* first read out the dummy so the pipe doesn't get clogged */ ret = read(w->sig_pipe[0], &dummy, 1); if (ret) { /* ignore errors */ } /* grab a query reply if any */ if (w->reply_list) { /* ======> POOL LOCK */ pthread_mutex_lock(&w->lock); if (w->reply_list != NULL) { q = w->reply_list; w->reply_list = q->next; } /* <====== POOL LOCK */ pthread_mutex_unlock(&w->lock); } if (q) { switch (q->status) { case GP_QUERY_IN: /* ?! fallback and kill client conn */ case GP_QUERY_ERR: GPDEBUGN(3, "[status] Handling query error, terminating CID %d.\n", gp_conn_get_cid(q->conn)); gp_conn_free(q->conn); gp_query_free(q, true); break; case GP_QUERY_OUT: GPDEBUGN(3, "[status] Handling query reply: %p (%zu)\n", q->buffer, q->buflen); gp_socket_send_data(vctx, q->conn, q->buffer, q->buflen); gp_query_free(q, false); break; } } /* while we are at it, check if there is anything in the wait list * we need to process, as one thread just got free :-) */ q = NULL; if (w->wait_list) { /* only the dispatcher handles wait_list * so we do not need to lock around it */ if (w->wait_list) { q = w->wait_list; w->wait_list = q->next; q->next = NULL; } } if (q) { gp_query_assign(w, q); } } /** WORKER THREADS **/ static void *gp_worker_main(void *pvt) { struct gp_thread *t = (struct gp_thread *)pvt; struct gp_query *q = NULL; char dummy = 0; int ret; while (!t->pool->shutdown) { /* initialize debug client id to 0 until work is scheduled */ gp_debug_set_conn_id(0); /* ======> COND_MUTEX */ pthread_mutex_lock(&t->cond_mutex); while (t->query == NULL) { /* wait for next query */ pthread_cond_wait(&t->cond_wakeup, &t->cond_mutex); if (t->pool->shutdown) { pthread_mutex_unlock(&t->cond_mutex); pthread_exit(NULL); } } /* grab the query off the shared pointer */ q = t->query; t->query = NULL; /* <====== COND_MUTEX */ pthread_mutex_unlock(&t->cond_mutex); /* set client id before hndling requests */ gp_debug_set_conn_id(gp_conn_get_cid(q->conn)); /* handle the client request */ GPDEBUGN(3, "[status] Handling query input: %p (%zu)\n", q->buffer, q->buflen); gp_handle_query(t->pool, q); GPDEBUGN(3 ,"[status] Handling query output: %p (%zu)\n", q->buffer, q->buflen); /* now get lock on main queue, to play with the reply list */ /* ======> POOL LOCK */ pthread_mutex_lock(&t->pool->lock); /* put back query so that dispatcher can send reply */ q->next = t->pool->reply_list; t->pool->reply_list = q; /* add us back to the free list but only if we are not * shutting down */ if (!t->pool->shutdown) { LIST_DEL(t->pool->busy_list, t); LIST_ADD(t->pool->free_list, t); } /* <====== POOL LOCK */ pthread_mutex_unlock(&t->pool->lock); /* and wake up dispatcher so it will handle it */ ret = write(t->pool->sig_pipe[1], &dummy, 1); if (ret == -1) { GPERROR("Failed to signal dispatcher!"); } } pthread_exit(NULL); } static void gp_handle_query(struct gp_workers *w, struct gp_query *q) { struct gp_call_ctx gpcall = { 0 }; uint8_t *buffer; size_t buflen; int ret; /* find service */ gpcall.gpctx = w->gpctx; gpcall.service = gp_creds_match_conn(w->gpctx, q->conn); if (!gpcall.service) { q->status = GP_QUERY_ERR; return; } gpcall.connection = q->conn; ret = gp_rpc_process_call(&gpcall, q->buffer, q->buflen, &buffer, &buflen); if (ret) { q->status = GP_QUERY_ERR; } else { q->status = GP_QUERY_OUT; free(q->buffer); q->buffer = buffer; q->buflen = buflen; } if (gpcall.destroy_callback) { gpcall.destroy_callback(gpcall.destroy_callback_data); } }
./CrossVul/dataset_final_sorted/CWE-667/c/good_4008_0
crossvul-cpp_data_bad_4008_0
/* Copyright (C) 2011 the GSS-PROXY contributors, see COPYING for license */ #include "config.h" #include <pthread.h> #include <stdint.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include "gp_proxy.h" #define DEFAULT_WORKER_THREADS_NUM 5 #define GP_QUERY_IN 0 #define GP_QUERY_OUT 1 #define GP_QUERY_ERR 2 struct gp_query { struct gp_query *next; struct gp_conn *conn; uint8_t *buffer; size_t buflen; int status; }; struct gp_thread { struct gp_thread *prev; struct gp_thread *next; struct gp_workers *pool; pthread_t tid; struct gp_query *query; pthread_mutex_t cond_mutex; pthread_cond_t cond_wakeup; }; struct gp_workers { pthread_mutex_t lock; struct gssproxy_ctx *gpctx; bool shutdown; struct gp_query *wait_list; struct gp_query *reply_list; struct gp_thread *free_list; struct gp_thread *busy_list; int num_threads; int sig_pipe[2]; }; static void *gp_worker_main(void *pvt); static void gp_handle_query(struct gp_workers *w, struct gp_query *q); static void gp_handle_reply(verto_ctx *vctx, verto_ev *ev); /** DISPATCHER FUNCTIONS **/ int gp_workers_init(struct gssproxy_ctx *gpctx) { struct gp_workers *w; struct gp_thread *t; pthread_attr_t attr; verto_ev *ev; int vflags; int ret; int i; w = calloc(1, sizeof(struct gp_workers)); if (!w) { return ENOMEM; } w->gpctx = gpctx; /* init global queue mutex */ ret = pthread_mutex_init(&w->lock, NULL); if (ret) { free(w); return ENOMEM; } if (gpctx->config->num_workers > 0) { w->num_threads = gpctx->config->num_workers; } else { w->num_threads = DEFAULT_WORKER_THREADS_NUM; } /* make thread joinable (portability) */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); /* init all workers */ for (i = 0; i < w->num_threads; i++) { t = calloc(1, sizeof(struct gp_thread)); if (!t) { ret = -1; goto done; } t->pool = w; ret = pthread_cond_init(&t->cond_wakeup, NULL); if (ret) { free(t); goto done; } ret = pthread_mutex_init(&t->cond_mutex, NULL); if (ret) { free(t); goto done; } ret = pthread_create(&t->tid, &attr, gp_worker_main, t); if (ret) { free(t); goto done; } LIST_ADD(w->free_list, t); } /* add wakeup pipe, so that threads can hand back replies to the * dispatcher */ ret = pipe2(w->sig_pipe, O_NONBLOCK | O_CLOEXEC); if (ret == -1) { goto done; } vflags = VERTO_EV_FLAG_PERSIST | VERTO_EV_FLAG_IO_READ; ev = verto_add_io(gpctx->vctx, vflags, gp_handle_reply, w->sig_pipe[0]); if (!ev) { ret = -1; goto done; } verto_set_private(ev, w, NULL); gpctx->workers = w; ret = 0; done: if (ret) { gp_workers_free(w); } return ret; } void gp_workers_free(struct gp_workers *w) { struct gp_thread *t; void *retval; /* ======> POOL LOCK */ pthread_mutex_lock(&w->lock); w->shutdown = true; /* <====== POOL LOCK */ pthread_mutex_unlock(&w->lock); /* we do not run the following operations within * the lock, or deadlocks may arise for threads * that are just finishing doing some work */ /* we guarantee nobody is touching these lists by * preventing workers from touching the free/busy * lists when a 'shutdown' is in progress */ while (w->free_list) { /* pick threads one by one */ t = w->free_list; LIST_DEL(w->free_list, t); /* wake up threads, then join them */ /* ======> COND_MUTEX */ pthread_mutex_lock(&t->cond_mutex); pthread_cond_signal(&t->cond_wakeup); /* <====== COND_MUTEX */ pthread_mutex_unlock(&t->cond_mutex); pthread_join(t->tid, &retval); pthread_mutex_destroy(&t->cond_mutex); pthread_cond_destroy(&t->cond_wakeup); free(t); } /* do the same with the busy list */ while (w->busy_list) { /* pick threads one by one */ t = w->busy_list; LIST_DEL(w->free_list, t); /* wake up threads, then join them */ /* ======> COND_MUTEX */ pthread_mutex_lock(&t->cond_mutex); pthread_cond_signal(&t->cond_wakeup); /* <====== COND_MUTEX */ pthread_mutex_unlock(&t->cond_mutex); pthread_join(t->tid, &retval); pthread_mutex_destroy(&t->cond_mutex); pthread_cond_destroy(&t->cond_wakeup); free(t); } close(w->sig_pipe[0]); close(w->sig_pipe[1]); pthread_mutex_destroy(&w->lock); free(w); } static void gp_query_assign(struct gp_workers *w, struct gp_query *q) { struct gp_thread *t = NULL; /* then either find a free thread or queue in the wait list */ /* ======> POOL LOCK */ pthread_mutex_lock(&w->lock); if (w->free_list) { t = w->free_list; LIST_DEL(w->free_list, t); LIST_ADD(w->busy_list, t); } /* <====== POOL LOCK */ pthread_mutex_unlock(&w->lock); if (t) { /* found free thread, assign work */ /* ======> COND_MUTEX */ pthread_mutex_lock(&t->cond_mutex); /* hand over the query */ t->query = q; pthread_cond_signal(&t->cond_wakeup); /* <====== COND_MUTEX */ pthread_mutex_unlock(&t->cond_mutex); } else { /* all threads are busy, store in wait list */ /* only the dispatcher handles wait_list * so we do not need to lock around it */ q->next = w->wait_list; w->wait_list = q; } } static void gp_query_free(struct gp_query *q, bool free_buffer) { if (!q) { return; } if (free_buffer) { free(q->buffer); } free(q); } int gp_query_new(struct gp_workers *w, struct gp_conn *conn, uint8_t *buffer, size_t buflen) { struct gp_query *q; /* create query struct */ q = calloc(1, sizeof(struct gp_query)); if (!q) { return ENOMEM; } q->conn = conn; q->buffer = buffer; q->buflen = buflen; gp_query_assign(w, q); return 0; } static void gp_handle_reply(verto_ctx *vctx, verto_ev *ev) { struct gp_workers *w; struct gp_query *q = NULL; char dummy; int ret; w = verto_get_private(ev); /* first read out the dummy so the pipe doesn't get clogged */ ret = read(w->sig_pipe[0], &dummy, 1); if (ret) { /* ignore errors */ } /* grab a query reply if any */ if (w->reply_list) { /* ======> POOL LOCK */ pthread_mutex_lock(&w->lock); if (w->reply_list != NULL) { q = w->reply_list; w->reply_list = q->next; } /* <====== POOL LOCK */ pthread_mutex_unlock(&w->lock); } if (q) { switch (q->status) { case GP_QUERY_IN: /* ?! fallback and kill client conn */ case GP_QUERY_ERR: GPDEBUGN(3, "[status] Handling query error, terminating CID %d.\n", gp_conn_get_cid(q->conn)); gp_conn_free(q->conn); gp_query_free(q, true); break; case GP_QUERY_OUT: GPDEBUGN(3, "[status] Handling query reply: %p (%zu)\n", q->buffer, q->buflen); gp_socket_send_data(vctx, q->conn, q->buffer, q->buflen); gp_query_free(q, false); break; } } /* while we are at it, check if there is anything in the wait list * we need to process, as one thread just got free :-) */ q = NULL; if (w->wait_list) { /* only the dispatcher handles wait_list * so we do not need to lock around it */ if (w->wait_list) { q = w->wait_list; w->wait_list = q->next; q->next = NULL; } } if (q) { gp_query_assign(w, q); } } /** WORKER THREADS **/ static void *gp_worker_main(void *pvt) { struct gp_thread *t = (struct gp_thread *)pvt; struct gp_query *q = NULL; char dummy = 0; int ret; while (!t->pool->shutdown) { /* initialize debug client id to 0 until work is scheduled */ gp_debug_set_conn_id(0); /* ======> COND_MUTEX */ pthread_mutex_lock(&t->cond_mutex); while (t->query == NULL) { /* wait for next query */ pthread_cond_wait(&t->cond_wakeup, &t->cond_mutex); if (t->pool->shutdown) { pthread_exit(NULL); } } /* grab the query off the shared pointer */ q = t->query; t->query = NULL; /* <====== COND_MUTEX */ pthread_mutex_unlock(&t->cond_mutex); /* set client id before hndling requests */ gp_debug_set_conn_id(gp_conn_get_cid(q->conn)); /* handle the client request */ GPDEBUGN(3, "[status] Handling query input: %p (%zu)\n", q->buffer, q->buflen); gp_handle_query(t->pool, q); GPDEBUGN(3 ,"[status] Handling query output: %p (%zu)\n", q->buffer, q->buflen); /* now get lock on main queue, to play with the reply list */ /* ======> POOL LOCK */ pthread_mutex_lock(&t->pool->lock); /* put back query so that dispatcher can send reply */ q->next = t->pool->reply_list; t->pool->reply_list = q; /* add us back to the free list but only if we are not * shutting down */ if (!t->pool->shutdown) { LIST_DEL(t->pool->busy_list, t); LIST_ADD(t->pool->free_list, t); } /* <====== POOL LOCK */ pthread_mutex_unlock(&t->pool->lock); /* and wake up dispatcher so it will handle it */ ret = write(t->pool->sig_pipe[1], &dummy, 1); if (ret == -1) { GPERROR("Failed to signal dispatcher!"); } } pthread_exit(NULL); } static void gp_handle_query(struct gp_workers *w, struct gp_query *q) { struct gp_call_ctx gpcall = { 0 }; uint8_t *buffer; size_t buflen; int ret; /* find service */ gpcall.gpctx = w->gpctx; gpcall.service = gp_creds_match_conn(w->gpctx, q->conn); if (!gpcall.service) { q->status = GP_QUERY_ERR; return; } gpcall.connection = q->conn; ret = gp_rpc_process_call(&gpcall, q->buffer, q->buflen, &buffer, &buflen); if (ret) { q->status = GP_QUERY_ERR; } else { q->status = GP_QUERY_OUT; free(q->buffer); q->buffer = buffer; q->buflen = buflen; } if (gpcall.destroy_callback) { gpcall.destroy_callback(gpcall.destroy_callback_data); } }
./CrossVul/dataset_final_sorted/CWE-667/c/bad_4008_0
crossvul-cpp_data_bad_3628_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-16/cpp/bad_3628_0
crossvul-cpp_data_good_3628_0
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include "headers.h" #include "checkpoints.h" #include "db.h" #include "net.h" #include "init.h" #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> using namespace std; using namespace boost; // // Global state // // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); CCriticalSection cs_setpwalletRegistered; set<CWallet*> setpwalletRegistered; CCriticalSection cs_main; static map<uint256, CTransaction> mapTransactions; CCriticalSection cs_mapTransactions; unsigned int nTransactionsUpdated = 0; map<COutPoint, CInPoint> mapNextTx; map<uint256, CBlockIndex*> mapBlockIndex; uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"); static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32); CBlockIndex* pindexGenesisBlock = NULL; int nBestHeight = -1; CBigNum bnBestChainWork = 0; CBigNum bnBestInvalidWork = 0; uint256 hashBestChain = 0; CBlockIndex* pindexBest = NULL; int64 nTimeBestReceived = 0; CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have map<uint256, CBlock*> mapOrphanBlocks; multimap<uint256, CBlock*> mapOrphanBlocksByPrev; map<uint256, CDataStream*> mapOrphanTransactions; multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev; // Constant stuff for coinbase transactions we create: CScript COINBASE_FLAGS; const string strMessageMagic = "Bitcoin Signed Message:\n"; double dHashesPerSec; int64 nHPSTimerStart; // Settings int64 nTransactionFee = 0; ////////////////////////////////////////////////////////////////////////////// // // dispatching functions // // These functions dispatch to one or all registered wallets void RegisterWallet(CWallet* pwalletIn) { CRITICAL_BLOCK(cs_setpwalletRegistered) { setpwalletRegistered.insert(pwalletIn); } } void UnregisterWallet(CWallet* pwalletIn) { CRITICAL_BLOCK(cs_setpwalletRegistered) { setpwalletRegistered.erase(pwalletIn); } } // check whether the passed transaction is from us bool static IsFromMe(CTransaction& tx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->IsFromMe(tx)) return true; return false; } // get the wallet transaction with the given hash (if it exists) bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->GetTransaction(hashTx,wtx)) return true; return false; } // erases transaction with the given hash from all wallets void static EraseFromWallets(uint256 hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->EraseFromWallet(hash); } // make sure all wallets know about the given transaction, in the given block void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate); } // notify wallets about a new best chain void static SetBestChain(const CBlockLocator& loc) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->SetBestChain(loc); } // notify wallets about an updated transaction void static UpdatedTransaction(const uint256& hashTx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->UpdatedTransaction(hashTx); } // dump all wallets void static PrintWallets(const CBlock& block) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->PrintWallet(block); } // notify wallets about an incoming inventory (for request counts) void static Inventory(const uint256& hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->Inventory(hash); } // ask wallets to resend their transactions void static ResendWalletTransactions() { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->ResendWalletTransactions(); } ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions // void AddOrphanTx(const CDataStream& vMsg) { CTransaction tx; CDataStream(vMsg) >> tx; uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return; CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg); BOOST_FOREACH(const CTxIn& txin, tx.vin) mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg)); } void static EraseOrphanTx(uint256 hash) { if (!mapOrphanTransactions.count(hash)) return; const CDataStream* pvMsg = mapOrphanTransactions[hash]; CTransaction tx; CDataStream(*pvMsg) >> tx; BOOST_FOREACH(const CTxIn& txin, tx.vin) { for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash); mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);) { if ((*mi).second == pvMsg) mapOrphanTransactionsByPrev.erase(mi++); else mi++; } } delete pvMsg; mapOrphanTransactions.erase(hash); } int LimitOrphanTxSize(int nMaxOrphans) { int nEvicted = 0; while (mapOrphanTransactions.size() > nMaxOrphans) { // Evict a random orphan: std::vector<unsigned char> randbytes(32); RAND_bytes(&randbytes[0], 32); uint256 randomhash(randbytes); map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } ////////////////////////////////////////////////////////////////////////////// // // CTransaction and CTxIndex // bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet) { SetNull(); if (!txdb.ReadTxIndex(prevout.hash, txindexRet)) return false; if (!ReadFromDisk(txindexRet.pos)) return false; if (prevout.n >= vout.size()) { SetNull(); return false; } return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout) { CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::ReadFromDisk(COutPoint prevout) { CTxDB txdb("r"); CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::IsStandard() const { BOOST_FOREACH(const CTxIn& txin, vin) { // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG // pay-to-script-hash, which is 3 ~80-byte signatures, 3 // ~65-byte public keys, plus a few script ops. if (txin.scriptSig.size() > 500) return false; if (!txin.scriptSig.IsPushOnly()) return false; } BOOST_FOREACH(const CTxOut& txout, vout) if (!::IsStandard(txout.scriptPubKey)) return false; return true; } // // Check transaction inputs, and make sure any // pay-to-script-hash transactions are evaluating IsStandard scripts // // Why bother? To avoid denial-of-service attacks; an attacker // can submit a standard HASH... OP_EQUAL transaction, // which will get accepted into blocks. The redemption // script can be anything; an attacker could use a very // expensive-to-check-upon-redemption script like: // DUP CHECKSIG DROP ... repeated 100 times... OP_1 // bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const { if (IsCoinBase()) return true; // Coinbases don't use vin normally for (int i = 0; i < vin.size(); i++) { const CTxOut& prev = GetOutputFor(vin[i], mapInputs); vector<vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations // beside "push data" in the scriptSig the // IsStandard() call returns false vector<vector<unsigned char> > stack; if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0)) return false; if (whichType == TX_SCRIPTHASH) { if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); vector<vector<unsigned char> > vSolutions2; txnouttype whichType2; if (!Solver(subscript, whichType2, vSolutions2)) return false; if (whichType2 == TX_SCRIPTHASH) return false; nArgsExpected += ScriptSigArgsExpected(whichType2, vSolutions2); } if (stack.size() != nArgsExpected) return false; } return true; } int CTransaction::GetLegacySigOpCount() const { int nSigOps = 0; BOOST_FOREACH(const CTxIn& txin, vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } BOOST_FOREACH(const CTxOut& txout, vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } int CMerkleTx::SetMerkleBranch(const CBlock* pblock) { if (fClient) { if (hashBlock == 0) return 0; } else { CBlock blockTmp; if (pblock == NULL) { // Load the block this tx is in CTxIndex txindex; if (!CTxDB("r").ReadTxIndex(GetHash(), txindex)) return 0; if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos)) return 0; pblock = &blockTmp; } // Update the tx's hashBlock hashBlock = pblock->GetHash(); // Locate the transaction for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++) if (pblock->vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == pblock->vtx.size()) { vMerkleBranch.clear(); nIndex = -1; printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = pblock->GetMerkleBranch(nIndex); } // Is the tx in a block that's in the main chain map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return pindexBest->nHeight - pindex->nHeight + 1; } bool CTransaction::CheckTransaction() const { // Basic checks that don't depend on any context if (vin.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vin empty")); if (vout.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vout empty")); // Size limits if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE) return DoS(100, error("CTransaction::CheckTransaction() : size limits failed")); // Check for negative or overflow output values int64 nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { if (txout.nValue < 0) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative")); if (txout.nValue > MAX_MONEY) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high")); nValueOut += txout.nValue; if (!MoneyRange(nValueOut)) return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range")); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, vin) { if (vInOutPoints.count(txin.prevout)) return false; vInOutPoints.insert(txin.prevout); } if (IsCoinBase()) { if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100) return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size")); } else { BOOST_FOREACH(const CTxIn& txin, vin) if (txin.prevout.IsNull()) return DoS(10, error("CTransaction::CheckTransaction() : prevout is null")); } return true; } bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs) { if (pfMissingInputs) *pfMissingInputs = false; if (!CheckTransaction()) return error("AcceptToMemoryPool() : CheckTransaction failed"); // Coinbase is only valid in a block, not as a loose transaction if (IsCoinBase()) return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx")); // To help v0.1.5 clients who would see it as a negative number if ((int64)nLockTime > std::numeric_limits<int>::max()) return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet"); // Rather not work on nonstandard transactions (unless -testnet) if (!fTestNet && !IsStandard()) return error("AcceptToMemoryPool() : nonstandard transaction type"); // Do we already have it? uint256 hash = GetHash(); CRITICAL_BLOCK(cs_mapTransactions) if (mapTransactions.count(hash)) return false; if (fCheckInputs) if (txdb.ContainsTx(hash)) return false; // Check for conflicts with in-memory transactions CTransaction* ptxOld = NULL; for (int i = 0; i < vin.size(); i++) { COutPoint outpoint = vin[i].prevout; if (mapNextTx.count(outpoint)) { // Disable replacement feature for now return false; // Allow replacing with a newer version of the same transaction if (i != 0) return false; ptxOld = mapNextTx[outpoint].ptx; if (ptxOld->IsFinal()) return false; if (!IsNewerThan(*ptxOld)) return false; for (int i = 0; i < vin.size(); i++) { COutPoint outpoint = vin[i].prevout; if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld) return false; } break; } } if (fCheckInputs) { MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (!FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { if (fInvalid) return error("AcceptToMemoryPool() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str()); if (pfMissingInputs) *pfMissingInputs = true; return error("AcceptToMemoryPool() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str()); } // Check for non-standard pay-to-script-hash in inputs if (!AreInputsStandard(mapInputs) && !fTestNet) return error("AcceptToMemoryPool() : nonstandard transaction input"); // Note: if you modify this code to accept non-standard transactions, then // you should add code here to check that the transaction does a // reasonable number of ECDSA signature verifications. int64 nFees = GetValueIn(mapInputs)-GetValueOut(); unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK); // Don't accept it if it can't get into a block if (nFees < GetMinFee(1000, true, GMF_RELAY)) return error("AcceptToMemoryPool() : not enough fees"); // Continuously rate-limit free transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make other's transactions take longer to confirm. if (nFees < MIN_RELAY_TX_FEE) { static CCriticalSection cs; static double dFreeCount; static int64 nLastTime; int64 nNow = GetTime(); CRITICAL_BLOCK(cs) { // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is thousand-bytes-per-minute // At default rate it would take over a month to fill 1GB if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this)) return error("AcceptToMemoryPool() : free transaction rejected by rate limiter"); if (fDebug) printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); dFreeCount += nSize; } } // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. if (!ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false)) { return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str()); } } // Store transaction in memory CRITICAL_BLOCK(cs_mapTransactions) { if (ptxOld) { printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str()); ptxOld->RemoveFromMemoryPool(); } AddToMemoryPoolUnchecked(); } ///// are we sure this is ok when loading transactions or restoring block txes // If updated, erase old tx from wallet if (ptxOld) EraseFromWallets(ptxOld->GetHash()); printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str()); return true; } bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs) { CTxDB txdb("r"); return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs); } uint64 nPooledTx = 0; bool CTransaction::AddToMemoryPoolUnchecked() { printf("AcceptToMemoryPoolUnchecked(): size %lu\n", mapTransactions.size()); // Add to memory pool without checking anything. Don't call this directly, // call AcceptToMemoryPool to properly check the transaction first. CRITICAL_BLOCK(cs_mapTransactions) { uint256 hash = GetHash(); mapTransactions[hash] = *this; for (int i = 0; i < vin.size(); i++) mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i); nTransactionsUpdated++; ++nPooledTx; } return true; } bool CTransaction::RemoveFromMemoryPool() { // Remove transaction from memory pool CRITICAL_BLOCK(cs_mapTransactions) { uint256 hash = GetHash(); if (mapTransactions.count(hash)) { BOOST_FOREACH(const CTxIn& txin, vin) mapNextTx.erase(txin.prevout); mapTransactions.erase(hash); nTransactionsUpdated++; --nPooledTx; } } return true; } int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; // Find the block it claims to be in map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return pindexBest->nHeight - pindex->nHeight + 1; } int CMerkleTx::GetBlocksToMaturity() const { if (!IsCoinBase()) return 0; return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs) { if (fClient) { if (!IsInMainChain() && !ClientConnectInputs()) return false; return CTransaction::AcceptToMemoryPool(txdb, false); } else { return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs); } } bool CMerkleTx::AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); } bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs) { CRITICAL_BLOCK(cs_mapTransactions) { // Add previous supporting transactions first BOOST_FOREACH(CMerkleTx& tx, vtxPrev) { if (!tx.IsCoinBase()) { uint256 hash = tx.GetHash(); if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash)) tx.AcceptToMemoryPool(txdb, fCheckInputs); } } return AcceptToMemoryPool(txdb, fCheckInputs); } return false; } bool CWalletTx::AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); } int CTxIndex::GetDepthInMainChain() const { // Read block header CBlock block; if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false)) return 0; // Find the block in the index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash()); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return 1 + nBestHeight - pindex->nHeight; } ////////////////////////////////////////////////////////////////////////////// // // CBlock and CBlockIndex // bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions) { if (!fReadTransactions) { *this = pindex->GetBlockHeader(); return true; } if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions)) return false; if (GetHash() != pindex->GetBlockHash()) return error("CBlock::ReadFromDisk() : GetHash() doesn't match index"); return true; } uint256 static GetOrphanRoot(const CBlock* pblock) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblock->hashPrevBlock)) pblock = mapOrphanBlocks[pblock->hashPrevBlock]; return pblock->GetHash(); } int64 static GetBlockValue(int nHeight, int64 nFees) { int64 nSubsidy = 50 * COIN; // Subsidy is cut in half every 4 years nSubsidy >>= (nHeight / 210000); return nSubsidy + nFees; } static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks static const int64 nTargetSpacing = 10 * 60; static const int64 nInterval = nTargetTimespan / nTargetSpacing; // // minimum amount of work that could possibly be required nTime after // minimum work required was nBase // unsigned int ComputeMinWork(unsigned int nBase, int64 nTime) { // Testnet has min-difficulty blocks // after nTargetSpacing*2 time between blocks: if (fTestNet && nTime > nTargetSpacing*2) return bnProofOfWorkLimit.GetCompact(); CBigNum bnResult; bnResult.SetCompact(nBase); while (nTime > 0 && bnResult < bnProofOfWorkLimit) { // Maximum 400% adjustment... bnResult *= 4; // ... in best-case exactly 4-times-normal target time nTime -= nTargetTimespan*4; } if (bnResult > bnProofOfWorkLimit) bnResult = bnProofOfWorkLimit; return bnResult.GetCompact(); } unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock) { unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact(); // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; // Only change once per interval if ((pindexLast->nHeight+1) % nInterval != 0) { // Special rules for testnet after 15 Feb 2012: if (fTestNet && pblock->nTime > 1329264000) { // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->nTime - pindexLast->nTime > nTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // Go back by what we want to be 14 days worth of blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < nInterval-1; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); // Limit adjustment step int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime(); printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan); if (nActualTimespan < nTargetTimespan/4) nActualTimespan = nTargetTimespan/4; if (nActualTimespan > nTargetTimespan*4) nActualTimespan = nTargetTimespan*4; // Retarget CBigNum bnNew; bnNew.SetCompact(pindexLast->nBits); bnNew *= nActualTimespan; bnNew /= nTargetTimespan; if (bnNew > bnProofOfWorkLimit) bnNew = bnProofOfWorkLimit; /// debug print printf("GetNextWorkRequired RETARGET\n"); printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan); printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str()); printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str()); return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits) { CBigNum bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget.getuint256()) return error("CheckProofOfWork() : hash doesn't match nBits"); return true; } // Return maximum amount of blocks that other nodes claim to have int GetNumBlocksOfPeers() { return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate()); } bool IsInitialBlockDownload() { if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate()) return true; static int64 nLastUpdate; static CBlockIndex* pindexLastBest; if (pindexBest != pindexLastBest) { pindexLastBest = pindexBest; nLastUpdate = GetTime(); } return (GetTime() - nLastUpdate < 10 && pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60); } void static InvalidChainFound(CBlockIndex* pindexNew) { if (pindexNew->bnChainWork > bnBestInvalidWork) { bnBestInvalidWork = pindexNew->bnChainWork; CTxDB().WriteBestInvalidWork(bnBestInvalidWork); MainFrameRepaint(); } printf("InvalidChainFound: invalid block=%s height=%d work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str()); printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str()); if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6) printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n"); } void CBlock::UpdateTime(const CBlockIndex* pindexPrev) { nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); // Updating time can change work required on testnet: if (fTestNet) nBits = GetNextWorkRequired(pindexPrev, this); } bool CTransaction::DisconnectInputs(CTxDB& txdb) { // Relinquish previous transactions' spent pointers if (!IsCoinBase()) { BOOST_FOREACH(const CTxIn& txin, vin) { COutPoint prevout = txin.prevout; // Get prev txindex from disk CTxIndex txindex; if (!txdb.ReadTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : ReadTxIndex failed"); if (prevout.n >= txindex.vSpent.size()) return error("DisconnectInputs() : prevout.n out of range"); // Mark outpoint as not spent txindex.vSpent[prevout.n].SetNull(); // Write back if (!txdb.UpdateTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : UpdateTxIndex failed"); } } // Remove transaction from index // This can fail if a duplicate of this transaction was in a chain that got // reorganized away. This is only possible if this transaction was completely // spent, so erasing it would be a no-op anway. txdb.EraseTxIndex(*this); return true; } bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid) { // FetchInputs can return false either because we just haven't seen some inputs // (in which case the transaction should be stored as an orphan) // or because the transaction is malformed (in which case the transaction should // be dropped). If tx is definitely invalid, fInvalid will be set to true. fInvalid = false; if (IsCoinBase()) return true; // Coinbase transactions have no inputs to fetch. for (int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; if (inputsRet.count(prevout.hash)) continue; // Got it already // Read txindex CTxIndex& txindex = inputsRet[prevout.hash].first; bool fFound = true; if ((fBlock || fMiner) && mapTestPool.count(prevout.hash)) { // Get txindex from current proposed changes txindex = mapTestPool.find(prevout.hash)->second; } else { // Read txindex from txdb fFound = txdb.ReadTxIndex(prevout.hash, txindex); } if (!fFound && (fBlock || fMiner)) return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); // Read txPrev CTransaction& txPrev = inputsRet[prevout.hash].second; if (!fFound || txindex.pos == CDiskTxPos(1,1,1)) { // Get prev tx from single transactions in memory CRITICAL_BLOCK(cs_mapTransactions) { if (!mapTransactions.count(prevout.hash)) return error("FetchInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); txPrev = mapTransactions[prevout.hash]; } if (!fFound) txindex.vSpent.resize(txPrev.vout.size()); } else { // Get prev tx from disk if (!txPrev.ReadFromDisk(txindex.pos)) return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); } } // Make sure all prevout.n's are valid: for (int i = 0; i < vin.size(); i++) { const COutPoint prevout = vin[i].prevout; assert(inputsRet.count(prevout.hash) != 0); const CTxIndex& txindex = inputsRet[prevout.hash].first; const CTransaction& txPrev = inputsRet[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) { // Revisit this if/when transaction replacement is implemented and allows // adding inputs: fInvalid = true; return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); } } return true; } const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const { MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash); if (mi == inputs.end()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found"); const CTransaction& txPrev = (mi->second).second; if (input.prevout.n >= txPrev.vout.size()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range"); return txPrev.vout[input.prevout.n]; } int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; int64 nResult = 0; for (int i = 0; i < vin.size(); i++) { nResult += GetOutputFor(vin[i], inputs).nValue; } return nResult; } int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; int nSigOps = 0; for (int i = 0; i < vin.size(); i++) { const CTxOut& prevout = GetOutputFor(vin[i], inputs); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig); } return nSigOps; } bool CTransaction::ConnectInputs(MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash) { // Take over previous transactions' spent pointers // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain // fMiner is true when called from the internal bitcoin miner // ... both are false when called from CTransaction::AcceptToMemoryPool if (!IsCoinBase()) { int64 nValueIn = 0; int64 nFees = 0; for (int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); // If prev is coinbase, check that it's matured if (txPrev.IsCoinBase()) for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev) if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile) return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight); // Check for conflicts (double-spend) // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!txindex.vSpent[prevout.n].IsNull()) return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str()); // Check for negative or overflow input values nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return DoS(100, error("ConnectInputs() : txin values out of range")); // Skip ECDSA signature verification when connecting blocks (fBlock=true) // before the last blockchain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate()))) { // Verify signature if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0)) { // only during transition phase for P2SH: do not invoke anti-DoS code for // potentially old clients relaying bad P2SH transactions if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0)) return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str()); return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str())); } } // Mark outpoints as spent txindex.vSpent[prevout.n] = posThisTx; // Write back if (fBlock || fMiner) { mapTestPool[prevout.hash] = txindex; } } if (nValueIn < GetValueOut()) return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str())); // Tally transaction fees int64 nTxFee = nValueIn - GetValueOut(); if (nTxFee < 0) return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str())); nFees += nTxFee; if (!MoneyRange(nFees)) return DoS(100, error("ConnectInputs() : nFees out of range")); } return true; } bool CTransaction::ClientConnectInputs() { if (IsCoinBase()) return false; // Take over previous transactions' spent pointers CRITICAL_BLOCK(cs_mapTransactions) { int64 nValueIn = 0; for (int i = 0; i < vin.size(); i++) { // Get prev tx from single transactions in memory COutPoint prevout = vin[i].prevout; if (!mapTransactions.count(prevout.hash)) return false; CTransaction& txPrev = mapTransactions[prevout.hash]; if (prevout.n >= txPrev.vout.size()) return false; // Verify signature if (!VerifySignature(txPrev, *this, i, true, 0)) return error("ConnectInputs() : VerifySignature failed"); ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of ///// this has to go away now that posNext is gone // // Check for conflicts // if (!txPrev.vout[prevout.n].posNext.IsNull()) // return error("ConnectInputs() : prev tx already used"); // // // Flag outpoints as used // txPrev.vout[prevout.n].posNext = posThisTx; nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return error("ClientConnectInputs() : txin values out of range"); } if (GetValueOut() > nValueIn) return false; } return true; } bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Disconnect in reverse order for (int i = vtx.size()-1; i >= 0; i--) if (!vtx[i].DisconnectInputs(txdb)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = 0; if (!txdb.WriteBlockIndex(blockindexPrev)) return error("DisconnectBlock() : WriteBlockIndex failed"); } return true; } bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Check it again in case a previous version let a bad block in if (!CheckBlock()) return false; // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. // If such overwrites are allowed, coinbases and transactions depending upon those // can be duplicated to remove the ability to spend the first instance -- even after // being sent to another address. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool // already refuses previously-known transaction id's entirely. // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC. // On testnet it is enabled as of februari 20, 2012, 0:00 UTC. if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000)) BOOST_FOREACH(CTransaction& tx, vtx) { CTxIndex txindexOld; if (txdb.ReadTxIndex(tx.GetHash(), txindexOld)) BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent) if (pos.IsNull()) return false; } // To avoid being on the short end of a block-chain split, // don't do secondary validation of pay-to-script-hash transactions // until blocks with timestamps after paytoscripthashtime (see init.cpp for default). // This code can be removed once a super-majority of the network has upgraded. int64 nEvalSwitchTime = GetArg("-paytoscripthashtime", std::numeric_limits<int64_t>::max()); bool fStrictPayToScriptHash = (pindex->nTime >= nEvalSwitchTime); //// issue here: it doesn't know the version unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size()); map<uint256, CTxIndex> mapQueuedChanges; int64 nFees = 0; int nSigOps = 0; BOOST_FOREACH(CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos); nTxPos += ::GetSerializeSize(tx, SER_DISK); MapPrevTx mapInputs; if (!tx.IsCoinBase()) { bool fInvalid; if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid)) return false; if (fStrictPayToScriptHash) { // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. nSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); } nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash)) return false; } mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size()); } // Write queued txindex changes for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi) { if (!txdb.UpdateTxIndex((*mi).first, (*mi).second)) return error("ConnectBlock() : UpdateTxIndex failed"); } if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = pindex->GetBlockHash(); if (!txdb.WriteBlockIndex(blockindexPrev)) return error("ConnectBlock() : WriteBlockIndex failed"); } // Watch for transactions paying to me BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, true); return true; } bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew) { printf("REORGANIZE\n"); // Find the fork CBlockIndex* pfork = pindexBest; CBlockIndex* plonger = pindexNew; while (pfork != plonger) { while (plonger->nHeight > pfork->nHeight) if (!(plonger = plonger->pprev)) return error("Reorganize() : plonger->pprev is null"); if (pfork == plonger) break; if (!(pfork = pfork->pprev)) return error("Reorganize() : pfork->pprev is null"); } // List of what to disconnect vector<CBlockIndex*> vDisconnect; for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev) vDisconnect.push_back(pindex); // List of what to connect vector<CBlockIndex*> vConnect; for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev) vConnect.push_back(pindex); reverse(vConnect.begin(), vConnect.end()); // Disconnect shorter branch vector<CTransaction> vResurrect; BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) { CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for disconnect failed"); if (!block.DisconnectBlock(txdb, pindex)) return error("Reorganize() : DisconnectBlock failed"); // Queue memory transactions to resurrect BOOST_FOREACH(const CTransaction& tx, block.vtx) if (!tx.IsCoinBase()) vResurrect.push_back(tx); } // Connect longer branch vector<CTransaction> vDelete; for (int i = 0; i < vConnect.size(); i++) { CBlockIndex* pindex = vConnect[i]; CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for connect failed"); if (!block.ConnectBlock(txdb, pindex)) { // Invalid block txdb.TxnAbort(); return error("Reorganize() : ConnectBlock failed"); } // Queue memory transactions to delete BOOST_FOREACH(const CTransaction& tx, block.vtx) vDelete.push_back(tx); } if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash())) return error("Reorganize() : WriteHashBestChain failed"); // Make sure it's successfully written to disk before changing memory structure if (!txdb.TxnCommit()) return error("Reorganize() : TxnCommit failed"); // Disconnect shorter branch BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) if (pindex->pprev) pindex->pprev->pnext = NULL; // Connect longer branch BOOST_FOREACH(CBlockIndex* pindex, vConnect) if (pindex->pprev) pindex->pprev->pnext = pindex; // Resurrect memory transactions that were in the disconnected branch BOOST_FOREACH(CTransaction& tx, vResurrect) tx.AcceptToMemoryPool(txdb, false); // Delete redundant memory transactions that are in the connected branch BOOST_FOREACH(CTransaction& tx, vDelete) tx.RemoveFromMemoryPool(); printf("REORGANIZE: Disconnected %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str()); printf("REORGANIZE: Connected %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str()); return true; } static void runCommand(std::string strCommand) { int nErr = ::system(strCommand.c_str()); if (nErr) printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr); } bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew) { uint256 hash = GetHash(); txdb.TxnBegin(); if (pindexGenesisBlock == NULL && hash == hashGenesisBlock) { txdb.WriteHashBestChain(hash); if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); pindexGenesisBlock = pindexNew; } else if (hashPrevBlock == hashBestChain) { // Adding to current best branch if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return error("SetBestChain() : ConnectBlock failed"); } if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); // Add to current best branch pindexNew->pprev->pnext = pindexNew; // Delete redundant memory transactions BOOST_FOREACH(CTransaction& tx, vtx) tx.RemoveFromMemoryPool(); } else { // New best branch if (!Reorganize(txdb, pindexNew)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return error("SetBestChain() : Reorganize failed"); } } // Update best block in wallet (so we can detect restored wallets) bool fIsInitialDownload = IsInitialBlockDownload(); if (!fIsInitialDownload) { const CBlockLocator locator(pindexNew); ::SetBestChain(locator); } // New best block hashBestChain = hash; pindexBest = pindexNew; nBestHeight = pindexBest->nHeight; bnBestChainWork = pindexNew->bnChainWork; nTimeBestReceived = GetTime(); nTransactionsUpdated++; printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str()); std::string strCmd = GetArg("-blocknotify", ""); if (!fIsInitialDownload && !strCmd.empty()) { boost::replace_all(strCmd, "%s", hashBestChain.GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } return true; } bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos) { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str()); // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this); if (!pindexNew) return error("AddToBlockIndex() : new CBlockIndex failed"); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock); if (miPrev != mapBlockIndex.end()) { pindexNew->pprev = (*miPrev).second; pindexNew->nHeight = pindexNew->pprev->nHeight + 1; } pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork(); CTxDB txdb; txdb.TxnBegin(); txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew)); if (!txdb.TxnCommit()) return false; // New best if (pindexNew->bnChainWork > bnBestChainWork) if (!SetBestChain(txdb, pindexNew)) return false; txdb.Close(); if (pindexNew == pindexBest) { // Notify UI to display prev block's coinbase if it was ours static uint256 hashPrevBestCoinBase; UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = vtx[0].GetHash(); } MainFrameRepaint(); return true; } bool CBlock::CheckBlock() const { // These are checks that are independent of context // that can be verified before saving an orphan block. // Size limits if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE) return DoS(100, error("CheckBlock() : size limits failed")); // Check proof of work matches claimed amount if (!CheckProofOfWork(GetHash(), nBits)) return DoS(50, error("CheckBlock() : proof of work failed")); // Check timestamp if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60) return error("CheckBlock() : block timestamp too far in the future"); // First transaction must be coinbase, the rest must not be if (vtx.empty() || !vtx[0].IsCoinBase()) return DoS(100, error("CheckBlock() : first tx is not coinbase")); for (int i = 1; i < vtx.size(); i++) if (vtx[i].IsCoinBase()) return DoS(100, error("CheckBlock() : more than one coinbase")); // Check transactions BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.CheckTransaction()) return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed")); int nSigOps = 0; BOOST_FOREACH(const CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); } if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount")); // Check merkleroot if (hashMerkleRoot != BuildMerkleTree()) return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch")); return true; } bool CBlock::AcceptBlock() { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AcceptBlock() : block already in mapBlockIndex"); // Get prev block index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock); if (mi == mapBlockIndex.end()) return DoS(10, error("AcceptBlock() : prev block not found")); CBlockIndex* pindexPrev = (*mi).second; int nHeight = pindexPrev->nHeight+1; // Check proof of work if (nBits != GetNextWorkRequired(pindexPrev, this)) return DoS(100, error("AcceptBlock() : incorrect proof of work")); // Check timestamp against prev if (GetBlockTime() <= pindexPrev->GetMedianTimePast()) return error("AcceptBlock() : block's timestamp is too early"); // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.IsFinal(nHeight, GetBlockTime())) return DoS(10, error("AcceptBlock() : contains a non-final transaction")); // Check that the block chain matches the known block chain up to a checkpoint if (!Checkpoints::CheckBlock(nHeight, hash)) return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight)); // Write block to history file if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK))) return error("AcceptBlock() : out of disk space"); unsigned int nFile = -1; unsigned int nBlockPos = 0; if (!WriteToDisk(nFile, nBlockPos)) return error("AcceptBlock() : WriteToDisk failed"); if (!AddToBlockIndex(nFile, nBlockPos)) return error("AcceptBlock() : AddToBlockIndex failed"); // Relay inventory, but don't relay old inventory during initial block download if (hashBestChain == hash) CRITICAL_BLOCK(cs_vNodes) BOOST_FOREACH(CNode* pnode, vNodes) if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700)) pnode->PushInventory(CInv(MSG_BLOCK, hash)); return true; } bool ProcessBlock(CNode* pfrom, CBlock* pblock) { // Check for duplicate uint256 hash = pblock->GetHash(); if (mapBlockIndex.count(hash)) return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str()); if (mapOrphanBlocks.count(hash)) return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str()); // Preliminary checks if (!pblock->CheckBlock()) return error("ProcessBlock() : CheckBlock FAILED"); CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex); if (pcheckpoint && pblock->hashPrevBlock != hashBestChain) { // Extra checks to prevent "fill up memory by spamming with bogus blocks" int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime; if (deltaTime < 0) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with timestamp before last checkpoint"); } CBigNum bnNewBlock; bnNewBlock.SetCompact(pblock->nBits); CBigNum bnRequired; bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime)); if (bnNewBlock > bnRequired) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with too little proof-of-work"); } } // If don't already have its previous block, shunt it off to holding area until we get it if (!mapBlockIndex.count(pblock->hashPrevBlock)) { printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str()); CBlock* pblock2 = new CBlock(*pblock); mapOrphanBlocks.insert(make_pair(hash, pblock2)); mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2)); // Ask this guy to fill in what we're missing if (pfrom) pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2)); return true; } // Store to disk if (!pblock->AcceptBlock()) return error("ProcessBlock() : AcceptBlock FAILED"); // Recursively process any orphan blocks that depended on this one vector<uint256> vWorkQueue; vWorkQueue.push_back(hash); for (int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev); mi != mapOrphanBlocksByPrev.upper_bound(hashPrev); ++mi) { CBlock* pblockOrphan = (*mi).second; if (pblockOrphan->AcceptBlock()) vWorkQueue.push_back(pblockOrphan->GetHash()); mapOrphanBlocks.erase(pblockOrphan->GetHash()); delete pblockOrphan; } mapOrphanBlocksByPrev.erase(hashPrev); } printf("ProcessBlock: ACCEPTED\n"); return true; } bool CheckDiskSpace(uint64 nAdditionalBytes) { uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available; // Check for 15MB because database could create another 10MB log file at any time if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes) { fShutdown = true; string strMessage = _("Warning: Disk space is low "); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION); CreateThread(Shutdown, NULL); return false; } return true; } FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode) { if (nFile == -1) return NULL; FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode); if (!file) return NULL; if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w')) { if (fseek(file, nBlockPos, SEEK_SET) != 0) { fclose(file); return NULL; } } return file; } static unsigned int nCurrentBlockFile = 1; FILE* AppendBlockFile(unsigned int& nFileRet) { nFileRet = 0; loop { FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab"); if (!file) return NULL; if (fseek(file, 0, SEEK_END) != 0) return NULL; // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB if (ftell(file) < 0x7F000000 - MAX_SIZE) { nFileRet = nCurrentBlockFile; return file; } fclose(file); nCurrentBlockFile++; } } bool LoadBlockIndex(bool fAllowNew) { if (fTestNet) { hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008"); bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28); pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xb5; pchMessageStart[3] = 0xda; } // // Load block index // CTxDB txdb("cr"); if (!txdb.LoadBlockIndex()) return false; txdb.Close(); // // Init with genesis block // if (mapBlockIndex.empty()) { if (!fAllowNew) return false; // Genesis Block: // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1) // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) // vMerkleTree: 4a5e1e // Genesis block const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 50 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; CBlock block; block.vtx.push_back(txNew); block.hashPrevBlock = 0; block.hashMerkleRoot = block.BuildMerkleTree(); block.nVersion = 1; block.nTime = 1231006505; block.nBits = 0x1d00ffff; block.nNonce = 2083236893; if (fTestNet) { block.nTime = 1296688602; block.nBits = 0x1d07fff8; block.nNonce = 384568319; } //// debug print printf("%s\n", block.GetHash().ToString().c_str()); printf("%s\n", hashGenesisBlock.ToString().c_str()); printf("%s\n", block.hashMerkleRoot.ToString().c_str()); assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b")); block.print(); assert(block.GetHash() == hashGenesisBlock); // Start new block file unsigned int nFile; unsigned int nBlockPos; if (!block.WriteToDisk(nFile, nBlockPos)) return error("LoadBlockIndex() : writing genesis block to disk failed"); if (!block.AddToBlockIndex(nFile, nBlockPos)) return error("LoadBlockIndex() : genesis block not accepted"); } return true; } void PrintBlockTree() { // precompute tree structure map<CBlockIndex*, vector<CBlockIndex*> > mapNext; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { CBlockIndex* pindex = (*mi).second; mapNext[pindex->pprev].push_back(pindex); // test //while (rand() % 3 == 0) // mapNext[pindex->pprev].push_back(pindex); } vector<pair<int, CBlockIndex*> > vStack; vStack.push_back(make_pair(0, pindexGenesisBlock)); int nPrevCol = 0; while (!vStack.empty()) { int nCol = vStack.back().first; CBlockIndex* pindex = vStack.back().second; vStack.pop_back(); // print split or gap if (nCol > nPrevCol) { for (int i = 0; i < nCol-1; i++) printf("| "); printf("|\\\n"); } else if (nCol < nPrevCol) { for (int i = 0; i < nCol; i++) printf("| "); printf("|\n"); } nPrevCol = nCol; // print columns for (int i = 0; i < nCol; i++) printf("| "); // print item CBlock block; block.ReadFromDisk(pindex); printf("%d (%u,%u) %s %s tx %d", pindex->nHeight, pindex->nFile, pindex->nBlockPos, block.GetHash().ToString().substr(0,20).c_str(), DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(), block.vtx.size()); PrintWallets(block); // put the main timechain first vector<CBlockIndex*>& vNext = mapNext[pindex]; for (int i = 0; i < vNext.size(); i++) { if (vNext[i]->pnext) { swap(vNext[0], vNext[i]); break; } } // iterate children for (int i = 0; i < vNext.size(); i++) vStack.push_back(make_pair(nCol+i, vNext[i])); } } ////////////////////////////////////////////////////////////////////////////// // // CAlert // map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; string GetWarnings(string strFor) { int nPriority = 0; string strStatusBar; string strRPC; if (GetBoolArg("-testsafemode")) strRPC = "test"; // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } // Longer invalid proof-of-work chain if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6) { nPriority = 2000; strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade."; } // Alerts CRITICAL_BLOCK(cs_mapAlerts) { BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } bool CAlert::ProcessAlert() { if (!CheckSignature()) return false; if (!IsInEffect()) return false; CRITICAL_BLOCK(cs_mapAlerts) { // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); MainFrameRepaint(); return true; } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool static AlreadyHave(CTxDB& txdb, const CInv& inv) { switch (inv.type) { case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash); case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash); } // Don't know what it is, just say we already got one return true; } // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ascii, not valid as UTF-8, and produce // a large 4-byte int at any alignment. unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 }; bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) { static map<CService, vector<unsigned char> > mapReuseKey; RandAddSeedPerfmon(); if (fDebug) { printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str()); printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size()); } if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) { printf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (strCommand == "version") { // Each connection can only send one version message if (pfrom->nVersion != 0) { pfrom->Misbehaving(1); return false; } int64 nTime; CAddress addrMe; CAddress addrFrom; uint64 nNonce = 1; vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; if (pfrom->nVersion < 209) { // Since February 20, 2012, the protocol is initiated at version 209, // and earlier versions are no longer supported printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion); pfrom->fDisconnect = true; return false; } if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) vRecv >> pfrom->strSubVer; if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str()); pfrom->fDisconnect = true; return true; } // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); AddTimeData(pfrom->addr, nTime); // Change version pfrom->PushMessage("verack"); pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() && !IsInitialBlockDownload()) { CAddress addr(addrLocalHost); addr.nTime = GetAdjustedTime(); pfrom->PushAddress(addr); } // Get recent addresses if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000) { pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; } } // Ask the first connected node for block updates static int nAskedForBlocks = 0; if (!pfrom->fClient && (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) && (nAskedForBlocks < 1 || vNodes.size() <= 1)) { nAskedForBlocks++; pfrom->PushGetBlocks(pindexBest, uint256(0)); } // Relay alerts CRITICAL_BLOCK(cs_mapAlerts) BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) item.second.RelayTo(pfrom); pfrom->fSuccessfullyConnected = true; printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight); cPeerBlockCounts.input(pfrom->nStartingHeight); } else if (pfrom->nVersion == 0) { // Must have a version message before anything else pfrom->Misbehaving(1); return false; } else if (strCommand == "verack") { pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); } else if (strCommand == "addr") { vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000) return true; if (vAddr.size() > 1000) { pfrom->Misbehaving(20); return error("message addr size() = %d", vAddr.size()); } // Store the new addresses CAddrDB addrDB; addrDB.TxnBegin(); int64 nNow = GetAdjustedTime(); int64 nSince = nNow - 10 * 60; BOOST_FOREACH(CAddress& addr, vAddr) { if (fShutdown) return true; // ignore IPv6 for now, since it isn't implemented anyway if (!addr.IsIPv4()) continue; if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; AddAddress(addr, 2 * 60 * 60, &addrDB); pfrom->AddAddressKnown(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes CRITICAL_BLOCK(cs_vNodes) { // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the setAddrKnowns of the chosen nodes prevent repeats static uint256 hashSalt; if (hashSalt == 0) RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt)); int64 hashAddr = addr.GetHash(); uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); multimap<uint256, CNode*> mapMix; BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->nVersion < 31402) continue; unsigned int nPointer; memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = hashRand ^ nPointer; hashKey = Hash(BEGIN(hashKey), END(hashKey)); mapMix.insert(make_pair(hashKey, pnode)); } int nRelayNodes = 2; for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr); } } } addrDB.TxnCommit(); // Save addresses (it's ok if this fails) if (vAddr.size() < 1000) pfrom->fGetAddr = false; } else if (strCommand == "inv") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message inv size() = %d", vInv.size()); } CTxDB txdb("r"); BOOST_FOREACH(const CInv& inv, vInv) { if (fShutdown) return true; pfrom->AddInventoryKnown(inv); bool fAlreadyHave = AlreadyHave(txdb, inv); if (fDebug) printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new"); if (!fAlreadyHave) pfrom->AskFor(inv); else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash])); // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getdata") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message getdata size() = %d", vInv.size()); } BOOST_FOREACH(const CInv& inv, vInv) { if (fShutdown) return true; printf("received getdata for: %s\n", inv.ToString().c_str()); if (inv.type == MSG_BLOCK) { // Send block from disk map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { CBlock block; block.ReadFromDisk((*mi).second); pfrom->PushMessage("block", block); // Trigger them to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // Bypass PushInventory, this must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, hashBestChain)); pfrom->PushMessage("inv", vInv); pfrom->hashContinue = 0; } } } else if (inv.IsKnownType()) { // Send stream from relay memory CRITICAL_BLOCK(cs_mapRelay) { map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) pfrom->PushMessage(inv.GetCommand(), (*mi).second); } } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getblocks") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; // Find the last block the caller has in the main chain CBlockIndex* pindex = locator.GetBlockIndex(); // Send the rest of the chain if (pindex) pindex = pindex->pnext; int nLimit = 500 + locator.GetDistanceBack(); unsigned int nBytes = 0; printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit); for (; pindex; pindex = pindex->pnext) { if (pindex->GetBlockHash() == hashStop) { printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); CBlock block; block.ReadFromDisk(pindex, true); nBytes += block.GetSerializeSize(SER_NETWORK); if (--nLimit <= 0 || nBytes >= SendBufferSize()/2) { // When this block is requested, we'll send an inv that'll make them // getblocks the next batch of inventory. printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes); pfrom->hashContinue = pindex->GetBlockHash(); break; } } } else if (strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; CBlockIndex* pindex = NULL; if (locator.IsNull()) { // If locator is null, return the hashStop block map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop); if (mi == mapBlockIndex.end()) return true; pindex = (*mi).second; } else { // Find the last block the caller has in the main chain pindex = locator.GetBlockIndex(); if (pindex) pindex = pindex->pnext; } vector<CBlock> vHeaders; int nLimit = 2000 + locator.GetDistanceBack(); printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit); for (; pindex; pindex = pindex->pnext) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } pfrom->PushMessage("headers", vHeaders); } else if (strCommand == "tx") { vector<uint256> vWorkQueue; CDataStream vMsg(vRecv); CTransaction tx; vRecv >> tx; CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); bool fMissingInputs = false; if (tx.AcceptToMemoryPool(true, &fMissingInputs)) { SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); // Recursively process any orphan transactions that depended on this one for (int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev); mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev); ++mi) { const CDataStream& vMsg = *((*mi).second); CTransaction tx; CDataStream(vMsg) >> tx; CInv inv(MSG_TX, tx.GetHash()); if (tx.AcceptToMemoryPool(true)) { printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); } } } BOOST_FOREACH(uint256 hash, vWorkQueue) EraseOrphanTx(hash); } else if (fMissingInputs) { printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); AddOrphanTx(vMsg); // DoS prevention: do not allow mapOrphanTransactions to grow unbounded int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS); if (nEvicted > 0) printf("mapOrphan overflow, removed %d tx\n", nEvicted); } if (tx.nDoS) pfrom->Misbehaving(tx.nDoS); } else if (strCommand == "block") { CBlock block; vRecv >> block; printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str()); // block.print(); CInv inv(MSG_BLOCK, block.GetHash()); pfrom->AddInventoryKnown(inv); if (ProcessBlock(pfrom, &block)) mapAlreadyAskedFor.erase(inv); if (block.nDoS) pfrom->Misbehaving(block.nDoS); } else if (strCommand == "getaddr") { // Nodes rebroadcast an addr every 24 hours pfrom->vAddrToSend.clear(); int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours CRITICAL_BLOCK(cs_mapAddresses) { unsigned int nCount = 0; BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses) { const CAddress& addr = item.second; if (addr.nTime > nSince) nCount++; } BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses) { const CAddress& addr = item.second; if (addr.nTime > nSince && GetRand(nCount) < 2500) pfrom->PushAddress(addr); } } } else if (strCommand == "checkorder") { uint256 hashReply; vRecv >> hashReply; if (!GetBoolArg("-allowreceivebyip")) { pfrom->PushMessage("reply", hashReply, (int)2, string("")); return true; } CWalletTx order; vRecv >> order; /// we have a chance to check the order here // Keep giving the same key to the same ip until they use it if (!mapReuseKey.count(pfrom->addr)) pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true); // Send back approval of order and pubkey to use CScript scriptPubKey; scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG; pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey); } else if (strCommand == "reply") { uint256 hashReply; vRecv >> hashReply; CRequestTracker tracker; CRITICAL_BLOCK(pfrom->cs_mapRequests) { map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply); if (mi != pfrom->mapRequests.end()) { tracker = (*mi).second; pfrom->mapRequests.erase(mi); } } if (!tracker.IsNull()) tracker.fn(tracker.param1, vRecv); } else if (strCommand == "ping") { } else if (strCommand == "alert") { CAlert alert; vRecv >> alert; if (alert.ProcessAlert()) { // Relay pfrom->setKnown.insert(alert.GetHash()); CRITICAL_BLOCK(cs_vNodes) BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } } else { // Ignore unknown commands for extensibility } // Update the last seen time for this node's address if (pfrom->fNetworkNode) if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping") AddressCurrentlyConnected(pfrom->addr); return true; } bool ProcessMessages(CNode* pfrom) { CDataStream& vRecv = pfrom->vRecv; if (vRecv.empty()) return true; //if (fDebug) // printf("ProcessMessages(%u bytes)\n", vRecv.size()); // // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data // loop { // Scan for message start CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart)); int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader()); if (vRecv.end() - pstart < nHeaderSize) { if (vRecv.size() > nHeaderSize) { printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n"); vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize); } break; } if (pstart - vRecv.begin() > 0) printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin()); vRecv.erase(vRecv.begin(), pstart); // Read header vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize); CMessageHeader hdr; vRecv >> hdr; if (!hdr.IsValid()) { printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str()); continue; } string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; if (nMessageSize > MAX_SIZE) { printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize); continue; } if (nMessageSize > vRecv.size()) { // Rewind and wait for rest of message vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end()); break; } // Checksum uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); if (nChecksum != hdr.nChecksum) { printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum); continue; } // Copy message to its own buffer CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion); vRecv.ignore(nMessageSize); // Process message bool fRet = false; try { CRITICAL_BLOCK(cs_main) fRet = ProcessMessage(pfrom, strCommand, vMsg); if (fShutdown) return true; } catch (std::ios_base::failure& e) { if (strstr(e.what(), "end of data")) { // Allow exceptions from underlength message on vRecv printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from overlong size printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what()); } else { PrintExceptionContinue(&e, "ProcessMessage()"); } } catch (std::exception& e) { PrintExceptionContinue(&e, "ProcessMessage()"); } catch (...) { PrintExceptionContinue(NULL, "ProcessMessage()"); } if (!fRet) printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize); } vRecv.Compact(); return true; } bool SendMessages(CNode* pto, bool fSendTrickle) { CRITICAL_BLOCK(cs_main) { // Don't send anything until we get their version message if (pto->nVersion == 0) return true; // Keep-alive ping if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) pto->PushMessage("ping"); // Resend wallet transactions that haven't gotten in a block yet ResendWalletTransactions(); // Address refresh broadcast static int64 nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) { CRITICAL_BLOCK(cs_vNodes) { BOOST_FOREACH(CNode* pnode, vNodes) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); // Rebroadcast our address if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable()) { CAddress addr(addrLocalHost); addr.nTime = GetAdjustedTime(); pnode->PushAddress(addr); } } } nLastRebroadcast = GetTime(); } // Clear out old addresses periodically so it's not too much work at once static int64 nLastClear; if (nLastClear == 0) nLastClear = GetTime(); if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3) { nLastClear = GetTime(); CRITICAL_BLOCK(cs_mapAddresses) { CAddrDB addrdb; int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60; for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin(); mi != mapAddresses.end();) { const CAddress& addr = (*mi).second; if (addr.nTime < nSince) { if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20) break; addrdb.EraseAddress(addr); mapAddresses.erase(mi++); } else mi++; } } } // // Message: addr // if (fSendTrickle) { vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) { // returns true if wasn't already contained in the set if (pto->setAddrKnown.insert(addr).second) { vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { pto->PushMessage("addr", vAddr); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } // // Message: inventory // vector<CInv> vInv; vector<CInv> vInvWait; CRITICAL_BLOCK(pto->cs_inventory) { vInv.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size()); BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) { if (pto->setInventoryKnown.count(inv)) continue; // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { // 1/4 of tx invs blast to all immediately static uint256 hashSalt; if (hashSalt == 0) RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt)); uint256 hashRand = inv.hash ^ hashSalt; hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((hashRand & 3) != 0); // always trickle our own transactions if (!fTrickleWait) { CWalletTx wtx; if (GetTransaction(inv.hash, wtx)) if (wtx.fFromMe) fTrickleWait = true; } if (fTrickleWait) { vInvWait.push_back(inv); continue; } } // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { vInv.push_back(inv); if (vInv.size() >= 1000) { pto->PushMessage("inv", vInv); vInv.clear(); } } } pto->vInventoryToSend = vInvWait; } if (!vInv.empty()) pto->PushMessage("inv", vInv); // // Message: getdata // vector<CInv> vGetData; int64 nNow = GetTime() * 1000000; CTxDB txdb("r"); while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) { const CInv& inv = (*pto->mapAskFor.begin()).second; if (!AlreadyHave(txdb, inv)) { printf("sending getdata: %s\n", inv.ToString().c_str()); vGetData.push_back(inv); if (vGetData.size() >= 1000) { pto->PushMessage("getdata", vGetData); vGetData.clear(); } } mapAlreadyAskedFor[inv] = nNow; pto->mapAskFor.erase(pto->mapAskFor.begin()); } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); } return true; } ////////////////////////////////////////////////////////////////////////////// // // BitcoinMiner // int static FormatHashBlocks(void* pbuffer, unsigned int len) { unsigned char* pdata = (unsigned char*)pbuffer; unsigned int blocks = 1 + ((len + 8) / 64); unsigned char* pend = pdata + 64 * blocks; memset(pdata + len, 0, 64 * blocks - len); pdata[len] = 0x80; unsigned int bits = len * 8; pend[-1] = (bits >> 0) & 0xff; pend[-2] = (bits >> 8) & 0xff; pend[-3] = (bits >> 16) & 0xff; pend[-4] = (bits >> 24) & 0xff; return blocks; } static const unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; void SHA256Transform(void* pstate, void* pinput, const void* pinit) { SHA256_CTX ctx; unsigned char data[64]; SHA256_Init(&ctx); for (int i = 0; i < 16; i++) ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]); for (int i = 0; i < 8; i++) ctx.h[i] = ((uint32_t*)pinit)[i]; SHA256_Update(&ctx, data, sizeof(data)); for (int i = 0; i < 8; i++) ((uint32_t*)pstate)[i] = ctx.h[i]; } // // ScanHash scans nonces looking for a hash with at least some zero bits. // It operates on big endian data. Caller does the byte reversing. // All input buffers are 16-byte aligned. nNonce is usually preserved // between calls, but periodically or if nNonce is 0xffff0000 or above, // the block is rebuilt and nNonce starts over at zero. // unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone) { unsigned int& nNonce = *(unsigned int*)(pdata + 12); for (;;) { // Crypto++ SHA-256 // Hash pdata using pmidstate as the starting state into // preformatted buffer phash1, then hash phash1 into phash nNonce++; SHA256Transform(phash1, pdata, pmidstate); SHA256Transform(phash, phash1, pSHA256InitState); // Return the nonce if the hash has at least some zero bits, // caller will check if it has enough to reach the target if (((unsigned short*)phash)[14] == 0) return nNonce; // If nothing found after trying for a while, return -1 if ((nNonce & 0xffff) == 0) { nHashesDone = 0xffff+1; return -1; } } } // Some explaining would be appreciated class COrphan { public: CTransaction* ptx; set<uint256> setDependsOn; double dPriority; COrphan(CTransaction* ptxIn) { ptx = ptxIn; dPriority = 0; } void print() const { printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority); BOOST_FOREACH(uint256 hash, setDependsOn) printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str()); } }; uint64 nLastBlockTx = 0; uint64 nLastBlockSize = 0; CBlock* CreateNewBlock(CReserveKey& reservekey) { CBlockIndex* pindexPrev = pindexBest; // Create new block auto_ptr<CBlock> pblock(new CBlock()); if (!pblock.get()) return NULL; // Create coinbase tx CTransaction txNew; txNew.vin.resize(1); txNew.vin[0].prevout.SetNull(); txNew.vout.resize(1); txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG; // Add our coinbase tx as first transaction pblock->vtx.push_back(txNew); // Collect memory pool transactions into the block int64 nFees = 0; CRITICAL_BLOCK(cs_main) CRITICAL_BLOCK(cs_mapTransactions) { CTxDB txdb("r"); // Priority order to process transactions list<COrphan> vOrphan; // list memory doesn't move map<uint256, vector<COrphan*> > mapDependers; multimap<double, CTransaction*> mapPriority; for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi) { CTransaction& tx = (*mi).second; if (tx.IsCoinBase() || !tx.IsFinal()) continue; COrphan* porphan = NULL; double dPriority = 0; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Read prev transaction CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) { // Has to wait for dependencies if (!porphan) { // Use list for automatic deletion vOrphan.push_back(COrphan(&tx)); porphan = &vOrphan.back(); } mapDependers[txin.prevout.hash].push_back(porphan); porphan->setDependsOn.insert(txin.prevout.hash); continue; } int64 nValueIn = txPrev.vout[txin.prevout.n].nValue; // Read block header int nConf = txindex.GetDepthInMainChain(); dPriority += (double)nValueIn * nConf; if (fDebug && GetBoolArg("-printpriority")) printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority); } // Priority is sum(valuein * age) / txsize dPriority /= ::GetSerializeSize(tx, SER_NETWORK); if (porphan) porphan->dPriority = dPriority; else mapPriority.insert(make_pair(-dPriority, &(*mi).second)); if (fDebug && GetBoolArg("-printpriority")) { printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str()); if (porphan) porphan->print(); printf("\n"); } } // Collect transactions into block map<uint256, CTxIndex> mapTestPool; uint64 nBlockSize = 1000; uint64 nBlockTx = 0; int nBlockSigOps = 100; while (!mapPriority.empty()) { // Take highest priority transaction off priority queue double dPriority = -(*mapPriority.begin()).first; CTransaction& tx = *(*mapPriority.begin()).second; mapPriority.erase(mapPriority.begin()); // Size limits unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK); if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) continue; // Legacy limits on sigOps: int nTxSigOps = tx.GetLegacySigOpCount(); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; // Transaction fee required depends on block size bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority)); int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK); // Connecting shouldn't fail due to dependency on other memory pool transactions // because we're already processing them in order of dependency map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool); MapPrevTx mapInputs; bool fInvalid; if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid)) continue; int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (nTxFees < nMinFee) continue; nTxSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true)) continue; mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size()); swap(mapTestPool, mapTestPoolTmp); // Added pblock->vtx.push_back(tx); nBlockSize += nTxSize; ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nTxFees; // Add transactions that depend on this one to the priority queue uint256 hash = tx.GetHash(); if (mapDependers.count(hash)) { BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) { if (!porphan->setDependsOn.empty()) { porphan->setDependsOn.erase(hash); if (porphan->setDependsOn.empty()) mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx)); } } } } nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; printf("CreateNewBlock(): total size %lu\n", nBlockSize); } pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees); // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); pblock->UpdateTime(pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get()); pblock->nNonce = 0; return pblock.release(); } void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS; assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); } void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1) { // // Prebuild hash buffers // struct { struct unnamed2 { int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; } block; unsigned char pchPadding0[64]; uint256 hash1; unsigned char pchPadding1[64]; } tmp; memset(&tmp, 0, sizeof(tmp)); tmp.block.nVersion = pblock->nVersion; tmp.block.hashPrevBlock = pblock->hashPrevBlock; tmp.block.hashMerkleRoot = pblock->hashMerkleRoot; tmp.block.nTime = pblock->nTime; tmp.block.nBits = pblock->nBits; tmp.block.nNonce = pblock->nNonce; FormatHashBlocks(&tmp.block, sizeof(tmp.block)); FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1)); // Byte swap all the input buffer for (int i = 0; i < sizeof(tmp)/4; i++) ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]); // Precalc the first half of the first hash, which stays constant SHA256Transform(pmidstate, &tmp.block, pSHA256InitState); memcpy(pdata, &tmp.block, 128); memcpy(phash1, &tmp.hash1, 64); } bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) { uint256 hash = pblock->GetHash(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); if (hash > hashTarget) return false; //// debug print printf("BitcoinMiner:\n"); printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); pblock->print(); printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str()); printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str()); // Found a solution CRITICAL_BLOCK(cs_main) { if (pblock->hashPrevBlock != hashBestChain) return error("BitcoinMiner : generated block is stale"); // Remove key from key pool reservekey.KeepKey(); // Track how many getdata requests this block gets CRITICAL_BLOCK(wallet.cs_wallet) wallet.mapRequestCount[pblock->GetHash()] = 0; // Process this block the same as if we had received it from another node if (!ProcessBlock(NULL, pblock)) return error("BitcoinMiner : ProcessBlock, block not accepted"); } return true; } void static ThreadBitcoinMiner(void* parg); static bool fGenerateBitcoins = false; static bool fLimitProcessors = false; static int nLimitProcessors = -1; void static BitcoinMiner(CWallet *pwallet) { printf("BitcoinMiner started\n"); SetThreadPriority(THREAD_PRIORITY_LOWEST); // Each thread has its own key and counter CReserveKey reservekey(pwallet); unsigned int nExtraNonce = 0; while (fGenerateBitcoins) { if (AffinityBugWorkaround(ThreadBitcoinMiner)) return; if (fShutdown) return; while (vNodes.empty() || IsInitialBlockDownload()) { Sleep(1000); if (fShutdown) return; if (!fGenerateBitcoins) return; } // // Create new block // unsigned int nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrev = pindexBest; auto_ptr<CBlock> pblock(CreateNewBlock(reservekey)); if (!pblock.get()) return; IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce); printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size()); // // Prebuild hash buffers // char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf); char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf); char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf); FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1); unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4); unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8); unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12); // // Search // int64 nStart = GetTime(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); uint256 hashbuf[2]; uint256& hash = *alignup<16>(hashbuf); loop { unsigned int nHashesDone = 0; unsigned int nNonceFound; // Crypto++ SHA-256 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone); // Check if something found if (nNonceFound != -1) { for (int i = 0; i < sizeof(hash)/4; i++) ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]); if (hash <= hashTarget) { // Found a solution pblock->nNonce = ByteReverse(nNonceFound); assert(hash == pblock->GetHash()); SetThreadPriority(THREAD_PRIORITY_NORMAL); CheckWork(pblock.get(), *pwalletMain, reservekey); SetThreadPriority(THREAD_PRIORITY_LOWEST); break; } } // Meter hashes/sec static int64 nHashCounter; if (nHPSTimerStart == 0) { nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; } else nHashCounter += nHashesDone; if (GetTimeMillis() - nHPSTimerStart > 4000) { static CCriticalSection cs; CRITICAL_BLOCK(cs) { if (GetTimeMillis() - nHPSTimerStart > 4000) { dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart); nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0); UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0)); static int64 nLogTime; if (GetTime() - nLogTime > 30 * 60) { nLogTime = GetTime(); printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str()); printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0); } } } } // Check for stop or if block needs to be rebuilt if (fShutdown) return; if (!fGenerateBitcoins) return; if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors) return; if (vNodes.empty()) break; if (nBlockNonce >= 0xffff0000) break; if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60) break; if (pindexPrev != pindexBest) break; // Update nTime every few seconds pblock->UpdateTime(pindexPrev); nBlockTime = ByteReverse(pblock->nTime); if (fTestNet) { // Changing pblock->nTime can change work required on testnet: nBlockBits = ByteReverse(pblock->nBits); hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); } } } } void static ThreadBitcoinMiner(void* parg) { CWallet* pwallet = (CWallet*)parg; try { vnThreadsRunning[THREAD_MINER]++; BitcoinMiner(pwallet); vnThreadsRunning[THREAD_MINER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_MINER]--; PrintException(&e, "ThreadBitcoinMiner()"); } catch (...) { vnThreadsRunning[THREAD_MINER]--; PrintException(NULL, "ThreadBitcoinMiner()"); } UIThreadCall(boost::bind(CalledSetStatusBar, "", 0)); nHPSTimerStart = 0; if (vnThreadsRunning[THREAD_MINER] == 0) dHashesPerSec = 0; printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]); } void GenerateBitcoins(bool fGenerate, CWallet* pwallet) { fGenerateBitcoins = fGenerate; nLimitProcessors = GetArg("-genproclimit", -1); if (nLimitProcessors == 0) fGenerateBitcoins = false; fLimitProcessors = (nLimitProcessors != -1); if (fGenerate) { int nProcessors = boost::thread::hardware_concurrency(); printf("%d processors\n", nProcessors); if (nProcessors < 1) nProcessors = 1; if (fLimitProcessors && nProcessors > nLimitProcessors) nProcessors = nLimitProcessors; int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER]; printf("Starting %d BitcoinMiner threads\n", nAddThreads); for (int i = 0; i < nAddThreads; i++) { if (!CreateThread(ThreadBitcoinMiner, pwallet)) printf("Error: CreateThread(ThreadBitcoinMiner) failed\n"); Sleep(10); } } }
./CrossVul/dataset_final_sorted/CWE-16/cpp/good_3628_0
crossvul-cpp_data_good_3582_0
/* * linux/kernel/sys.c * * Copyright (C) 1991, 1992 Linus Torvalds */ #include <linux/export.h> #include <linux/mm.h> #include <linux/utsname.h> #include <linux/mman.h> #include <linux/reboot.h> #include <linux/prctl.h> #include <linux/highuid.h> #include <linux/fs.h> #include <linux/kmod.h> #include <linux/perf_event.h> #include <linux/resource.h> #include <linux/kernel.h> #include <linux/kexec.h> #include <linux/workqueue.h> #include <linux/capability.h> #include <linux/device.h> #include <linux/key.h> #include <linux/times.h> #include <linux/posix-timers.h> #include <linux/security.h> #include <linux/dcookies.h> #include <linux/suspend.h> #include <linux/tty.h> #include <linux/signal.h> #include <linux/cn_proc.h> #include <linux/getcpu.h> #include <linux/task_io_accounting_ops.h> #include <linux/seccomp.h> #include <linux/cpu.h> #include <linux/personality.h> #include <linux/ptrace.h> #include <linux/fs_struct.h> #include <linux/file.h> #include <linux/mount.h> #include <linux/gfp.h> #include <linux/syscore_ops.h> #include <linux/version.h> #include <linux/ctype.h> #include <linux/compat.h> #include <linux/syscalls.h> #include <linux/kprobes.h> #include <linux/user_namespace.h> #include <linux/kmsg_dump.h> /* Move somewhere else to avoid recompiling? */ #include <generated/utsrelease.h> #include <asm/uaccess.h> #include <asm/io.h> #include <asm/unistd.h> #ifndef SET_UNALIGN_CTL # define SET_UNALIGN_CTL(a,b) (-EINVAL) #endif #ifndef GET_UNALIGN_CTL # define GET_UNALIGN_CTL(a,b) (-EINVAL) #endif #ifndef SET_FPEMU_CTL # define SET_FPEMU_CTL(a,b) (-EINVAL) #endif #ifndef GET_FPEMU_CTL # define GET_FPEMU_CTL(a,b) (-EINVAL) #endif #ifndef SET_FPEXC_CTL # define SET_FPEXC_CTL(a,b) (-EINVAL) #endif #ifndef GET_FPEXC_CTL # define GET_FPEXC_CTL(a,b) (-EINVAL) #endif #ifndef GET_ENDIAN # define GET_ENDIAN(a,b) (-EINVAL) #endif #ifndef SET_ENDIAN # define SET_ENDIAN(a,b) (-EINVAL) #endif #ifndef GET_TSC_CTL # define GET_TSC_CTL(a) (-EINVAL) #endif #ifndef SET_TSC_CTL # define SET_TSC_CTL(a) (-EINVAL) #endif /* * this is where the system-wide overflow UID and GID are defined, for * architectures that now have 32-bit UID/GID but didn't in the past */ int overflowuid = DEFAULT_OVERFLOWUID; int overflowgid = DEFAULT_OVERFLOWGID; EXPORT_SYMBOL(overflowuid); EXPORT_SYMBOL(overflowgid); /* * the same as above, but for filesystems which can only store a 16-bit * UID and GID. as such, this is needed on all architectures */ int fs_overflowuid = DEFAULT_FS_OVERFLOWUID; int fs_overflowgid = DEFAULT_FS_OVERFLOWUID; EXPORT_SYMBOL(fs_overflowuid); EXPORT_SYMBOL(fs_overflowgid); /* * this indicates whether you can reboot with ctrl-alt-del: the default is yes */ int C_A_D = 1; struct pid *cad_pid; EXPORT_SYMBOL(cad_pid); /* * If set, this is used for preparing the system to power off. */ void (*pm_power_off_prepare)(void); /* * Returns true if current's euid is same as p's uid or euid, * or has CAP_SYS_NICE to p's user_ns. * * Called with rcu_read_lock, creds are safe */ static bool set_one_prio_perm(struct task_struct *p) { const struct cred *cred = current_cred(), *pcred = __task_cred(p); if (uid_eq(pcred->uid, cred->euid) || uid_eq(pcred->euid, cred->euid)) return true; if (ns_capable(pcred->user_ns, CAP_SYS_NICE)) return true; return false; } /* * set the priority of a task * - the caller must hold the RCU read lock */ static int set_one_prio(struct task_struct *p, int niceval, int error) { int no_nice; if (!set_one_prio_perm(p)) { error = -EPERM; goto out; } if (niceval < task_nice(p) && !can_nice(p, niceval)) { error = -EACCES; goto out; } no_nice = security_task_setnice(p, niceval); if (no_nice) { error = no_nice; goto out; } if (error == -ESRCH) error = 0; set_user_nice(p, niceval); out: return error; } SYSCALL_DEFINE3(setpriority, int, which, int, who, int, niceval) { struct task_struct *g, *p; struct user_struct *user; const struct cred *cred = current_cred(); int error = -EINVAL; struct pid *pgrp; kuid_t uid; if (which > PRIO_USER || which < PRIO_PROCESS) goto out; /* normalize: avoid signed division (rounding problems) */ error = -ESRCH; if (niceval < -20) niceval = -20; if (niceval > 19) niceval = 19; rcu_read_lock(); read_lock(&tasklist_lock); switch (which) { case PRIO_PROCESS: if (who) p = find_task_by_vpid(who); else p = current; if (p) error = set_one_prio(p, niceval, error); break; case PRIO_PGRP: if (who) pgrp = find_vpid(who); else pgrp = task_pgrp(current); do_each_pid_thread(pgrp, PIDTYPE_PGID, p) { error = set_one_prio(p, niceval, error); } while_each_pid_thread(pgrp, PIDTYPE_PGID, p); break; case PRIO_USER: uid = make_kuid(cred->user_ns, who); user = cred->user; if (!who) uid = cred->uid; else if (!uid_eq(uid, cred->uid) && !(user = find_user(uid))) goto out_unlock; /* No processes for this user */ do_each_thread(g, p) { if (uid_eq(task_uid(p), uid)) error = set_one_prio(p, niceval, error); } while_each_thread(g, p); if (!uid_eq(uid, cred->uid)) free_uid(user); /* For find_user() */ break; } out_unlock: read_unlock(&tasklist_lock); rcu_read_unlock(); out: return error; } /* * Ugh. To avoid negative return values, "getpriority()" will * not return the normal nice-value, but a negated value that * has been offset by 20 (ie it returns 40..1 instead of -20..19) * to stay compatible. */ SYSCALL_DEFINE2(getpriority, int, which, int, who) { struct task_struct *g, *p; struct user_struct *user; const struct cred *cred = current_cred(); long niceval, retval = -ESRCH; struct pid *pgrp; kuid_t uid; if (which > PRIO_USER || which < PRIO_PROCESS) return -EINVAL; rcu_read_lock(); read_lock(&tasklist_lock); switch (which) { case PRIO_PROCESS: if (who) p = find_task_by_vpid(who); else p = current; if (p) { niceval = 20 - task_nice(p); if (niceval > retval) retval = niceval; } break; case PRIO_PGRP: if (who) pgrp = find_vpid(who); else pgrp = task_pgrp(current); do_each_pid_thread(pgrp, PIDTYPE_PGID, p) { niceval = 20 - task_nice(p); if (niceval > retval) retval = niceval; } while_each_pid_thread(pgrp, PIDTYPE_PGID, p); break; case PRIO_USER: uid = make_kuid(cred->user_ns, who); user = cred->user; if (!who) uid = cred->uid; else if (!uid_eq(uid, cred->uid) && !(user = find_user(uid))) goto out_unlock; /* No processes for this user */ do_each_thread(g, p) { if (uid_eq(task_uid(p), uid)) { niceval = 20 - task_nice(p); if (niceval > retval) retval = niceval; } } while_each_thread(g, p); if (!uid_eq(uid, cred->uid)) free_uid(user); /* for find_user() */ break; } out_unlock: read_unlock(&tasklist_lock); rcu_read_unlock(); return retval; } /** * emergency_restart - reboot the system * * Without shutting down any hardware or taking any locks * reboot the system. This is called when we know we are in * trouble so this is our best effort to reboot. This is * safe to call in interrupt context. */ void emergency_restart(void) { kmsg_dump(KMSG_DUMP_EMERG); machine_emergency_restart(); } EXPORT_SYMBOL_GPL(emergency_restart); void kernel_restart_prepare(char *cmd) { blocking_notifier_call_chain(&reboot_notifier_list, SYS_RESTART, cmd); system_state = SYSTEM_RESTART; usermodehelper_disable(); device_shutdown(); syscore_shutdown(); } /** * register_reboot_notifier - Register function to be called at reboot time * @nb: Info about notifier function to be called * * Registers a function with the list of functions * to be called at reboot time. * * Currently always returns zero, as blocking_notifier_chain_register() * always returns zero. */ int register_reboot_notifier(struct notifier_block *nb) { return blocking_notifier_chain_register(&reboot_notifier_list, nb); } EXPORT_SYMBOL(register_reboot_notifier); /** * unregister_reboot_notifier - Unregister previously registered reboot notifier * @nb: Hook to be unregistered * * Unregisters a previously registered reboot * notifier function. * * Returns zero on success, or %-ENOENT on failure. */ int unregister_reboot_notifier(struct notifier_block *nb) { return blocking_notifier_chain_unregister(&reboot_notifier_list, nb); } EXPORT_SYMBOL(unregister_reboot_notifier); /** * kernel_restart - reboot the system * @cmd: pointer to buffer containing command to execute for restart * or %NULL * * Shutdown everything and perform a clean reboot. * This is not safe to call in interrupt context. */ void kernel_restart(char *cmd) { kernel_restart_prepare(cmd); disable_nonboot_cpus(); if (!cmd) printk(KERN_EMERG "Restarting system.\n"); else printk(KERN_EMERG "Restarting system with command '%s'.\n", cmd); kmsg_dump(KMSG_DUMP_RESTART); machine_restart(cmd); } EXPORT_SYMBOL_GPL(kernel_restart); static void kernel_shutdown_prepare(enum system_states state) { blocking_notifier_call_chain(&reboot_notifier_list, (state == SYSTEM_HALT)?SYS_HALT:SYS_POWER_OFF, NULL); system_state = state; usermodehelper_disable(); device_shutdown(); } /** * kernel_halt - halt the system * * Shutdown everything and perform a clean system halt. */ void kernel_halt(void) { kernel_shutdown_prepare(SYSTEM_HALT); syscore_shutdown(); printk(KERN_EMERG "System halted.\n"); kmsg_dump(KMSG_DUMP_HALT); machine_halt(); } EXPORT_SYMBOL_GPL(kernel_halt); /** * kernel_power_off - power_off the system * * Shutdown everything and perform a clean system power_off. */ void kernel_power_off(void) { kernel_shutdown_prepare(SYSTEM_POWER_OFF); if (pm_power_off_prepare) pm_power_off_prepare(); disable_nonboot_cpus(); syscore_shutdown(); printk(KERN_EMERG "Power down.\n"); kmsg_dump(KMSG_DUMP_POWEROFF); machine_power_off(); } EXPORT_SYMBOL_GPL(kernel_power_off); static DEFINE_MUTEX(reboot_mutex); /* * Reboot system call: for obvious reasons only root may call it, * and even root needs to set up some magic numbers in the registers * so that some mistake won't make this reboot the whole machine. * You can also set the meaning of the ctrl-alt-del-key here. * * reboot doesn't sync: do that yourself before calling this. */ SYSCALL_DEFINE4(reboot, int, magic1, int, magic2, unsigned int, cmd, void __user *, arg) { char buffer[256]; int ret = 0; /* We only trust the superuser with rebooting the system. */ if (!capable(CAP_SYS_BOOT)) return -EPERM; /* For safety, we require "magic" arguments. */ if (magic1 != LINUX_REBOOT_MAGIC1 || (magic2 != LINUX_REBOOT_MAGIC2 && magic2 != LINUX_REBOOT_MAGIC2A && magic2 != LINUX_REBOOT_MAGIC2B && magic2 != LINUX_REBOOT_MAGIC2C)) return -EINVAL; /* * If pid namespaces are enabled and the current task is in a child * pid_namespace, the command is handled by reboot_pid_ns() which will * call do_exit(). */ ret = reboot_pid_ns(task_active_pid_ns(current), cmd); if (ret) return ret; /* Instead of trying to make the power_off code look like * halt when pm_power_off is not set do it the easy way. */ if ((cmd == LINUX_REBOOT_CMD_POWER_OFF) && !pm_power_off) cmd = LINUX_REBOOT_CMD_HALT; mutex_lock(&reboot_mutex); switch (cmd) { case LINUX_REBOOT_CMD_RESTART: kernel_restart(NULL); break; case LINUX_REBOOT_CMD_CAD_ON: C_A_D = 1; break; case LINUX_REBOOT_CMD_CAD_OFF: C_A_D = 0; break; case LINUX_REBOOT_CMD_HALT: kernel_halt(); do_exit(0); panic("cannot halt"); case LINUX_REBOOT_CMD_POWER_OFF: kernel_power_off(); do_exit(0); break; case LINUX_REBOOT_CMD_RESTART2: if (strncpy_from_user(&buffer[0], arg, sizeof(buffer) - 1) < 0) { ret = -EFAULT; break; } buffer[sizeof(buffer) - 1] = '\0'; kernel_restart(buffer); break; #ifdef CONFIG_KEXEC case LINUX_REBOOT_CMD_KEXEC: ret = kernel_kexec(); break; #endif #ifdef CONFIG_HIBERNATION case LINUX_REBOOT_CMD_SW_SUSPEND: ret = hibernate(); break; #endif default: ret = -EINVAL; break; } mutex_unlock(&reboot_mutex); return ret; } static void deferred_cad(struct work_struct *dummy) { kernel_restart(NULL); } /* * This function gets called by ctrl-alt-del - ie the keyboard interrupt. * As it's called within an interrupt, it may NOT sync: the only choice * is whether to reboot at once, or just ignore the ctrl-alt-del. */ void ctrl_alt_del(void) { static DECLARE_WORK(cad_work, deferred_cad); if (C_A_D) schedule_work(&cad_work); else kill_cad_pid(SIGINT, 1); } /* * Unprivileged users may change the real gid to the effective gid * or vice versa. (BSD-style) * * If you set the real gid at all, or set the effective gid to a value not * equal to the real gid, then the saved gid is set to the new effective gid. * * This makes it possible for a setgid program to completely drop its * privileges, which is often a useful assertion to make when you are doing * a security audit over a program. * * The general idea is that a program which uses just setregid() will be * 100% compatible with BSD. A program which uses just setgid() will be * 100% compatible with POSIX with saved IDs. * * SMP: There are not races, the GIDs are checked only by filesystem * operations (as far as semantic preservation is concerned). */ SYSCALL_DEFINE2(setregid, gid_t, rgid, gid_t, egid) { struct user_namespace *ns = current_user_ns(); const struct cred *old; struct cred *new; int retval; kgid_t krgid, kegid; krgid = make_kgid(ns, rgid); kegid = make_kgid(ns, egid); if ((rgid != (gid_t) -1) && !gid_valid(krgid)) return -EINVAL; if ((egid != (gid_t) -1) && !gid_valid(kegid)) return -EINVAL; new = prepare_creds(); if (!new) return -ENOMEM; old = current_cred(); retval = -EPERM; if (rgid != (gid_t) -1) { if (gid_eq(old->gid, krgid) || gid_eq(old->egid, krgid) || nsown_capable(CAP_SETGID)) new->gid = krgid; else goto error; } if (egid != (gid_t) -1) { if (gid_eq(old->gid, kegid) || gid_eq(old->egid, kegid) || gid_eq(old->sgid, kegid) || nsown_capable(CAP_SETGID)) new->egid = kegid; else goto error; } if (rgid != (gid_t) -1 || (egid != (gid_t) -1 && !gid_eq(kegid, old->gid))) new->sgid = new->egid; new->fsgid = new->egid; return commit_creds(new); error: abort_creds(new); return retval; } /* * setgid() is implemented like SysV w/ SAVED_IDS * * SMP: Same implicit races as above. */ SYSCALL_DEFINE1(setgid, gid_t, gid) { struct user_namespace *ns = current_user_ns(); const struct cred *old; struct cred *new; int retval; kgid_t kgid; kgid = make_kgid(ns, gid); if (!gid_valid(kgid)) return -EINVAL; new = prepare_creds(); if (!new) return -ENOMEM; old = current_cred(); retval = -EPERM; if (nsown_capable(CAP_SETGID)) new->gid = new->egid = new->sgid = new->fsgid = kgid; else if (gid_eq(kgid, old->gid) || gid_eq(kgid, old->sgid)) new->egid = new->fsgid = kgid; else goto error; return commit_creds(new); error: abort_creds(new); return retval; } /* * change the user struct in a credentials set to match the new UID */ static int set_user(struct cred *new) { struct user_struct *new_user; new_user = alloc_uid(new->uid); if (!new_user) return -EAGAIN; /* * We don't fail in case of NPROC limit excess here because too many * poorly written programs don't check set*uid() return code, assuming * it never fails if called by root. We may still enforce NPROC limit * for programs doing set*uid()+execve() by harmlessly deferring the * failure to the execve() stage. */ if (atomic_read(&new_user->processes) >= rlimit(RLIMIT_NPROC) && new_user != INIT_USER) current->flags |= PF_NPROC_EXCEEDED; else current->flags &= ~PF_NPROC_EXCEEDED; free_uid(new->user); new->user = new_user; return 0; } /* * Unprivileged users may change the real uid to the effective uid * or vice versa. (BSD-style) * * If you set the real uid at all, or set the effective uid to a value not * equal to the real uid, then the saved uid is set to the new effective uid. * * This makes it possible for a setuid program to completely drop its * privileges, which is often a useful assertion to make when you are doing * a security audit over a program. * * The general idea is that a program which uses just setreuid() will be * 100% compatible with BSD. A program which uses just setuid() will be * 100% compatible with POSIX with saved IDs. */ SYSCALL_DEFINE2(setreuid, uid_t, ruid, uid_t, euid) { struct user_namespace *ns = current_user_ns(); const struct cred *old; struct cred *new; int retval; kuid_t kruid, keuid; kruid = make_kuid(ns, ruid); keuid = make_kuid(ns, euid); if ((ruid != (uid_t) -1) && !uid_valid(kruid)) return -EINVAL; if ((euid != (uid_t) -1) && !uid_valid(keuid)) return -EINVAL; new = prepare_creds(); if (!new) return -ENOMEM; old = current_cred(); retval = -EPERM; if (ruid != (uid_t) -1) { new->uid = kruid; if (!uid_eq(old->uid, kruid) && !uid_eq(old->euid, kruid) && !nsown_capable(CAP_SETUID)) goto error; } if (euid != (uid_t) -1) { new->euid = keuid; if (!uid_eq(old->uid, keuid) && !uid_eq(old->euid, keuid) && !uid_eq(old->suid, keuid) && !nsown_capable(CAP_SETUID)) goto error; } if (!uid_eq(new->uid, old->uid)) { retval = set_user(new); if (retval < 0) goto error; } if (ruid != (uid_t) -1 || (euid != (uid_t) -1 && !uid_eq(keuid, old->uid))) new->suid = new->euid; new->fsuid = new->euid; retval = security_task_fix_setuid(new, old, LSM_SETID_RE); if (retval < 0) goto error; return commit_creds(new); error: abort_creds(new); return retval; } /* * setuid() is implemented like SysV with SAVED_IDS * * Note that SAVED_ID's is deficient in that a setuid root program * like sendmail, for example, cannot set its uid to be a normal * user and then switch back, because if you're root, setuid() sets * the saved uid too. If you don't like this, blame the bright people * in the POSIX committee and/or USG. Note that the BSD-style setreuid() * will allow a root program to temporarily drop privileges and be able to * regain them by swapping the real and effective uid. */ SYSCALL_DEFINE1(setuid, uid_t, uid) { struct user_namespace *ns = current_user_ns(); const struct cred *old; struct cred *new; int retval; kuid_t kuid; kuid = make_kuid(ns, uid); if (!uid_valid(kuid)) return -EINVAL; new = prepare_creds(); if (!new) return -ENOMEM; old = current_cred(); retval = -EPERM; if (nsown_capable(CAP_SETUID)) { new->suid = new->uid = kuid; if (!uid_eq(kuid, old->uid)) { retval = set_user(new); if (retval < 0) goto error; } } else if (!uid_eq(kuid, old->uid) && !uid_eq(kuid, new->suid)) { goto error; } new->fsuid = new->euid = kuid; retval = security_task_fix_setuid(new, old, LSM_SETID_ID); if (retval < 0) goto error; return commit_creds(new); error: abort_creds(new); return retval; } /* * This function implements a generic ability to update ruid, euid, * and suid. This allows you to implement the 4.4 compatible seteuid(). */ SYSCALL_DEFINE3(setresuid, uid_t, ruid, uid_t, euid, uid_t, suid) { struct user_namespace *ns = current_user_ns(); const struct cred *old; struct cred *new; int retval; kuid_t kruid, keuid, ksuid; kruid = make_kuid(ns, ruid); keuid = make_kuid(ns, euid); ksuid = make_kuid(ns, suid); if ((ruid != (uid_t) -1) && !uid_valid(kruid)) return -EINVAL; if ((euid != (uid_t) -1) && !uid_valid(keuid)) return -EINVAL; if ((suid != (uid_t) -1) && !uid_valid(ksuid)) return -EINVAL; new = prepare_creds(); if (!new) return -ENOMEM; old = current_cred(); retval = -EPERM; if (!nsown_capable(CAP_SETUID)) { if (ruid != (uid_t) -1 && !uid_eq(kruid, old->uid) && !uid_eq(kruid, old->euid) && !uid_eq(kruid, old->suid)) goto error; if (euid != (uid_t) -1 && !uid_eq(keuid, old->uid) && !uid_eq(keuid, old->euid) && !uid_eq(keuid, old->suid)) goto error; if (suid != (uid_t) -1 && !uid_eq(ksuid, old->uid) && !uid_eq(ksuid, old->euid) && !uid_eq(ksuid, old->suid)) goto error; } if (ruid != (uid_t) -1) { new->uid = kruid; if (!uid_eq(kruid, old->uid)) { retval = set_user(new); if (retval < 0) goto error; } } if (euid != (uid_t) -1) new->euid = keuid; if (suid != (uid_t) -1) new->suid = ksuid; new->fsuid = new->euid; retval = security_task_fix_setuid(new, old, LSM_SETID_RES); if (retval < 0) goto error; return commit_creds(new); error: abort_creds(new); return retval; } SYSCALL_DEFINE3(getresuid, uid_t __user *, ruidp, uid_t __user *, euidp, uid_t __user *, suidp) { const struct cred *cred = current_cred(); int retval; uid_t ruid, euid, suid; ruid = from_kuid_munged(cred->user_ns, cred->uid); euid = from_kuid_munged(cred->user_ns, cred->euid); suid = from_kuid_munged(cred->user_ns, cred->suid); if (!(retval = put_user(ruid, ruidp)) && !(retval = put_user(euid, euidp))) retval = put_user(suid, suidp); return retval; } /* * Same as above, but for rgid, egid, sgid. */ SYSCALL_DEFINE3(setresgid, gid_t, rgid, gid_t, egid, gid_t, sgid) { struct user_namespace *ns = current_user_ns(); const struct cred *old; struct cred *new; int retval; kgid_t krgid, kegid, ksgid; krgid = make_kgid(ns, rgid); kegid = make_kgid(ns, egid); ksgid = make_kgid(ns, sgid); if ((rgid != (gid_t) -1) && !gid_valid(krgid)) return -EINVAL; if ((egid != (gid_t) -1) && !gid_valid(kegid)) return -EINVAL; if ((sgid != (gid_t) -1) && !gid_valid(ksgid)) return -EINVAL; new = prepare_creds(); if (!new) return -ENOMEM; old = current_cred(); retval = -EPERM; if (!nsown_capable(CAP_SETGID)) { if (rgid != (gid_t) -1 && !gid_eq(krgid, old->gid) && !gid_eq(krgid, old->egid) && !gid_eq(krgid, old->sgid)) goto error; if (egid != (gid_t) -1 && !gid_eq(kegid, old->gid) && !gid_eq(kegid, old->egid) && !gid_eq(kegid, old->sgid)) goto error; if (sgid != (gid_t) -1 && !gid_eq(ksgid, old->gid) && !gid_eq(ksgid, old->egid) && !gid_eq(ksgid, old->sgid)) goto error; } if (rgid != (gid_t) -1) new->gid = krgid; if (egid != (gid_t) -1) new->egid = kegid; if (sgid != (gid_t) -1) new->sgid = ksgid; new->fsgid = new->egid; return commit_creds(new); error: abort_creds(new); return retval; } SYSCALL_DEFINE3(getresgid, gid_t __user *, rgidp, gid_t __user *, egidp, gid_t __user *, sgidp) { const struct cred *cred = current_cred(); int retval; gid_t rgid, egid, sgid; rgid = from_kgid_munged(cred->user_ns, cred->gid); egid = from_kgid_munged(cred->user_ns, cred->egid); sgid = from_kgid_munged(cred->user_ns, cred->sgid); if (!(retval = put_user(rgid, rgidp)) && !(retval = put_user(egid, egidp))) retval = put_user(sgid, sgidp); return retval; } /* * "setfsuid()" sets the fsuid - the uid used for filesystem checks. This * is used for "access()" and for the NFS daemon (letting nfsd stay at * whatever uid it wants to). It normally shadows "euid", except when * explicitly set by setfsuid() or for access.. */ SYSCALL_DEFINE1(setfsuid, uid_t, uid) { const struct cred *old; struct cred *new; uid_t old_fsuid; kuid_t kuid; old = current_cred(); old_fsuid = from_kuid_munged(old->user_ns, old->fsuid); kuid = make_kuid(old->user_ns, uid); if (!uid_valid(kuid)) return old_fsuid; new = prepare_creds(); if (!new) return old_fsuid; if (uid_eq(kuid, old->uid) || uid_eq(kuid, old->euid) || uid_eq(kuid, old->suid) || uid_eq(kuid, old->fsuid) || nsown_capable(CAP_SETUID)) { if (!uid_eq(kuid, old->fsuid)) { new->fsuid = kuid; if (security_task_fix_setuid(new, old, LSM_SETID_FS) == 0) goto change_okay; } } abort_creds(new); return old_fsuid; change_okay: commit_creds(new); return old_fsuid; } /* * Samma på svenska.. */ SYSCALL_DEFINE1(setfsgid, gid_t, gid) { const struct cred *old; struct cred *new; gid_t old_fsgid; kgid_t kgid; old = current_cred(); old_fsgid = from_kgid_munged(old->user_ns, old->fsgid); kgid = make_kgid(old->user_ns, gid); if (!gid_valid(kgid)) return old_fsgid; new = prepare_creds(); if (!new) return old_fsgid; if (gid_eq(kgid, old->gid) || gid_eq(kgid, old->egid) || gid_eq(kgid, old->sgid) || gid_eq(kgid, old->fsgid) || nsown_capable(CAP_SETGID)) { if (!gid_eq(kgid, old->fsgid)) { new->fsgid = kgid; goto change_okay; } } abort_creds(new); return old_fsgid; change_okay: commit_creds(new); return old_fsgid; } void do_sys_times(struct tms *tms) { cputime_t tgutime, tgstime, cutime, cstime; spin_lock_irq(&current->sighand->siglock); thread_group_times(current, &tgutime, &tgstime); cutime = current->signal->cutime; cstime = current->signal->cstime; spin_unlock_irq(&current->sighand->siglock); tms->tms_utime = cputime_to_clock_t(tgutime); tms->tms_stime = cputime_to_clock_t(tgstime); tms->tms_cutime = cputime_to_clock_t(cutime); tms->tms_cstime = cputime_to_clock_t(cstime); } SYSCALL_DEFINE1(times, struct tms __user *, tbuf) { if (tbuf) { struct tms tmp; do_sys_times(&tmp); if (copy_to_user(tbuf, &tmp, sizeof(struct tms))) return -EFAULT; } force_successful_syscall_return(); return (long) jiffies_64_to_clock_t(get_jiffies_64()); } /* * This needs some heavy checking ... * I just haven't the stomach for it. I also don't fully * understand sessions/pgrp etc. Let somebody who does explain it. * * OK, I think I have the protection semantics right.... this is really * only important on a multi-user system anyway, to make sure one user * can't send a signal to a process owned by another. -TYT, 12/12/91 * * Auch. Had to add the 'did_exec' flag to conform completely to POSIX. * LBT 04.03.94 */ SYSCALL_DEFINE2(setpgid, pid_t, pid, pid_t, pgid) { struct task_struct *p; struct task_struct *group_leader = current->group_leader; struct pid *pgrp; int err; if (!pid) pid = task_pid_vnr(group_leader); if (!pgid) pgid = pid; if (pgid < 0) return -EINVAL; rcu_read_lock(); /* From this point forward we keep holding onto the tasklist lock * so that our parent does not change from under us. -DaveM */ write_lock_irq(&tasklist_lock); err = -ESRCH; p = find_task_by_vpid(pid); if (!p) goto out; err = -EINVAL; if (!thread_group_leader(p)) goto out; if (same_thread_group(p->real_parent, group_leader)) { err = -EPERM; if (task_session(p) != task_session(group_leader)) goto out; err = -EACCES; if (p->did_exec) goto out; } else { err = -ESRCH; if (p != group_leader) goto out; } err = -EPERM; if (p->signal->leader) goto out; pgrp = task_pid(p); if (pgid != pid) { struct task_struct *g; pgrp = find_vpid(pgid); g = pid_task(pgrp, PIDTYPE_PGID); if (!g || task_session(g) != task_session(group_leader)) goto out; } err = security_task_setpgid(p, pgid); if (err) goto out; if (task_pgrp(p) != pgrp) change_pid(p, PIDTYPE_PGID, pgrp); err = 0; out: /* All paths lead to here, thus we are safe. -DaveM */ write_unlock_irq(&tasklist_lock); rcu_read_unlock(); return err; } SYSCALL_DEFINE1(getpgid, pid_t, pid) { struct task_struct *p; struct pid *grp; int retval; rcu_read_lock(); if (!pid) grp = task_pgrp(current); else { retval = -ESRCH; p = find_task_by_vpid(pid); if (!p) goto out; grp = task_pgrp(p); if (!grp) goto out; retval = security_task_getpgid(p); if (retval) goto out; } retval = pid_vnr(grp); out: rcu_read_unlock(); return retval; } #ifdef __ARCH_WANT_SYS_GETPGRP SYSCALL_DEFINE0(getpgrp) { return sys_getpgid(0); } #endif SYSCALL_DEFINE1(getsid, pid_t, pid) { struct task_struct *p; struct pid *sid; int retval; rcu_read_lock(); if (!pid) sid = task_session(current); else { retval = -ESRCH; p = find_task_by_vpid(pid); if (!p) goto out; sid = task_session(p); if (!sid) goto out; retval = security_task_getsid(p); if (retval) goto out; } retval = pid_vnr(sid); out: rcu_read_unlock(); return retval; } SYSCALL_DEFINE0(setsid) { struct task_struct *group_leader = current->group_leader; struct pid *sid = task_pid(group_leader); pid_t session = pid_vnr(sid); int err = -EPERM; write_lock_irq(&tasklist_lock); /* Fail if I am already a session leader */ if (group_leader->signal->leader) goto out; /* Fail if a process group id already exists that equals the * proposed session id. */ if (pid_task(sid, PIDTYPE_PGID)) goto out; group_leader->signal->leader = 1; __set_special_pids(sid); proc_clear_tty(group_leader); err = session; out: write_unlock_irq(&tasklist_lock); if (err > 0) { proc_sid_connector(group_leader); sched_autogroup_create_attach(group_leader); } return err; } DECLARE_RWSEM(uts_sem); #ifdef COMPAT_UTS_MACHINE #define override_architecture(name) \ (personality(current->personality) == PER_LINUX32 && \ copy_to_user(name->machine, COMPAT_UTS_MACHINE, \ sizeof(COMPAT_UTS_MACHINE))) #else #define override_architecture(name) 0 #endif /* * Work around broken programs that cannot handle "Linux 3.0". * Instead we map 3.x to 2.6.40+x, so e.g. 3.0 would be 2.6.40 */ static int override_release(char __user *release, size_t len) { int ret = 0; if (current->personality & UNAME26) { const char *rest = UTS_RELEASE; char buf[65] = { 0 }; int ndots = 0; unsigned v; size_t copy; while (*rest) { if (*rest == '.' && ++ndots >= 3) break; if (!isdigit(*rest) && *rest != '.') break; rest++; } v = ((LINUX_VERSION_CODE >> 8) & 0xff) + 40; copy = min(sizeof(buf), max_t(size_t, 1, len)); copy = scnprintf(buf, copy, "2.6.%u%s", v, rest); ret = copy_to_user(release, buf, copy + 1); } return ret; } SYSCALL_DEFINE1(newuname, struct new_utsname __user *, name) { int errno = 0; down_read(&uts_sem); if (copy_to_user(name, utsname(), sizeof *name)) errno = -EFAULT; up_read(&uts_sem); if (!errno && override_release(name->release, sizeof(name->release))) errno = -EFAULT; if (!errno && override_architecture(name)) errno = -EFAULT; return errno; } #ifdef __ARCH_WANT_SYS_OLD_UNAME /* * Old cruft */ SYSCALL_DEFINE1(uname, struct old_utsname __user *, name) { int error = 0; if (!name) return -EFAULT; down_read(&uts_sem); if (copy_to_user(name, utsname(), sizeof(*name))) error = -EFAULT; up_read(&uts_sem); if (!error && override_release(name->release, sizeof(name->release))) error = -EFAULT; if (!error && override_architecture(name)) error = -EFAULT; return error; } SYSCALL_DEFINE1(olduname, struct oldold_utsname __user *, name) { int error; if (!name) return -EFAULT; if (!access_ok(VERIFY_WRITE, name, sizeof(struct oldold_utsname))) return -EFAULT; down_read(&uts_sem); error = __copy_to_user(&name->sysname, &utsname()->sysname, __OLD_UTS_LEN); error |= __put_user(0, name->sysname + __OLD_UTS_LEN); error |= __copy_to_user(&name->nodename, &utsname()->nodename, __OLD_UTS_LEN); error |= __put_user(0, name->nodename + __OLD_UTS_LEN); error |= __copy_to_user(&name->release, &utsname()->release, __OLD_UTS_LEN); error |= __put_user(0, name->release + __OLD_UTS_LEN); error |= __copy_to_user(&name->version, &utsname()->version, __OLD_UTS_LEN); error |= __put_user(0, name->version + __OLD_UTS_LEN); error |= __copy_to_user(&name->machine, &utsname()->machine, __OLD_UTS_LEN); error |= __put_user(0, name->machine + __OLD_UTS_LEN); up_read(&uts_sem); if (!error && override_architecture(name)) error = -EFAULT; if (!error && override_release(name->release, sizeof(name->release))) error = -EFAULT; return error ? -EFAULT : 0; } #endif SYSCALL_DEFINE2(sethostname, char __user *, name, int, len) { int errno; char tmp[__NEW_UTS_LEN]; if (!ns_capable(current->nsproxy->uts_ns->user_ns, CAP_SYS_ADMIN)) return -EPERM; if (len < 0 || len > __NEW_UTS_LEN) return -EINVAL; down_write(&uts_sem); errno = -EFAULT; if (!copy_from_user(tmp, name, len)) { struct new_utsname *u = utsname(); memcpy(u->nodename, tmp, len); memset(u->nodename + len, 0, sizeof(u->nodename) - len); errno = 0; uts_proc_notify(UTS_PROC_HOSTNAME); } up_write(&uts_sem); return errno; } #ifdef __ARCH_WANT_SYS_GETHOSTNAME SYSCALL_DEFINE2(gethostname, char __user *, name, int, len) { int i, errno; struct new_utsname *u; if (len < 0) return -EINVAL; down_read(&uts_sem); u = utsname(); i = 1 + strlen(u->nodename); if (i > len) i = len; errno = 0; if (copy_to_user(name, u->nodename, i)) errno = -EFAULT; up_read(&uts_sem); return errno; } #endif /* * Only setdomainname; getdomainname can be implemented by calling * uname() */ SYSCALL_DEFINE2(setdomainname, char __user *, name, int, len) { int errno; char tmp[__NEW_UTS_LEN]; if (!ns_capable(current->nsproxy->uts_ns->user_ns, CAP_SYS_ADMIN)) return -EPERM; if (len < 0 || len > __NEW_UTS_LEN) return -EINVAL; down_write(&uts_sem); errno = -EFAULT; if (!copy_from_user(tmp, name, len)) { struct new_utsname *u = utsname(); memcpy(u->domainname, tmp, len); memset(u->domainname + len, 0, sizeof(u->domainname) - len); errno = 0; uts_proc_notify(UTS_PROC_DOMAINNAME); } up_write(&uts_sem); return errno; } SYSCALL_DEFINE2(getrlimit, unsigned int, resource, struct rlimit __user *, rlim) { struct rlimit value; int ret; ret = do_prlimit(current, resource, NULL, &value); if (!ret) ret = copy_to_user(rlim, &value, sizeof(*rlim)) ? -EFAULT : 0; return ret; } #ifdef __ARCH_WANT_SYS_OLD_GETRLIMIT /* * Back compatibility for getrlimit. Needed for some apps. */ SYSCALL_DEFINE2(old_getrlimit, unsigned int, resource, struct rlimit __user *, rlim) { struct rlimit x; if (resource >= RLIM_NLIMITS) return -EINVAL; task_lock(current->group_leader); x = current->signal->rlim[resource]; task_unlock(current->group_leader); if (x.rlim_cur > 0x7FFFFFFF) x.rlim_cur = 0x7FFFFFFF; if (x.rlim_max > 0x7FFFFFFF) x.rlim_max = 0x7FFFFFFF; return copy_to_user(rlim, &x, sizeof(x))?-EFAULT:0; } #endif static inline bool rlim64_is_infinity(__u64 rlim64) { #if BITS_PER_LONG < 64 return rlim64 >= ULONG_MAX; #else return rlim64 == RLIM64_INFINITY; #endif } static void rlim_to_rlim64(const struct rlimit *rlim, struct rlimit64 *rlim64) { if (rlim->rlim_cur == RLIM_INFINITY) rlim64->rlim_cur = RLIM64_INFINITY; else rlim64->rlim_cur = rlim->rlim_cur; if (rlim->rlim_max == RLIM_INFINITY) rlim64->rlim_max = RLIM64_INFINITY; else rlim64->rlim_max = rlim->rlim_max; } static void rlim64_to_rlim(const struct rlimit64 *rlim64, struct rlimit *rlim) { if (rlim64_is_infinity(rlim64->rlim_cur)) rlim->rlim_cur = RLIM_INFINITY; else rlim->rlim_cur = (unsigned long)rlim64->rlim_cur; if (rlim64_is_infinity(rlim64->rlim_max)) rlim->rlim_max = RLIM_INFINITY; else rlim->rlim_max = (unsigned long)rlim64->rlim_max; } /* make sure you are allowed to change @tsk limits before calling this */ int do_prlimit(struct task_struct *tsk, unsigned int resource, struct rlimit *new_rlim, struct rlimit *old_rlim) { struct rlimit *rlim; int retval = 0; if (resource >= RLIM_NLIMITS) return -EINVAL; if (new_rlim) { if (new_rlim->rlim_cur > new_rlim->rlim_max) return -EINVAL; if (resource == RLIMIT_NOFILE && new_rlim->rlim_max > sysctl_nr_open) return -EPERM; } /* protect tsk->signal and tsk->sighand from disappearing */ read_lock(&tasklist_lock); if (!tsk->sighand) { retval = -ESRCH; goto out; } rlim = tsk->signal->rlim + resource; task_lock(tsk->group_leader); if (new_rlim) { /* Keep the capable check against init_user_ns until cgroups can contain all limits */ if (new_rlim->rlim_max > rlim->rlim_max && !capable(CAP_SYS_RESOURCE)) retval = -EPERM; if (!retval) retval = security_task_setrlimit(tsk->group_leader, resource, new_rlim); if (resource == RLIMIT_CPU && new_rlim->rlim_cur == 0) { /* * The caller is asking for an immediate RLIMIT_CPU * expiry. But we use the zero value to mean "it was * never set". So let's cheat and make it one second * instead */ new_rlim->rlim_cur = 1; } } if (!retval) { if (old_rlim) *old_rlim = *rlim; if (new_rlim) *rlim = *new_rlim; } task_unlock(tsk->group_leader); /* * RLIMIT_CPU handling. Note that the kernel fails to return an error * code if it rejected the user's attempt to set RLIMIT_CPU. This is a * very long-standing error, and fixing it now risks breakage of * applications, so we live with it */ if (!retval && new_rlim && resource == RLIMIT_CPU && new_rlim->rlim_cur != RLIM_INFINITY) update_rlimit_cpu(tsk, new_rlim->rlim_cur); out: read_unlock(&tasklist_lock); return retval; } /* rcu lock must be held */ static int check_prlimit_permission(struct task_struct *task) { const struct cred *cred = current_cred(), *tcred; if (current == task) return 0; tcred = __task_cred(task); if (uid_eq(cred->uid, tcred->euid) && uid_eq(cred->uid, tcred->suid) && uid_eq(cred->uid, tcred->uid) && gid_eq(cred->gid, tcred->egid) && gid_eq(cred->gid, tcred->sgid) && gid_eq(cred->gid, tcred->gid)) return 0; if (ns_capable(tcred->user_ns, CAP_SYS_RESOURCE)) return 0; return -EPERM; } SYSCALL_DEFINE4(prlimit64, pid_t, pid, unsigned int, resource, const struct rlimit64 __user *, new_rlim, struct rlimit64 __user *, old_rlim) { struct rlimit64 old64, new64; struct rlimit old, new; struct task_struct *tsk; int ret; if (new_rlim) { if (copy_from_user(&new64, new_rlim, sizeof(new64))) return -EFAULT; rlim64_to_rlim(&new64, &new); } rcu_read_lock(); tsk = pid ? find_task_by_vpid(pid) : current; if (!tsk) { rcu_read_unlock(); return -ESRCH; } ret = check_prlimit_permission(tsk); if (ret) { rcu_read_unlock(); return ret; } get_task_struct(tsk); rcu_read_unlock(); ret = do_prlimit(tsk, resource, new_rlim ? &new : NULL, old_rlim ? &old : NULL); if (!ret && old_rlim) { rlim_to_rlim64(&old, &old64); if (copy_to_user(old_rlim, &old64, sizeof(old64))) ret = -EFAULT; } put_task_struct(tsk); return ret; } SYSCALL_DEFINE2(setrlimit, unsigned int, resource, struct rlimit __user *, rlim) { struct rlimit new_rlim; if (copy_from_user(&new_rlim, rlim, sizeof(*rlim))) return -EFAULT; return do_prlimit(current, resource, &new_rlim, NULL); } /* * It would make sense to put struct rusage in the task_struct, * except that would make the task_struct be *really big*. After * task_struct gets moved into malloc'ed memory, it would * make sense to do this. It will make moving the rest of the information * a lot simpler! (Which we're not doing right now because we're not * measuring them yet). * * When sampling multiple threads for RUSAGE_SELF, under SMP we might have * races with threads incrementing their own counters. But since word * reads are atomic, we either get new values or old values and we don't * care which for the sums. We always take the siglock to protect reading * the c* fields from p->signal from races with exit.c updating those * fields when reaping, so a sample either gets all the additions of a * given child after it's reaped, or none so this sample is before reaping. * * Locking: * We need to take the siglock for CHILDEREN, SELF and BOTH * for the cases current multithreaded, non-current single threaded * non-current multithreaded. Thread traversal is now safe with * the siglock held. * Strictly speaking, we donot need to take the siglock if we are current and * single threaded, as no one else can take our signal_struct away, no one * else can reap the children to update signal->c* counters, and no one else * can race with the signal-> fields. If we do not take any lock, the * signal-> fields could be read out of order while another thread was just * exiting. So we should place a read memory barrier when we avoid the lock. * On the writer side, write memory barrier is implied in __exit_signal * as __exit_signal releases the siglock spinlock after updating the signal-> * fields. But we don't do this yet to keep things simple. * */ static void accumulate_thread_rusage(struct task_struct *t, struct rusage *r) { r->ru_nvcsw += t->nvcsw; r->ru_nivcsw += t->nivcsw; r->ru_minflt += t->min_flt; r->ru_majflt += t->maj_flt; r->ru_inblock += task_io_get_inblock(t); r->ru_oublock += task_io_get_oublock(t); } static void k_getrusage(struct task_struct *p, int who, struct rusage *r) { struct task_struct *t; unsigned long flags; cputime_t tgutime, tgstime, utime, stime; unsigned long maxrss = 0; memset((char *) r, 0, sizeof *r); utime = stime = 0; if (who == RUSAGE_THREAD) { task_times(current, &utime, &stime); accumulate_thread_rusage(p, r); maxrss = p->signal->maxrss; goto out; } if (!lock_task_sighand(p, &flags)) return; switch (who) { case RUSAGE_BOTH: case RUSAGE_CHILDREN: utime = p->signal->cutime; stime = p->signal->cstime; r->ru_nvcsw = p->signal->cnvcsw; r->ru_nivcsw = p->signal->cnivcsw; r->ru_minflt = p->signal->cmin_flt; r->ru_majflt = p->signal->cmaj_flt; r->ru_inblock = p->signal->cinblock; r->ru_oublock = p->signal->coublock; maxrss = p->signal->cmaxrss; if (who == RUSAGE_CHILDREN) break; case RUSAGE_SELF: thread_group_times(p, &tgutime, &tgstime); utime += tgutime; stime += tgstime; r->ru_nvcsw += p->signal->nvcsw; r->ru_nivcsw += p->signal->nivcsw; r->ru_minflt += p->signal->min_flt; r->ru_majflt += p->signal->maj_flt; r->ru_inblock += p->signal->inblock; r->ru_oublock += p->signal->oublock; if (maxrss < p->signal->maxrss) maxrss = p->signal->maxrss; t = p; do { accumulate_thread_rusage(t, r); t = next_thread(t); } while (t != p); break; default: BUG(); } unlock_task_sighand(p, &flags); out: cputime_to_timeval(utime, &r->ru_utime); cputime_to_timeval(stime, &r->ru_stime); if (who != RUSAGE_CHILDREN) { struct mm_struct *mm = get_task_mm(p); if (mm) { setmax_mm_hiwater_rss(&maxrss, mm); mmput(mm); } } r->ru_maxrss = maxrss * (PAGE_SIZE / 1024); /* convert pages to KBs */ } int getrusage(struct task_struct *p, int who, struct rusage __user *ru) { struct rusage r; k_getrusage(p, who, &r); return copy_to_user(ru, &r, sizeof(r)) ? -EFAULT : 0; } SYSCALL_DEFINE2(getrusage, int, who, struct rusage __user *, ru) { if (who != RUSAGE_SELF && who != RUSAGE_CHILDREN && who != RUSAGE_THREAD) return -EINVAL; return getrusage(current, who, ru); } SYSCALL_DEFINE1(umask, int, mask) { mask = xchg(&current->fs->umask, mask & S_IRWXUGO); return mask; } #ifdef CONFIG_CHECKPOINT_RESTORE static int prctl_set_mm_exe_file(struct mm_struct *mm, unsigned int fd) { struct fd exe; struct dentry *dentry; int err; exe = fdget(fd); if (!exe.file) return -EBADF; dentry = exe.file->f_path.dentry; /* * Because the original mm->exe_file points to executable file, make * sure that this one is executable as well, to avoid breaking an * overall picture. */ err = -EACCES; if (!S_ISREG(dentry->d_inode->i_mode) || exe.file->f_path.mnt->mnt_flags & MNT_NOEXEC) goto exit; err = inode_permission(dentry->d_inode, MAY_EXEC); if (err) goto exit; down_write(&mm->mmap_sem); /* * Forbid mm->exe_file change if old file still mapped. */ err = -EBUSY; if (mm->exe_file) { struct vm_area_struct *vma; for (vma = mm->mmap; vma; vma = vma->vm_next) if (vma->vm_file && path_equal(&vma->vm_file->f_path, &mm->exe_file->f_path)) goto exit_unlock; } /* * The symlink can be changed only once, just to disallow arbitrary * transitions malicious software might bring in. This means one * could make a snapshot over all processes running and monitor * /proc/pid/exe changes to notice unusual activity if needed. */ err = -EPERM; if (test_and_set_bit(MMF_EXE_FILE_CHANGED, &mm->flags)) goto exit_unlock; err = 0; set_mm_exe_file(mm, exe.file); /* this grabs a reference to exe.file */ exit_unlock: up_write(&mm->mmap_sem); exit: fdput(exe); return err; } static int prctl_set_mm(int opt, unsigned long addr, unsigned long arg4, unsigned long arg5) { unsigned long rlim = rlimit(RLIMIT_DATA); struct mm_struct *mm = current->mm; struct vm_area_struct *vma; int error; if (arg5 || (arg4 && opt != PR_SET_MM_AUXV)) return -EINVAL; if (!capable(CAP_SYS_RESOURCE)) return -EPERM; if (opt == PR_SET_MM_EXE_FILE) return prctl_set_mm_exe_file(mm, (unsigned int)addr); if (addr >= TASK_SIZE || addr < mmap_min_addr) return -EINVAL; error = -EINVAL; down_read(&mm->mmap_sem); vma = find_vma(mm, addr); switch (opt) { case PR_SET_MM_START_CODE: mm->start_code = addr; break; case PR_SET_MM_END_CODE: mm->end_code = addr; break; case PR_SET_MM_START_DATA: mm->start_data = addr; break; case PR_SET_MM_END_DATA: mm->end_data = addr; break; case PR_SET_MM_START_BRK: if (addr <= mm->end_data) goto out; if (rlim < RLIM_INFINITY && (mm->brk - addr) + (mm->end_data - mm->start_data) > rlim) goto out; mm->start_brk = addr; break; case PR_SET_MM_BRK: if (addr <= mm->end_data) goto out; if (rlim < RLIM_INFINITY && (addr - mm->start_brk) + (mm->end_data - mm->start_data) > rlim) goto out; mm->brk = addr; break; /* * If command line arguments and environment * are placed somewhere else on stack, we can * set them up here, ARG_START/END to setup * command line argumets and ENV_START/END * for environment. */ case PR_SET_MM_START_STACK: case PR_SET_MM_ARG_START: case PR_SET_MM_ARG_END: case PR_SET_MM_ENV_START: case PR_SET_MM_ENV_END: if (!vma) { error = -EFAULT; goto out; } if (opt == PR_SET_MM_START_STACK) mm->start_stack = addr; else if (opt == PR_SET_MM_ARG_START) mm->arg_start = addr; else if (opt == PR_SET_MM_ARG_END) mm->arg_end = addr; else if (opt == PR_SET_MM_ENV_START) mm->env_start = addr; else if (opt == PR_SET_MM_ENV_END) mm->env_end = addr; break; /* * This doesn't move auxiliary vector itself * since it's pinned to mm_struct, but allow * to fill vector with new values. It's up * to a caller to provide sane values here * otherwise user space tools which use this * vector might be unhappy. */ case PR_SET_MM_AUXV: { unsigned long user_auxv[AT_VECTOR_SIZE]; if (arg4 > sizeof(user_auxv)) goto out; up_read(&mm->mmap_sem); if (copy_from_user(user_auxv, (const void __user *)addr, arg4)) return -EFAULT; /* Make sure the last entry is always AT_NULL */ user_auxv[AT_VECTOR_SIZE - 2] = 0; user_auxv[AT_VECTOR_SIZE - 1] = 0; BUILD_BUG_ON(sizeof(user_auxv) != sizeof(mm->saved_auxv)); task_lock(current); memcpy(mm->saved_auxv, user_auxv, arg4); task_unlock(current); return 0; } default: goto out; } error = 0; out: up_read(&mm->mmap_sem); return error; } static int prctl_get_tid_address(struct task_struct *me, int __user **tid_addr) { return put_user(me->clear_child_tid, tid_addr); } #else /* CONFIG_CHECKPOINT_RESTORE */ static int prctl_set_mm(int opt, unsigned long addr, unsigned long arg4, unsigned long arg5) { return -EINVAL; } static int prctl_get_tid_address(struct task_struct *me, int __user **tid_addr) { return -EINVAL; } #endif SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3, unsigned long, arg4, unsigned long, arg5) { struct task_struct *me = current; unsigned char comm[sizeof(me->comm)]; long error; error = security_task_prctl(option, arg2, arg3, arg4, arg5); if (error != -ENOSYS) return error; error = 0; switch (option) { case PR_SET_PDEATHSIG: if (!valid_signal(arg2)) { error = -EINVAL; break; } me->pdeath_signal = arg2; break; case PR_GET_PDEATHSIG: error = put_user(me->pdeath_signal, (int __user *)arg2); break; case PR_GET_DUMPABLE: error = get_dumpable(me->mm); break; case PR_SET_DUMPABLE: if (arg2 < 0 || arg2 > 1) { error = -EINVAL; break; } set_dumpable(me->mm, arg2); break; case PR_SET_UNALIGN: error = SET_UNALIGN_CTL(me, arg2); break; case PR_GET_UNALIGN: error = GET_UNALIGN_CTL(me, arg2); break; case PR_SET_FPEMU: error = SET_FPEMU_CTL(me, arg2); break; case PR_GET_FPEMU: error = GET_FPEMU_CTL(me, arg2); break; case PR_SET_FPEXC: error = SET_FPEXC_CTL(me, arg2); break; case PR_GET_FPEXC: error = GET_FPEXC_CTL(me, arg2); break; case PR_GET_TIMING: error = PR_TIMING_STATISTICAL; break; case PR_SET_TIMING: if (arg2 != PR_TIMING_STATISTICAL) error = -EINVAL; break; case PR_SET_NAME: comm[sizeof(me->comm)-1] = 0; if (strncpy_from_user(comm, (char __user *)arg2, sizeof(me->comm) - 1) < 0) return -EFAULT; set_task_comm(me, comm); proc_comm_connector(me); break; case PR_GET_NAME: get_task_comm(comm, me); if (copy_to_user((char __user *)arg2, comm, sizeof(comm))) return -EFAULT; break; case PR_GET_ENDIAN: error = GET_ENDIAN(me, arg2); break; case PR_SET_ENDIAN: error = SET_ENDIAN(me, arg2); break; case PR_GET_SECCOMP: error = prctl_get_seccomp(); break; case PR_SET_SECCOMP: error = prctl_set_seccomp(arg2, (char __user *)arg3); break; case PR_GET_TSC: error = GET_TSC_CTL(arg2); break; case PR_SET_TSC: error = SET_TSC_CTL(arg2); break; case PR_TASK_PERF_EVENTS_DISABLE: error = perf_event_task_disable(); break; case PR_TASK_PERF_EVENTS_ENABLE: error = perf_event_task_enable(); break; case PR_GET_TIMERSLACK: error = current->timer_slack_ns; break; case PR_SET_TIMERSLACK: if (arg2 <= 0) current->timer_slack_ns = current->default_timer_slack_ns; else current->timer_slack_ns = arg2; break; case PR_MCE_KILL: if (arg4 | arg5) return -EINVAL; switch (arg2) { case PR_MCE_KILL_CLEAR: if (arg3 != 0) return -EINVAL; current->flags &= ~PF_MCE_PROCESS; break; case PR_MCE_KILL_SET: current->flags |= PF_MCE_PROCESS; if (arg3 == PR_MCE_KILL_EARLY) current->flags |= PF_MCE_EARLY; else if (arg3 == PR_MCE_KILL_LATE) current->flags &= ~PF_MCE_EARLY; else if (arg3 == PR_MCE_KILL_DEFAULT) current->flags &= ~(PF_MCE_EARLY|PF_MCE_PROCESS); else return -EINVAL; break; default: return -EINVAL; } break; case PR_MCE_KILL_GET: if (arg2 | arg3 | arg4 | arg5) return -EINVAL; if (current->flags & PF_MCE_PROCESS) error = (current->flags & PF_MCE_EARLY) ? PR_MCE_KILL_EARLY : PR_MCE_KILL_LATE; else error = PR_MCE_KILL_DEFAULT; break; case PR_SET_MM: error = prctl_set_mm(arg2, arg3, arg4, arg5); break; case PR_GET_TID_ADDRESS: error = prctl_get_tid_address(me, (int __user **)arg2); break; case PR_SET_CHILD_SUBREAPER: me->signal->is_child_subreaper = !!arg2; break; case PR_GET_CHILD_SUBREAPER: error = put_user(me->signal->is_child_subreaper, (int __user *) arg2); break; case PR_SET_NO_NEW_PRIVS: if (arg2 != 1 || arg3 || arg4 || arg5) return -EINVAL; current->no_new_privs = 1; break; case PR_GET_NO_NEW_PRIVS: if (arg2 || arg3 || arg4 || arg5) return -EINVAL; return current->no_new_privs ? 1 : 0; default: error = -EINVAL; break; } return error; } SYSCALL_DEFINE3(getcpu, unsigned __user *, cpup, unsigned __user *, nodep, struct getcpu_cache __user *, unused) { int err = 0; int cpu = raw_smp_processor_id(); if (cpup) err |= put_user(cpu, cpup); if (nodep) err |= put_user(cpu_to_node(cpu), nodep); return err ? -EFAULT : 0; } char poweroff_cmd[POWEROFF_CMD_PATH_LEN] = "/sbin/poweroff"; static void argv_cleanup(struct subprocess_info *info) { argv_free(info->argv); } static int __orderly_poweroff(void) { int argc; char **argv; static char *envp[] = { "HOME=/", "PATH=/sbin:/bin:/usr/sbin:/usr/bin", NULL }; int ret; argv = argv_split(GFP_ATOMIC, poweroff_cmd, &argc); if (argv == NULL) { printk(KERN_WARNING "%s failed to allocate memory for \"%s\"\n", __func__, poweroff_cmd); return -ENOMEM; } ret = call_usermodehelper_fns(argv[0], argv, envp, UMH_WAIT_EXEC, NULL, argv_cleanup, NULL); if (ret == -ENOMEM) argv_free(argv); return ret; } /** * orderly_poweroff - Trigger an orderly system poweroff * @force: force poweroff if command execution fails * * This may be called from any context to trigger a system shutdown. * If the orderly shutdown fails, it will force an immediate shutdown. */ int orderly_poweroff(bool force) { int ret = __orderly_poweroff(); if (ret && force) { printk(KERN_WARNING "Failed to start orderly shutdown: " "forcing the issue\n"); /* * I guess this should try to kick off some daemon to sync and * poweroff asap. Or not even bother syncing if we're doing an * emergency shutdown? */ emergency_sync(); kernel_power_off(); } return ret; } EXPORT_SYMBOL_GPL(orderly_poweroff);
./CrossVul/dataset_final_sorted/CWE-16/c/good_3582_0
crossvul-cpp_data_bad_3582_0
/* * linux/kernel/sys.c * * Copyright (C) 1991, 1992 Linus Torvalds */ #include <linux/export.h> #include <linux/mm.h> #include <linux/utsname.h> #include <linux/mman.h> #include <linux/reboot.h> #include <linux/prctl.h> #include <linux/highuid.h> #include <linux/fs.h> #include <linux/kmod.h> #include <linux/perf_event.h> #include <linux/resource.h> #include <linux/kernel.h> #include <linux/kexec.h> #include <linux/workqueue.h> #include <linux/capability.h> #include <linux/device.h> #include <linux/key.h> #include <linux/times.h> #include <linux/posix-timers.h> #include <linux/security.h> #include <linux/dcookies.h> #include <linux/suspend.h> #include <linux/tty.h> #include <linux/signal.h> #include <linux/cn_proc.h> #include <linux/getcpu.h> #include <linux/task_io_accounting_ops.h> #include <linux/seccomp.h> #include <linux/cpu.h> #include <linux/personality.h> #include <linux/ptrace.h> #include <linux/fs_struct.h> #include <linux/file.h> #include <linux/mount.h> #include <linux/gfp.h> #include <linux/syscore_ops.h> #include <linux/version.h> #include <linux/ctype.h> #include <linux/compat.h> #include <linux/syscalls.h> #include <linux/kprobes.h> #include <linux/user_namespace.h> #include <linux/kmsg_dump.h> /* Move somewhere else to avoid recompiling? */ #include <generated/utsrelease.h> #include <asm/uaccess.h> #include <asm/io.h> #include <asm/unistd.h> #ifndef SET_UNALIGN_CTL # define SET_UNALIGN_CTL(a,b) (-EINVAL) #endif #ifndef GET_UNALIGN_CTL # define GET_UNALIGN_CTL(a,b) (-EINVAL) #endif #ifndef SET_FPEMU_CTL # define SET_FPEMU_CTL(a,b) (-EINVAL) #endif #ifndef GET_FPEMU_CTL # define GET_FPEMU_CTL(a,b) (-EINVAL) #endif #ifndef SET_FPEXC_CTL # define SET_FPEXC_CTL(a,b) (-EINVAL) #endif #ifndef GET_FPEXC_CTL # define GET_FPEXC_CTL(a,b) (-EINVAL) #endif #ifndef GET_ENDIAN # define GET_ENDIAN(a,b) (-EINVAL) #endif #ifndef SET_ENDIAN # define SET_ENDIAN(a,b) (-EINVAL) #endif #ifndef GET_TSC_CTL # define GET_TSC_CTL(a) (-EINVAL) #endif #ifndef SET_TSC_CTL # define SET_TSC_CTL(a) (-EINVAL) #endif /* * this is where the system-wide overflow UID and GID are defined, for * architectures that now have 32-bit UID/GID but didn't in the past */ int overflowuid = DEFAULT_OVERFLOWUID; int overflowgid = DEFAULT_OVERFLOWGID; EXPORT_SYMBOL(overflowuid); EXPORT_SYMBOL(overflowgid); /* * the same as above, but for filesystems which can only store a 16-bit * UID and GID. as such, this is needed on all architectures */ int fs_overflowuid = DEFAULT_FS_OVERFLOWUID; int fs_overflowgid = DEFAULT_FS_OVERFLOWUID; EXPORT_SYMBOL(fs_overflowuid); EXPORT_SYMBOL(fs_overflowgid); /* * this indicates whether you can reboot with ctrl-alt-del: the default is yes */ int C_A_D = 1; struct pid *cad_pid; EXPORT_SYMBOL(cad_pid); /* * If set, this is used for preparing the system to power off. */ void (*pm_power_off_prepare)(void); /* * Returns true if current's euid is same as p's uid or euid, * or has CAP_SYS_NICE to p's user_ns. * * Called with rcu_read_lock, creds are safe */ static bool set_one_prio_perm(struct task_struct *p) { const struct cred *cred = current_cred(), *pcred = __task_cred(p); if (uid_eq(pcred->uid, cred->euid) || uid_eq(pcred->euid, cred->euid)) return true; if (ns_capable(pcred->user_ns, CAP_SYS_NICE)) return true; return false; } /* * set the priority of a task * - the caller must hold the RCU read lock */ static int set_one_prio(struct task_struct *p, int niceval, int error) { int no_nice; if (!set_one_prio_perm(p)) { error = -EPERM; goto out; } if (niceval < task_nice(p) && !can_nice(p, niceval)) { error = -EACCES; goto out; } no_nice = security_task_setnice(p, niceval); if (no_nice) { error = no_nice; goto out; } if (error == -ESRCH) error = 0; set_user_nice(p, niceval); out: return error; } SYSCALL_DEFINE3(setpriority, int, which, int, who, int, niceval) { struct task_struct *g, *p; struct user_struct *user; const struct cred *cred = current_cred(); int error = -EINVAL; struct pid *pgrp; kuid_t uid; if (which > PRIO_USER || which < PRIO_PROCESS) goto out; /* normalize: avoid signed division (rounding problems) */ error = -ESRCH; if (niceval < -20) niceval = -20; if (niceval > 19) niceval = 19; rcu_read_lock(); read_lock(&tasklist_lock); switch (which) { case PRIO_PROCESS: if (who) p = find_task_by_vpid(who); else p = current; if (p) error = set_one_prio(p, niceval, error); break; case PRIO_PGRP: if (who) pgrp = find_vpid(who); else pgrp = task_pgrp(current); do_each_pid_thread(pgrp, PIDTYPE_PGID, p) { error = set_one_prio(p, niceval, error); } while_each_pid_thread(pgrp, PIDTYPE_PGID, p); break; case PRIO_USER: uid = make_kuid(cred->user_ns, who); user = cred->user; if (!who) uid = cred->uid; else if (!uid_eq(uid, cred->uid) && !(user = find_user(uid))) goto out_unlock; /* No processes for this user */ do_each_thread(g, p) { if (uid_eq(task_uid(p), uid)) error = set_one_prio(p, niceval, error); } while_each_thread(g, p); if (!uid_eq(uid, cred->uid)) free_uid(user); /* For find_user() */ break; } out_unlock: read_unlock(&tasklist_lock); rcu_read_unlock(); out: return error; } /* * Ugh. To avoid negative return values, "getpriority()" will * not return the normal nice-value, but a negated value that * has been offset by 20 (ie it returns 40..1 instead of -20..19) * to stay compatible. */ SYSCALL_DEFINE2(getpriority, int, which, int, who) { struct task_struct *g, *p; struct user_struct *user; const struct cred *cred = current_cred(); long niceval, retval = -ESRCH; struct pid *pgrp; kuid_t uid; if (which > PRIO_USER || which < PRIO_PROCESS) return -EINVAL; rcu_read_lock(); read_lock(&tasklist_lock); switch (which) { case PRIO_PROCESS: if (who) p = find_task_by_vpid(who); else p = current; if (p) { niceval = 20 - task_nice(p); if (niceval > retval) retval = niceval; } break; case PRIO_PGRP: if (who) pgrp = find_vpid(who); else pgrp = task_pgrp(current); do_each_pid_thread(pgrp, PIDTYPE_PGID, p) { niceval = 20 - task_nice(p); if (niceval > retval) retval = niceval; } while_each_pid_thread(pgrp, PIDTYPE_PGID, p); break; case PRIO_USER: uid = make_kuid(cred->user_ns, who); user = cred->user; if (!who) uid = cred->uid; else if (!uid_eq(uid, cred->uid) && !(user = find_user(uid))) goto out_unlock; /* No processes for this user */ do_each_thread(g, p) { if (uid_eq(task_uid(p), uid)) { niceval = 20 - task_nice(p); if (niceval > retval) retval = niceval; } } while_each_thread(g, p); if (!uid_eq(uid, cred->uid)) free_uid(user); /* for find_user() */ break; } out_unlock: read_unlock(&tasklist_lock); rcu_read_unlock(); return retval; } /** * emergency_restart - reboot the system * * Without shutting down any hardware or taking any locks * reboot the system. This is called when we know we are in * trouble so this is our best effort to reboot. This is * safe to call in interrupt context. */ void emergency_restart(void) { kmsg_dump(KMSG_DUMP_EMERG); machine_emergency_restart(); } EXPORT_SYMBOL_GPL(emergency_restart); void kernel_restart_prepare(char *cmd) { blocking_notifier_call_chain(&reboot_notifier_list, SYS_RESTART, cmd); system_state = SYSTEM_RESTART; usermodehelper_disable(); device_shutdown(); syscore_shutdown(); } /** * register_reboot_notifier - Register function to be called at reboot time * @nb: Info about notifier function to be called * * Registers a function with the list of functions * to be called at reboot time. * * Currently always returns zero, as blocking_notifier_chain_register() * always returns zero. */ int register_reboot_notifier(struct notifier_block *nb) { return blocking_notifier_chain_register(&reboot_notifier_list, nb); } EXPORT_SYMBOL(register_reboot_notifier); /** * unregister_reboot_notifier - Unregister previously registered reboot notifier * @nb: Hook to be unregistered * * Unregisters a previously registered reboot * notifier function. * * Returns zero on success, or %-ENOENT on failure. */ int unregister_reboot_notifier(struct notifier_block *nb) { return blocking_notifier_chain_unregister(&reboot_notifier_list, nb); } EXPORT_SYMBOL(unregister_reboot_notifier); /** * kernel_restart - reboot the system * @cmd: pointer to buffer containing command to execute for restart * or %NULL * * Shutdown everything and perform a clean reboot. * This is not safe to call in interrupt context. */ void kernel_restart(char *cmd) { kernel_restart_prepare(cmd); disable_nonboot_cpus(); if (!cmd) printk(KERN_EMERG "Restarting system.\n"); else printk(KERN_EMERG "Restarting system with command '%s'.\n", cmd); kmsg_dump(KMSG_DUMP_RESTART); machine_restart(cmd); } EXPORT_SYMBOL_GPL(kernel_restart); static void kernel_shutdown_prepare(enum system_states state) { blocking_notifier_call_chain(&reboot_notifier_list, (state == SYSTEM_HALT)?SYS_HALT:SYS_POWER_OFF, NULL); system_state = state; usermodehelper_disable(); device_shutdown(); } /** * kernel_halt - halt the system * * Shutdown everything and perform a clean system halt. */ void kernel_halt(void) { kernel_shutdown_prepare(SYSTEM_HALT); syscore_shutdown(); printk(KERN_EMERG "System halted.\n"); kmsg_dump(KMSG_DUMP_HALT); machine_halt(); } EXPORT_SYMBOL_GPL(kernel_halt); /** * kernel_power_off - power_off the system * * Shutdown everything and perform a clean system power_off. */ void kernel_power_off(void) { kernel_shutdown_prepare(SYSTEM_POWER_OFF); if (pm_power_off_prepare) pm_power_off_prepare(); disable_nonboot_cpus(); syscore_shutdown(); printk(KERN_EMERG "Power down.\n"); kmsg_dump(KMSG_DUMP_POWEROFF); machine_power_off(); } EXPORT_SYMBOL_GPL(kernel_power_off); static DEFINE_MUTEX(reboot_mutex); /* * Reboot system call: for obvious reasons only root may call it, * and even root needs to set up some magic numbers in the registers * so that some mistake won't make this reboot the whole machine. * You can also set the meaning of the ctrl-alt-del-key here. * * reboot doesn't sync: do that yourself before calling this. */ SYSCALL_DEFINE4(reboot, int, magic1, int, magic2, unsigned int, cmd, void __user *, arg) { char buffer[256]; int ret = 0; /* We only trust the superuser with rebooting the system. */ if (!capable(CAP_SYS_BOOT)) return -EPERM; /* For safety, we require "magic" arguments. */ if (magic1 != LINUX_REBOOT_MAGIC1 || (magic2 != LINUX_REBOOT_MAGIC2 && magic2 != LINUX_REBOOT_MAGIC2A && magic2 != LINUX_REBOOT_MAGIC2B && magic2 != LINUX_REBOOT_MAGIC2C)) return -EINVAL; /* * If pid namespaces are enabled and the current task is in a child * pid_namespace, the command is handled by reboot_pid_ns() which will * call do_exit(). */ ret = reboot_pid_ns(task_active_pid_ns(current), cmd); if (ret) return ret; /* Instead of trying to make the power_off code look like * halt when pm_power_off is not set do it the easy way. */ if ((cmd == LINUX_REBOOT_CMD_POWER_OFF) && !pm_power_off) cmd = LINUX_REBOOT_CMD_HALT; mutex_lock(&reboot_mutex); switch (cmd) { case LINUX_REBOOT_CMD_RESTART: kernel_restart(NULL); break; case LINUX_REBOOT_CMD_CAD_ON: C_A_D = 1; break; case LINUX_REBOOT_CMD_CAD_OFF: C_A_D = 0; break; case LINUX_REBOOT_CMD_HALT: kernel_halt(); do_exit(0); panic("cannot halt"); case LINUX_REBOOT_CMD_POWER_OFF: kernel_power_off(); do_exit(0); break; case LINUX_REBOOT_CMD_RESTART2: if (strncpy_from_user(&buffer[0], arg, sizeof(buffer) - 1) < 0) { ret = -EFAULT; break; } buffer[sizeof(buffer) - 1] = '\0'; kernel_restart(buffer); break; #ifdef CONFIG_KEXEC case LINUX_REBOOT_CMD_KEXEC: ret = kernel_kexec(); break; #endif #ifdef CONFIG_HIBERNATION case LINUX_REBOOT_CMD_SW_SUSPEND: ret = hibernate(); break; #endif default: ret = -EINVAL; break; } mutex_unlock(&reboot_mutex); return ret; } static void deferred_cad(struct work_struct *dummy) { kernel_restart(NULL); } /* * This function gets called by ctrl-alt-del - ie the keyboard interrupt. * As it's called within an interrupt, it may NOT sync: the only choice * is whether to reboot at once, or just ignore the ctrl-alt-del. */ void ctrl_alt_del(void) { static DECLARE_WORK(cad_work, deferred_cad); if (C_A_D) schedule_work(&cad_work); else kill_cad_pid(SIGINT, 1); } /* * Unprivileged users may change the real gid to the effective gid * or vice versa. (BSD-style) * * If you set the real gid at all, or set the effective gid to a value not * equal to the real gid, then the saved gid is set to the new effective gid. * * This makes it possible for a setgid program to completely drop its * privileges, which is often a useful assertion to make when you are doing * a security audit over a program. * * The general idea is that a program which uses just setregid() will be * 100% compatible with BSD. A program which uses just setgid() will be * 100% compatible with POSIX with saved IDs. * * SMP: There are not races, the GIDs are checked only by filesystem * operations (as far as semantic preservation is concerned). */ SYSCALL_DEFINE2(setregid, gid_t, rgid, gid_t, egid) { struct user_namespace *ns = current_user_ns(); const struct cred *old; struct cred *new; int retval; kgid_t krgid, kegid; krgid = make_kgid(ns, rgid); kegid = make_kgid(ns, egid); if ((rgid != (gid_t) -1) && !gid_valid(krgid)) return -EINVAL; if ((egid != (gid_t) -1) && !gid_valid(kegid)) return -EINVAL; new = prepare_creds(); if (!new) return -ENOMEM; old = current_cred(); retval = -EPERM; if (rgid != (gid_t) -1) { if (gid_eq(old->gid, krgid) || gid_eq(old->egid, krgid) || nsown_capable(CAP_SETGID)) new->gid = krgid; else goto error; } if (egid != (gid_t) -1) { if (gid_eq(old->gid, kegid) || gid_eq(old->egid, kegid) || gid_eq(old->sgid, kegid) || nsown_capable(CAP_SETGID)) new->egid = kegid; else goto error; } if (rgid != (gid_t) -1 || (egid != (gid_t) -1 && !gid_eq(kegid, old->gid))) new->sgid = new->egid; new->fsgid = new->egid; return commit_creds(new); error: abort_creds(new); return retval; } /* * setgid() is implemented like SysV w/ SAVED_IDS * * SMP: Same implicit races as above. */ SYSCALL_DEFINE1(setgid, gid_t, gid) { struct user_namespace *ns = current_user_ns(); const struct cred *old; struct cred *new; int retval; kgid_t kgid; kgid = make_kgid(ns, gid); if (!gid_valid(kgid)) return -EINVAL; new = prepare_creds(); if (!new) return -ENOMEM; old = current_cred(); retval = -EPERM; if (nsown_capable(CAP_SETGID)) new->gid = new->egid = new->sgid = new->fsgid = kgid; else if (gid_eq(kgid, old->gid) || gid_eq(kgid, old->sgid)) new->egid = new->fsgid = kgid; else goto error; return commit_creds(new); error: abort_creds(new); return retval; } /* * change the user struct in a credentials set to match the new UID */ static int set_user(struct cred *new) { struct user_struct *new_user; new_user = alloc_uid(new->uid); if (!new_user) return -EAGAIN; /* * We don't fail in case of NPROC limit excess here because too many * poorly written programs don't check set*uid() return code, assuming * it never fails if called by root. We may still enforce NPROC limit * for programs doing set*uid()+execve() by harmlessly deferring the * failure to the execve() stage. */ if (atomic_read(&new_user->processes) >= rlimit(RLIMIT_NPROC) && new_user != INIT_USER) current->flags |= PF_NPROC_EXCEEDED; else current->flags &= ~PF_NPROC_EXCEEDED; free_uid(new->user); new->user = new_user; return 0; } /* * Unprivileged users may change the real uid to the effective uid * or vice versa. (BSD-style) * * If you set the real uid at all, or set the effective uid to a value not * equal to the real uid, then the saved uid is set to the new effective uid. * * This makes it possible for a setuid program to completely drop its * privileges, which is often a useful assertion to make when you are doing * a security audit over a program. * * The general idea is that a program which uses just setreuid() will be * 100% compatible with BSD. A program which uses just setuid() will be * 100% compatible with POSIX with saved IDs. */ SYSCALL_DEFINE2(setreuid, uid_t, ruid, uid_t, euid) { struct user_namespace *ns = current_user_ns(); const struct cred *old; struct cred *new; int retval; kuid_t kruid, keuid; kruid = make_kuid(ns, ruid); keuid = make_kuid(ns, euid); if ((ruid != (uid_t) -1) && !uid_valid(kruid)) return -EINVAL; if ((euid != (uid_t) -1) && !uid_valid(keuid)) return -EINVAL; new = prepare_creds(); if (!new) return -ENOMEM; old = current_cred(); retval = -EPERM; if (ruid != (uid_t) -1) { new->uid = kruid; if (!uid_eq(old->uid, kruid) && !uid_eq(old->euid, kruid) && !nsown_capable(CAP_SETUID)) goto error; } if (euid != (uid_t) -1) { new->euid = keuid; if (!uid_eq(old->uid, keuid) && !uid_eq(old->euid, keuid) && !uid_eq(old->suid, keuid) && !nsown_capable(CAP_SETUID)) goto error; } if (!uid_eq(new->uid, old->uid)) { retval = set_user(new); if (retval < 0) goto error; } if (ruid != (uid_t) -1 || (euid != (uid_t) -1 && !uid_eq(keuid, old->uid))) new->suid = new->euid; new->fsuid = new->euid; retval = security_task_fix_setuid(new, old, LSM_SETID_RE); if (retval < 0) goto error; return commit_creds(new); error: abort_creds(new); return retval; } /* * setuid() is implemented like SysV with SAVED_IDS * * Note that SAVED_ID's is deficient in that a setuid root program * like sendmail, for example, cannot set its uid to be a normal * user and then switch back, because if you're root, setuid() sets * the saved uid too. If you don't like this, blame the bright people * in the POSIX committee and/or USG. Note that the BSD-style setreuid() * will allow a root program to temporarily drop privileges and be able to * regain them by swapping the real and effective uid. */ SYSCALL_DEFINE1(setuid, uid_t, uid) { struct user_namespace *ns = current_user_ns(); const struct cred *old; struct cred *new; int retval; kuid_t kuid; kuid = make_kuid(ns, uid); if (!uid_valid(kuid)) return -EINVAL; new = prepare_creds(); if (!new) return -ENOMEM; old = current_cred(); retval = -EPERM; if (nsown_capable(CAP_SETUID)) { new->suid = new->uid = kuid; if (!uid_eq(kuid, old->uid)) { retval = set_user(new); if (retval < 0) goto error; } } else if (!uid_eq(kuid, old->uid) && !uid_eq(kuid, new->suid)) { goto error; } new->fsuid = new->euid = kuid; retval = security_task_fix_setuid(new, old, LSM_SETID_ID); if (retval < 0) goto error; return commit_creds(new); error: abort_creds(new); return retval; } /* * This function implements a generic ability to update ruid, euid, * and suid. This allows you to implement the 4.4 compatible seteuid(). */ SYSCALL_DEFINE3(setresuid, uid_t, ruid, uid_t, euid, uid_t, suid) { struct user_namespace *ns = current_user_ns(); const struct cred *old; struct cred *new; int retval; kuid_t kruid, keuid, ksuid; kruid = make_kuid(ns, ruid); keuid = make_kuid(ns, euid); ksuid = make_kuid(ns, suid); if ((ruid != (uid_t) -1) && !uid_valid(kruid)) return -EINVAL; if ((euid != (uid_t) -1) && !uid_valid(keuid)) return -EINVAL; if ((suid != (uid_t) -1) && !uid_valid(ksuid)) return -EINVAL; new = prepare_creds(); if (!new) return -ENOMEM; old = current_cred(); retval = -EPERM; if (!nsown_capable(CAP_SETUID)) { if (ruid != (uid_t) -1 && !uid_eq(kruid, old->uid) && !uid_eq(kruid, old->euid) && !uid_eq(kruid, old->suid)) goto error; if (euid != (uid_t) -1 && !uid_eq(keuid, old->uid) && !uid_eq(keuid, old->euid) && !uid_eq(keuid, old->suid)) goto error; if (suid != (uid_t) -1 && !uid_eq(ksuid, old->uid) && !uid_eq(ksuid, old->euid) && !uid_eq(ksuid, old->suid)) goto error; } if (ruid != (uid_t) -1) { new->uid = kruid; if (!uid_eq(kruid, old->uid)) { retval = set_user(new); if (retval < 0) goto error; } } if (euid != (uid_t) -1) new->euid = keuid; if (suid != (uid_t) -1) new->suid = ksuid; new->fsuid = new->euid; retval = security_task_fix_setuid(new, old, LSM_SETID_RES); if (retval < 0) goto error; return commit_creds(new); error: abort_creds(new); return retval; } SYSCALL_DEFINE3(getresuid, uid_t __user *, ruidp, uid_t __user *, euidp, uid_t __user *, suidp) { const struct cred *cred = current_cred(); int retval; uid_t ruid, euid, suid; ruid = from_kuid_munged(cred->user_ns, cred->uid); euid = from_kuid_munged(cred->user_ns, cred->euid); suid = from_kuid_munged(cred->user_ns, cred->suid); if (!(retval = put_user(ruid, ruidp)) && !(retval = put_user(euid, euidp))) retval = put_user(suid, suidp); return retval; } /* * Same as above, but for rgid, egid, sgid. */ SYSCALL_DEFINE3(setresgid, gid_t, rgid, gid_t, egid, gid_t, sgid) { struct user_namespace *ns = current_user_ns(); const struct cred *old; struct cred *new; int retval; kgid_t krgid, kegid, ksgid; krgid = make_kgid(ns, rgid); kegid = make_kgid(ns, egid); ksgid = make_kgid(ns, sgid); if ((rgid != (gid_t) -1) && !gid_valid(krgid)) return -EINVAL; if ((egid != (gid_t) -1) && !gid_valid(kegid)) return -EINVAL; if ((sgid != (gid_t) -1) && !gid_valid(ksgid)) return -EINVAL; new = prepare_creds(); if (!new) return -ENOMEM; old = current_cred(); retval = -EPERM; if (!nsown_capable(CAP_SETGID)) { if (rgid != (gid_t) -1 && !gid_eq(krgid, old->gid) && !gid_eq(krgid, old->egid) && !gid_eq(krgid, old->sgid)) goto error; if (egid != (gid_t) -1 && !gid_eq(kegid, old->gid) && !gid_eq(kegid, old->egid) && !gid_eq(kegid, old->sgid)) goto error; if (sgid != (gid_t) -1 && !gid_eq(ksgid, old->gid) && !gid_eq(ksgid, old->egid) && !gid_eq(ksgid, old->sgid)) goto error; } if (rgid != (gid_t) -1) new->gid = krgid; if (egid != (gid_t) -1) new->egid = kegid; if (sgid != (gid_t) -1) new->sgid = ksgid; new->fsgid = new->egid; return commit_creds(new); error: abort_creds(new); return retval; } SYSCALL_DEFINE3(getresgid, gid_t __user *, rgidp, gid_t __user *, egidp, gid_t __user *, sgidp) { const struct cred *cred = current_cred(); int retval; gid_t rgid, egid, sgid; rgid = from_kgid_munged(cred->user_ns, cred->gid); egid = from_kgid_munged(cred->user_ns, cred->egid); sgid = from_kgid_munged(cred->user_ns, cred->sgid); if (!(retval = put_user(rgid, rgidp)) && !(retval = put_user(egid, egidp))) retval = put_user(sgid, sgidp); return retval; } /* * "setfsuid()" sets the fsuid - the uid used for filesystem checks. This * is used for "access()" and for the NFS daemon (letting nfsd stay at * whatever uid it wants to). It normally shadows "euid", except when * explicitly set by setfsuid() or for access.. */ SYSCALL_DEFINE1(setfsuid, uid_t, uid) { const struct cred *old; struct cred *new; uid_t old_fsuid; kuid_t kuid; old = current_cred(); old_fsuid = from_kuid_munged(old->user_ns, old->fsuid); kuid = make_kuid(old->user_ns, uid); if (!uid_valid(kuid)) return old_fsuid; new = prepare_creds(); if (!new) return old_fsuid; if (uid_eq(kuid, old->uid) || uid_eq(kuid, old->euid) || uid_eq(kuid, old->suid) || uid_eq(kuid, old->fsuid) || nsown_capable(CAP_SETUID)) { if (!uid_eq(kuid, old->fsuid)) { new->fsuid = kuid; if (security_task_fix_setuid(new, old, LSM_SETID_FS) == 0) goto change_okay; } } abort_creds(new); return old_fsuid; change_okay: commit_creds(new); return old_fsuid; } /* * Samma på svenska.. */ SYSCALL_DEFINE1(setfsgid, gid_t, gid) { const struct cred *old; struct cred *new; gid_t old_fsgid; kgid_t kgid; old = current_cred(); old_fsgid = from_kgid_munged(old->user_ns, old->fsgid); kgid = make_kgid(old->user_ns, gid); if (!gid_valid(kgid)) return old_fsgid; new = prepare_creds(); if (!new) return old_fsgid; if (gid_eq(kgid, old->gid) || gid_eq(kgid, old->egid) || gid_eq(kgid, old->sgid) || gid_eq(kgid, old->fsgid) || nsown_capable(CAP_SETGID)) { if (!gid_eq(kgid, old->fsgid)) { new->fsgid = kgid; goto change_okay; } } abort_creds(new); return old_fsgid; change_okay: commit_creds(new); return old_fsgid; } void do_sys_times(struct tms *tms) { cputime_t tgutime, tgstime, cutime, cstime; spin_lock_irq(&current->sighand->siglock); thread_group_times(current, &tgutime, &tgstime); cutime = current->signal->cutime; cstime = current->signal->cstime; spin_unlock_irq(&current->sighand->siglock); tms->tms_utime = cputime_to_clock_t(tgutime); tms->tms_stime = cputime_to_clock_t(tgstime); tms->tms_cutime = cputime_to_clock_t(cutime); tms->tms_cstime = cputime_to_clock_t(cstime); } SYSCALL_DEFINE1(times, struct tms __user *, tbuf) { if (tbuf) { struct tms tmp; do_sys_times(&tmp); if (copy_to_user(tbuf, &tmp, sizeof(struct tms))) return -EFAULT; } force_successful_syscall_return(); return (long) jiffies_64_to_clock_t(get_jiffies_64()); } /* * This needs some heavy checking ... * I just haven't the stomach for it. I also don't fully * understand sessions/pgrp etc. Let somebody who does explain it. * * OK, I think I have the protection semantics right.... this is really * only important on a multi-user system anyway, to make sure one user * can't send a signal to a process owned by another. -TYT, 12/12/91 * * Auch. Had to add the 'did_exec' flag to conform completely to POSIX. * LBT 04.03.94 */ SYSCALL_DEFINE2(setpgid, pid_t, pid, pid_t, pgid) { struct task_struct *p; struct task_struct *group_leader = current->group_leader; struct pid *pgrp; int err; if (!pid) pid = task_pid_vnr(group_leader); if (!pgid) pgid = pid; if (pgid < 0) return -EINVAL; rcu_read_lock(); /* From this point forward we keep holding onto the tasklist lock * so that our parent does not change from under us. -DaveM */ write_lock_irq(&tasklist_lock); err = -ESRCH; p = find_task_by_vpid(pid); if (!p) goto out; err = -EINVAL; if (!thread_group_leader(p)) goto out; if (same_thread_group(p->real_parent, group_leader)) { err = -EPERM; if (task_session(p) != task_session(group_leader)) goto out; err = -EACCES; if (p->did_exec) goto out; } else { err = -ESRCH; if (p != group_leader) goto out; } err = -EPERM; if (p->signal->leader) goto out; pgrp = task_pid(p); if (pgid != pid) { struct task_struct *g; pgrp = find_vpid(pgid); g = pid_task(pgrp, PIDTYPE_PGID); if (!g || task_session(g) != task_session(group_leader)) goto out; } err = security_task_setpgid(p, pgid); if (err) goto out; if (task_pgrp(p) != pgrp) change_pid(p, PIDTYPE_PGID, pgrp); err = 0; out: /* All paths lead to here, thus we are safe. -DaveM */ write_unlock_irq(&tasklist_lock); rcu_read_unlock(); return err; } SYSCALL_DEFINE1(getpgid, pid_t, pid) { struct task_struct *p; struct pid *grp; int retval; rcu_read_lock(); if (!pid) grp = task_pgrp(current); else { retval = -ESRCH; p = find_task_by_vpid(pid); if (!p) goto out; grp = task_pgrp(p); if (!grp) goto out; retval = security_task_getpgid(p); if (retval) goto out; } retval = pid_vnr(grp); out: rcu_read_unlock(); return retval; } #ifdef __ARCH_WANT_SYS_GETPGRP SYSCALL_DEFINE0(getpgrp) { return sys_getpgid(0); } #endif SYSCALL_DEFINE1(getsid, pid_t, pid) { struct task_struct *p; struct pid *sid; int retval; rcu_read_lock(); if (!pid) sid = task_session(current); else { retval = -ESRCH; p = find_task_by_vpid(pid); if (!p) goto out; sid = task_session(p); if (!sid) goto out; retval = security_task_getsid(p); if (retval) goto out; } retval = pid_vnr(sid); out: rcu_read_unlock(); return retval; } SYSCALL_DEFINE0(setsid) { struct task_struct *group_leader = current->group_leader; struct pid *sid = task_pid(group_leader); pid_t session = pid_vnr(sid); int err = -EPERM; write_lock_irq(&tasklist_lock); /* Fail if I am already a session leader */ if (group_leader->signal->leader) goto out; /* Fail if a process group id already exists that equals the * proposed session id. */ if (pid_task(sid, PIDTYPE_PGID)) goto out; group_leader->signal->leader = 1; __set_special_pids(sid); proc_clear_tty(group_leader); err = session; out: write_unlock_irq(&tasklist_lock); if (err > 0) { proc_sid_connector(group_leader); sched_autogroup_create_attach(group_leader); } return err; } DECLARE_RWSEM(uts_sem); #ifdef COMPAT_UTS_MACHINE #define override_architecture(name) \ (personality(current->personality) == PER_LINUX32 && \ copy_to_user(name->machine, COMPAT_UTS_MACHINE, \ sizeof(COMPAT_UTS_MACHINE))) #else #define override_architecture(name) 0 #endif /* * Work around broken programs that cannot handle "Linux 3.0". * Instead we map 3.x to 2.6.40+x, so e.g. 3.0 would be 2.6.40 */ static int override_release(char __user *release, int len) { int ret = 0; char buf[65]; if (current->personality & UNAME26) { char *rest = UTS_RELEASE; int ndots = 0; unsigned v; while (*rest) { if (*rest == '.' && ++ndots >= 3) break; if (!isdigit(*rest) && *rest != '.') break; rest++; } v = ((LINUX_VERSION_CODE >> 8) & 0xff) + 40; snprintf(buf, len, "2.6.%u%s", v, rest); ret = copy_to_user(release, buf, len); } return ret; } SYSCALL_DEFINE1(newuname, struct new_utsname __user *, name) { int errno = 0; down_read(&uts_sem); if (copy_to_user(name, utsname(), sizeof *name)) errno = -EFAULT; up_read(&uts_sem); if (!errno && override_release(name->release, sizeof(name->release))) errno = -EFAULT; if (!errno && override_architecture(name)) errno = -EFAULT; return errno; } #ifdef __ARCH_WANT_SYS_OLD_UNAME /* * Old cruft */ SYSCALL_DEFINE1(uname, struct old_utsname __user *, name) { int error = 0; if (!name) return -EFAULT; down_read(&uts_sem); if (copy_to_user(name, utsname(), sizeof(*name))) error = -EFAULT; up_read(&uts_sem); if (!error && override_release(name->release, sizeof(name->release))) error = -EFAULT; if (!error && override_architecture(name)) error = -EFAULT; return error; } SYSCALL_DEFINE1(olduname, struct oldold_utsname __user *, name) { int error; if (!name) return -EFAULT; if (!access_ok(VERIFY_WRITE, name, sizeof(struct oldold_utsname))) return -EFAULT; down_read(&uts_sem); error = __copy_to_user(&name->sysname, &utsname()->sysname, __OLD_UTS_LEN); error |= __put_user(0, name->sysname + __OLD_UTS_LEN); error |= __copy_to_user(&name->nodename, &utsname()->nodename, __OLD_UTS_LEN); error |= __put_user(0, name->nodename + __OLD_UTS_LEN); error |= __copy_to_user(&name->release, &utsname()->release, __OLD_UTS_LEN); error |= __put_user(0, name->release + __OLD_UTS_LEN); error |= __copy_to_user(&name->version, &utsname()->version, __OLD_UTS_LEN); error |= __put_user(0, name->version + __OLD_UTS_LEN); error |= __copy_to_user(&name->machine, &utsname()->machine, __OLD_UTS_LEN); error |= __put_user(0, name->machine + __OLD_UTS_LEN); up_read(&uts_sem); if (!error && override_architecture(name)) error = -EFAULT; if (!error && override_release(name->release, sizeof(name->release))) error = -EFAULT; return error ? -EFAULT : 0; } #endif SYSCALL_DEFINE2(sethostname, char __user *, name, int, len) { int errno; char tmp[__NEW_UTS_LEN]; if (!ns_capable(current->nsproxy->uts_ns->user_ns, CAP_SYS_ADMIN)) return -EPERM; if (len < 0 || len > __NEW_UTS_LEN) return -EINVAL; down_write(&uts_sem); errno = -EFAULT; if (!copy_from_user(tmp, name, len)) { struct new_utsname *u = utsname(); memcpy(u->nodename, tmp, len); memset(u->nodename + len, 0, sizeof(u->nodename) - len); errno = 0; uts_proc_notify(UTS_PROC_HOSTNAME); } up_write(&uts_sem); return errno; } #ifdef __ARCH_WANT_SYS_GETHOSTNAME SYSCALL_DEFINE2(gethostname, char __user *, name, int, len) { int i, errno; struct new_utsname *u; if (len < 0) return -EINVAL; down_read(&uts_sem); u = utsname(); i = 1 + strlen(u->nodename); if (i > len) i = len; errno = 0; if (copy_to_user(name, u->nodename, i)) errno = -EFAULT; up_read(&uts_sem); return errno; } #endif /* * Only setdomainname; getdomainname can be implemented by calling * uname() */ SYSCALL_DEFINE2(setdomainname, char __user *, name, int, len) { int errno; char tmp[__NEW_UTS_LEN]; if (!ns_capable(current->nsproxy->uts_ns->user_ns, CAP_SYS_ADMIN)) return -EPERM; if (len < 0 || len > __NEW_UTS_LEN) return -EINVAL; down_write(&uts_sem); errno = -EFAULT; if (!copy_from_user(tmp, name, len)) { struct new_utsname *u = utsname(); memcpy(u->domainname, tmp, len); memset(u->domainname + len, 0, sizeof(u->domainname) - len); errno = 0; uts_proc_notify(UTS_PROC_DOMAINNAME); } up_write(&uts_sem); return errno; } SYSCALL_DEFINE2(getrlimit, unsigned int, resource, struct rlimit __user *, rlim) { struct rlimit value; int ret; ret = do_prlimit(current, resource, NULL, &value); if (!ret) ret = copy_to_user(rlim, &value, sizeof(*rlim)) ? -EFAULT : 0; return ret; } #ifdef __ARCH_WANT_SYS_OLD_GETRLIMIT /* * Back compatibility for getrlimit. Needed for some apps. */ SYSCALL_DEFINE2(old_getrlimit, unsigned int, resource, struct rlimit __user *, rlim) { struct rlimit x; if (resource >= RLIM_NLIMITS) return -EINVAL; task_lock(current->group_leader); x = current->signal->rlim[resource]; task_unlock(current->group_leader); if (x.rlim_cur > 0x7FFFFFFF) x.rlim_cur = 0x7FFFFFFF; if (x.rlim_max > 0x7FFFFFFF) x.rlim_max = 0x7FFFFFFF; return copy_to_user(rlim, &x, sizeof(x))?-EFAULT:0; } #endif static inline bool rlim64_is_infinity(__u64 rlim64) { #if BITS_PER_LONG < 64 return rlim64 >= ULONG_MAX; #else return rlim64 == RLIM64_INFINITY; #endif } static void rlim_to_rlim64(const struct rlimit *rlim, struct rlimit64 *rlim64) { if (rlim->rlim_cur == RLIM_INFINITY) rlim64->rlim_cur = RLIM64_INFINITY; else rlim64->rlim_cur = rlim->rlim_cur; if (rlim->rlim_max == RLIM_INFINITY) rlim64->rlim_max = RLIM64_INFINITY; else rlim64->rlim_max = rlim->rlim_max; } static void rlim64_to_rlim(const struct rlimit64 *rlim64, struct rlimit *rlim) { if (rlim64_is_infinity(rlim64->rlim_cur)) rlim->rlim_cur = RLIM_INFINITY; else rlim->rlim_cur = (unsigned long)rlim64->rlim_cur; if (rlim64_is_infinity(rlim64->rlim_max)) rlim->rlim_max = RLIM_INFINITY; else rlim->rlim_max = (unsigned long)rlim64->rlim_max; } /* make sure you are allowed to change @tsk limits before calling this */ int do_prlimit(struct task_struct *tsk, unsigned int resource, struct rlimit *new_rlim, struct rlimit *old_rlim) { struct rlimit *rlim; int retval = 0; if (resource >= RLIM_NLIMITS) return -EINVAL; if (new_rlim) { if (new_rlim->rlim_cur > new_rlim->rlim_max) return -EINVAL; if (resource == RLIMIT_NOFILE && new_rlim->rlim_max > sysctl_nr_open) return -EPERM; } /* protect tsk->signal and tsk->sighand from disappearing */ read_lock(&tasklist_lock); if (!tsk->sighand) { retval = -ESRCH; goto out; } rlim = tsk->signal->rlim + resource; task_lock(tsk->group_leader); if (new_rlim) { /* Keep the capable check against init_user_ns until cgroups can contain all limits */ if (new_rlim->rlim_max > rlim->rlim_max && !capable(CAP_SYS_RESOURCE)) retval = -EPERM; if (!retval) retval = security_task_setrlimit(tsk->group_leader, resource, new_rlim); if (resource == RLIMIT_CPU && new_rlim->rlim_cur == 0) { /* * The caller is asking for an immediate RLIMIT_CPU * expiry. But we use the zero value to mean "it was * never set". So let's cheat and make it one second * instead */ new_rlim->rlim_cur = 1; } } if (!retval) { if (old_rlim) *old_rlim = *rlim; if (new_rlim) *rlim = *new_rlim; } task_unlock(tsk->group_leader); /* * RLIMIT_CPU handling. Note that the kernel fails to return an error * code if it rejected the user's attempt to set RLIMIT_CPU. This is a * very long-standing error, and fixing it now risks breakage of * applications, so we live with it */ if (!retval && new_rlim && resource == RLIMIT_CPU && new_rlim->rlim_cur != RLIM_INFINITY) update_rlimit_cpu(tsk, new_rlim->rlim_cur); out: read_unlock(&tasklist_lock); return retval; } /* rcu lock must be held */ static int check_prlimit_permission(struct task_struct *task) { const struct cred *cred = current_cred(), *tcred; if (current == task) return 0; tcred = __task_cred(task); if (uid_eq(cred->uid, tcred->euid) && uid_eq(cred->uid, tcred->suid) && uid_eq(cred->uid, tcred->uid) && gid_eq(cred->gid, tcred->egid) && gid_eq(cred->gid, tcred->sgid) && gid_eq(cred->gid, tcred->gid)) return 0; if (ns_capable(tcred->user_ns, CAP_SYS_RESOURCE)) return 0; return -EPERM; } SYSCALL_DEFINE4(prlimit64, pid_t, pid, unsigned int, resource, const struct rlimit64 __user *, new_rlim, struct rlimit64 __user *, old_rlim) { struct rlimit64 old64, new64; struct rlimit old, new; struct task_struct *tsk; int ret; if (new_rlim) { if (copy_from_user(&new64, new_rlim, sizeof(new64))) return -EFAULT; rlim64_to_rlim(&new64, &new); } rcu_read_lock(); tsk = pid ? find_task_by_vpid(pid) : current; if (!tsk) { rcu_read_unlock(); return -ESRCH; } ret = check_prlimit_permission(tsk); if (ret) { rcu_read_unlock(); return ret; } get_task_struct(tsk); rcu_read_unlock(); ret = do_prlimit(tsk, resource, new_rlim ? &new : NULL, old_rlim ? &old : NULL); if (!ret && old_rlim) { rlim_to_rlim64(&old, &old64); if (copy_to_user(old_rlim, &old64, sizeof(old64))) ret = -EFAULT; } put_task_struct(tsk); return ret; } SYSCALL_DEFINE2(setrlimit, unsigned int, resource, struct rlimit __user *, rlim) { struct rlimit new_rlim; if (copy_from_user(&new_rlim, rlim, sizeof(*rlim))) return -EFAULT; return do_prlimit(current, resource, &new_rlim, NULL); } /* * It would make sense to put struct rusage in the task_struct, * except that would make the task_struct be *really big*. After * task_struct gets moved into malloc'ed memory, it would * make sense to do this. It will make moving the rest of the information * a lot simpler! (Which we're not doing right now because we're not * measuring them yet). * * When sampling multiple threads for RUSAGE_SELF, under SMP we might have * races with threads incrementing their own counters. But since word * reads are atomic, we either get new values or old values and we don't * care which for the sums. We always take the siglock to protect reading * the c* fields from p->signal from races with exit.c updating those * fields when reaping, so a sample either gets all the additions of a * given child after it's reaped, or none so this sample is before reaping. * * Locking: * We need to take the siglock for CHILDEREN, SELF and BOTH * for the cases current multithreaded, non-current single threaded * non-current multithreaded. Thread traversal is now safe with * the siglock held. * Strictly speaking, we donot need to take the siglock if we are current and * single threaded, as no one else can take our signal_struct away, no one * else can reap the children to update signal->c* counters, and no one else * can race with the signal-> fields. If we do not take any lock, the * signal-> fields could be read out of order while another thread was just * exiting. So we should place a read memory barrier when we avoid the lock. * On the writer side, write memory barrier is implied in __exit_signal * as __exit_signal releases the siglock spinlock after updating the signal-> * fields. But we don't do this yet to keep things simple. * */ static void accumulate_thread_rusage(struct task_struct *t, struct rusage *r) { r->ru_nvcsw += t->nvcsw; r->ru_nivcsw += t->nivcsw; r->ru_minflt += t->min_flt; r->ru_majflt += t->maj_flt; r->ru_inblock += task_io_get_inblock(t); r->ru_oublock += task_io_get_oublock(t); } static void k_getrusage(struct task_struct *p, int who, struct rusage *r) { struct task_struct *t; unsigned long flags; cputime_t tgutime, tgstime, utime, stime; unsigned long maxrss = 0; memset((char *) r, 0, sizeof *r); utime = stime = 0; if (who == RUSAGE_THREAD) { task_times(current, &utime, &stime); accumulate_thread_rusage(p, r); maxrss = p->signal->maxrss; goto out; } if (!lock_task_sighand(p, &flags)) return; switch (who) { case RUSAGE_BOTH: case RUSAGE_CHILDREN: utime = p->signal->cutime; stime = p->signal->cstime; r->ru_nvcsw = p->signal->cnvcsw; r->ru_nivcsw = p->signal->cnivcsw; r->ru_minflt = p->signal->cmin_flt; r->ru_majflt = p->signal->cmaj_flt; r->ru_inblock = p->signal->cinblock; r->ru_oublock = p->signal->coublock; maxrss = p->signal->cmaxrss; if (who == RUSAGE_CHILDREN) break; case RUSAGE_SELF: thread_group_times(p, &tgutime, &tgstime); utime += tgutime; stime += tgstime; r->ru_nvcsw += p->signal->nvcsw; r->ru_nivcsw += p->signal->nivcsw; r->ru_minflt += p->signal->min_flt; r->ru_majflt += p->signal->maj_flt; r->ru_inblock += p->signal->inblock; r->ru_oublock += p->signal->oublock; if (maxrss < p->signal->maxrss) maxrss = p->signal->maxrss; t = p; do { accumulate_thread_rusage(t, r); t = next_thread(t); } while (t != p); break; default: BUG(); } unlock_task_sighand(p, &flags); out: cputime_to_timeval(utime, &r->ru_utime); cputime_to_timeval(stime, &r->ru_stime); if (who != RUSAGE_CHILDREN) { struct mm_struct *mm = get_task_mm(p); if (mm) { setmax_mm_hiwater_rss(&maxrss, mm); mmput(mm); } } r->ru_maxrss = maxrss * (PAGE_SIZE / 1024); /* convert pages to KBs */ } int getrusage(struct task_struct *p, int who, struct rusage __user *ru) { struct rusage r; k_getrusage(p, who, &r); return copy_to_user(ru, &r, sizeof(r)) ? -EFAULT : 0; } SYSCALL_DEFINE2(getrusage, int, who, struct rusage __user *, ru) { if (who != RUSAGE_SELF && who != RUSAGE_CHILDREN && who != RUSAGE_THREAD) return -EINVAL; return getrusage(current, who, ru); } SYSCALL_DEFINE1(umask, int, mask) { mask = xchg(&current->fs->umask, mask & S_IRWXUGO); return mask; } #ifdef CONFIG_CHECKPOINT_RESTORE static int prctl_set_mm_exe_file(struct mm_struct *mm, unsigned int fd) { struct fd exe; struct dentry *dentry; int err; exe = fdget(fd); if (!exe.file) return -EBADF; dentry = exe.file->f_path.dentry; /* * Because the original mm->exe_file points to executable file, make * sure that this one is executable as well, to avoid breaking an * overall picture. */ err = -EACCES; if (!S_ISREG(dentry->d_inode->i_mode) || exe.file->f_path.mnt->mnt_flags & MNT_NOEXEC) goto exit; err = inode_permission(dentry->d_inode, MAY_EXEC); if (err) goto exit; down_write(&mm->mmap_sem); /* * Forbid mm->exe_file change if old file still mapped. */ err = -EBUSY; if (mm->exe_file) { struct vm_area_struct *vma; for (vma = mm->mmap; vma; vma = vma->vm_next) if (vma->vm_file && path_equal(&vma->vm_file->f_path, &mm->exe_file->f_path)) goto exit_unlock; } /* * The symlink can be changed only once, just to disallow arbitrary * transitions malicious software might bring in. This means one * could make a snapshot over all processes running and monitor * /proc/pid/exe changes to notice unusual activity if needed. */ err = -EPERM; if (test_and_set_bit(MMF_EXE_FILE_CHANGED, &mm->flags)) goto exit_unlock; err = 0; set_mm_exe_file(mm, exe.file); /* this grabs a reference to exe.file */ exit_unlock: up_write(&mm->mmap_sem); exit: fdput(exe); return err; } static int prctl_set_mm(int opt, unsigned long addr, unsigned long arg4, unsigned long arg5) { unsigned long rlim = rlimit(RLIMIT_DATA); struct mm_struct *mm = current->mm; struct vm_area_struct *vma; int error; if (arg5 || (arg4 && opt != PR_SET_MM_AUXV)) return -EINVAL; if (!capable(CAP_SYS_RESOURCE)) return -EPERM; if (opt == PR_SET_MM_EXE_FILE) return prctl_set_mm_exe_file(mm, (unsigned int)addr); if (addr >= TASK_SIZE || addr < mmap_min_addr) return -EINVAL; error = -EINVAL; down_read(&mm->mmap_sem); vma = find_vma(mm, addr); switch (opt) { case PR_SET_MM_START_CODE: mm->start_code = addr; break; case PR_SET_MM_END_CODE: mm->end_code = addr; break; case PR_SET_MM_START_DATA: mm->start_data = addr; break; case PR_SET_MM_END_DATA: mm->end_data = addr; break; case PR_SET_MM_START_BRK: if (addr <= mm->end_data) goto out; if (rlim < RLIM_INFINITY && (mm->brk - addr) + (mm->end_data - mm->start_data) > rlim) goto out; mm->start_brk = addr; break; case PR_SET_MM_BRK: if (addr <= mm->end_data) goto out; if (rlim < RLIM_INFINITY && (addr - mm->start_brk) + (mm->end_data - mm->start_data) > rlim) goto out; mm->brk = addr; break; /* * If command line arguments and environment * are placed somewhere else on stack, we can * set them up here, ARG_START/END to setup * command line argumets and ENV_START/END * for environment. */ case PR_SET_MM_START_STACK: case PR_SET_MM_ARG_START: case PR_SET_MM_ARG_END: case PR_SET_MM_ENV_START: case PR_SET_MM_ENV_END: if (!vma) { error = -EFAULT; goto out; } if (opt == PR_SET_MM_START_STACK) mm->start_stack = addr; else if (opt == PR_SET_MM_ARG_START) mm->arg_start = addr; else if (opt == PR_SET_MM_ARG_END) mm->arg_end = addr; else if (opt == PR_SET_MM_ENV_START) mm->env_start = addr; else if (opt == PR_SET_MM_ENV_END) mm->env_end = addr; break; /* * This doesn't move auxiliary vector itself * since it's pinned to mm_struct, but allow * to fill vector with new values. It's up * to a caller to provide sane values here * otherwise user space tools which use this * vector might be unhappy. */ case PR_SET_MM_AUXV: { unsigned long user_auxv[AT_VECTOR_SIZE]; if (arg4 > sizeof(user_auxv)) goto out; up_read(&mm->mmap_sem); if (copy_from_user(user_auxv, (const void __user *)addr, arg4)) return -EFAULT; /* Make sure the last entry is always AT_NULL */ user_auxv[AT_VECTOR_SIZE - 2] = 0; user_auxv[AT_VECTOR_SIZE - 1] = 0; BUILD_BUG_ON(sizeof(user_auxv) != sizeof(mm->saved_auxv)); task_lock(current); memcpy(mm->saved_auxv, user_auxv, arg4); task_unlock(current); return 0; } default: goto out; } error = 0; out: up_read(&mm->mmap_sem); return error; } static int prctl_get_tid_address(struct task_struct *me, int __user **tid_addr) { return put_user(me->clear_child_tid, tid_addr); } #else /* CONFIG_CHECKPOINT_RESTORE */ static int prctl_set_mm(int opt, unsigned long addr, unsigned long arg4, unsigned long arg5) { return -EINVAL; } static int prctl_get_tid_address(struct task_struct *me, int __user **tid_addr) { return -EINVAL; } #endif SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3, unsigned long, arg4, unsigned long, arg5) { struct task_struct *me = current; unsigned char comm[sizeof(me->comm)]; long error; error = security_task_prctl(option, arg2, arg3, arg4, arg5); if (error != -ENOSYS) return error; error = 0; switch (option) { case PR_SET_PDEATHSIG: if (!valid_signal(arg2)) { error = -EINVAL; break; } me->pdeath_signal = arg2; break; case PR_GET_PDEATHSIG: error = put_user(me->pdeath_signal, (int __user *)arg2); break; case PR_GET_DUMPABLE: error = get_dumpable(me->mm); break; case PR_SET_DUMPABLE: if (arg2 < 0 || arg2 > 1) { error = -EINVAL; break; } set_dumpable(me->mm, arg2); break; case PR_SET_UNALIGN: error = SET_UNALIGN_CTL(me, arg2); break; case PR_GET_UNALIGN: error = GET_UNALIGN_CTL(me, arg2); break; case PR_SET_FPEMU: error = SET_FPEMU_CTL(me, arg2); break; case PR_GET_FPEMU: error = GET_FPEMU_CTL(me, arg2); break; case PR_SET_FPEXC: error = SET_FPEXC_CTL(me, arg2); break; case PR_GET_FPEXC: error = GET_FPEXC_CTL(me, arg2); break; case PR_GET_TIMING: error = PR_TIMING_STATISTICAL; break; case PR_SET_TIMING: if (arg2 != PR_TIMING_STATISTICAL) error = -EINVAL; break; case PR_SET_NAME: comm[sizeof(me->comm)-1] = 0; if (strncpy_from_user(comm, (char __user *)arg2, sizeof(me->comm) - 1) < 0) return -EFAULT; set_task_comm(me, comm); proc_comm_connector(me); break; case PR_GET_NAME: get_task_comm(comm, me); if (copy_to_user((char __user *)arg2, comm, sizeof(comm))) return -EFAULT; break; case PR_GET_ENDIAN: error = GET_ENDIAN(me, arg2); break; case PR_SET_ENDIAN: error = SET_ENDIAN(me, arg2); break; case PR_GET_SECCOMP: error = prctl_get_seccomp(); break; case PR_SET_SECCOMP: error = prctl_set_seccomp(arg2, (char __user *)arg3); break; case PR_GET_TSC: error = GET_TSC_CTL(arg2); break; case PR_SET_TSC: error = SET_TSC_CTL(arg2); break; case PR_TASK_PERF_EVENTS_DISABLE: error = perf_event_task_disable(); break; case PR_TASK_PERF_EVENTS_ENABLE: error = perf_event_task_enable(); break; case PR_GET_TIMERSLACK: error = current->timer_slack_ns; break; case PR_SET_TIMERSLACK: if (arg2 <= 0) current->timer_slack_ns = current->default_timer_slack_ns; else current->timer_slack_ns = arg2; break; case PR_MCE_KILL: if (arg4 | arg5) return -EINVAL; switch (arg2) { case PR_MCE_KILL_CLEAR: if (arg3 != 0) return -EINVAL; current->flags &= ~PF_MCE_PROCESS; break; case PR_MCE_KILL_SET: current->flags |= PF_MCE_PROCESS; if (arg3 == PR_MCE_KILL_EARLY) current->flags |= PF_MCE_EARLY; else if (arg3 == PR_MCE_KILL_LATE) current->flags &= ~PF_MCE_EARLY; else if (arg3 == PR_MCE_KILL_DEFAULT) current->flags &= ~(PF_MCE_EARLY|PF_MCE_PROCESS); else return -EINVAL; break; default: return -EINVAL; } break; case PR_MCE_KILL_GET: if (arg2 | arg3 | arg4 | arg5) return -EINVAL; if (current->flags & PF_MCE_PROCESS) error = (current->flags & PF_MCE_EARLY) ? PR_MCE_KILL_EARLY : PR_MCE_KILL_LATE; else error = PR_MCE_KILL_DEFAULT; break; case PR_SET_MM: error = prctl_set_mm(arg2, arg3, arg4, arg5); break; case PR_GET_TID_ADDRESS: error = prctl_get_tid_address(me, (int __user **)arg2); break; case PR_SET_CHILD_SUBREAPER: me->signal->is_child_subreaper = !!arg2; break; case PR_GET_CHILD_SUBREAPER: error = put_user(me->signal->is_child_subreaper, (int __user *) arg2); break; case PR_SET_NO_NEW_PRIVS: if (arg2 != 1 || arg3 || arg4 || arg5) return -EINVAL; current->no_new_privs = 1; break; case PR_GET_NO_NEW_PRIVS: if (arg2 || arg3 || arg4 || arg5) return -EINVAL; return current->no_new_privs ? 1 : 0; default: error = -EINVAL; break; } return error; } SYSCALL_DEFINE3(getcpu, unsigned __user *, cpup, unsigned __user *, nodep, struct getcpu_cache __user *, unused) { int err = 0; int cpu = raw_smp_processor_id(); if (cpup) err |= put_user(cpu, cpup); if (nodep) err |= put_user(cpu_to_node(cpu), nodep); return err ? -EFAULT : 0; } char poweroff_cmd[POWEROFF_CMD_PATH_LEN] = "/sbin/poweroff"; static void argv_cleanup(struct subprocess_info *info) { argv_free(info->argv); } static int __orderly_poweroff(void) { int argc; char **argv; static char *envp[] = { "HOME=/", "PATH=/sbin:/bin:/usr/sbin:/usr/bin", NULL }; int ret; argv = argv_split(GFP_ATOMIC, poweroff_cmd, &argc); if (argv == NULL) { printk(KERN_WARNING "%s failed to allocate memory for \"%s\"\n", __func__, poweroff_cmd); return -ENOMEM; } ret = call_usermodehelper_fns(argv[0], argv, envp, UMH_WAIT_EXEC, NULL, argv_cleanup, NULL); if (ret == -ENOMEM) argv_free(argv); return ret; } /** * orderly_poweroff - Trigger an orderly system poweroff * @force: force poweroff if command execution fails * * This may be called from any context to trigger a system shutdown. * If the orderly shutdown fails, it will force an immediate shutdown. */ int orderly_poweroff(bool force) { int ret = __orderly_poweroff(); if (ret && force) { printk(KERN_WARNING "Failed to start orderly shutdown: " "forcing the issue\n"); /* * I guess this should try to kick off some daemon to sync and * poweroff asap. Or not even bother syncing if we're doing an * emergency shutdown? */ emergency_sync(); kernel_power_off(); } return ret; } EXPORT_SYMBOL_GPL(orderly_poweroff);
./CrossVul/dataset_final_sorted/CWE-16/c/bad_3582_0
crossvul-cpp_data_bad_3860_1
/* * Copyright (c) 2016 Intel Corporation. * * SPDX-License-Identifier: Apache-2.0 */ #include <tc_util.h> #include <mqtt_internal.h> #include <sys/util.h> /* for ARRAY_SIZE */ #include <ztest.h> #define CLIENTID MQTT_UTF8_LITERAL("zephyr") #define TOPIC MQTT_UTF8_LITERAL("sensors") #define WILL_TOPIC MQTT_UTF8_LITERAL("quitting") #define WILL_MSG MQTT_UTF8_LITERAL("bye") #define USERNAME MQTT_UTF8_LITERAL("zephyr1") #define PASSWORD MQTT_UTF8_LITERAL("password") #define BUFFER_SIZE 128 static ZTEST_DMEM u8_t rx_buffer[BUFFER_SIZE]; static ZTEST_DMEM u8_t tx_buffer[BUFFER_SIZE]; static ZTEST_DMEM struct mqtt_client client; static ZTEST_DMEM struct mqtt_topic topic_qos_0 = { .qos = 0, .topic = TOPIC, }; static ZTEST_DMEM struct mqtt_topic topic_qos_1 = { .qos = 1, .topic = TOPIC, }; static ZTEST_DMEM struct mqtt_topic topic_qos_2 = { .qos = 2, .topic = TOPIC, }; static ZTEST_DMEM struct mqtt_topic will_topic_qos_0 = { .qos = 0, .topic = WILL_TOPIC, }; static ZTEST_DMEM struct mqtt_topic will_topic_qos_1 = { .qos = 1, .topic = WILL_TOPIC, }; static ZTEST_DMEM struct mqtt_utf8 will_msg = WILL_MSG; static ZTEST_DMEM struct mqtt_utf8 username = USERNAME; static ZTEST_DMEM struct mqtt_utf8 password = PASSWORD; /** * @brief MQTT test structure */ struct mqtt_test { /* test name, for example: "test connect 1" */ const char *test_name; /* cast to something like: * struct mqtt_publish_param *msg_publish = * (struct mqtt_publish_param *)ctx */ void *ctx; /* pointer to the eval routine, for example: * eval_fcn = eval_msg_connect */ int (*eval_fcn)(struct mqtt_test *); /* expected result */ u8_t *expected; /* length of 'expected' */ u16_t expected_len; }; /** * @brief eval_msg_connect Evaluate the given mqtt_test against the * connect packing/unpacking routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_connect(struct mqtt_test *mqtt_test); /** * @brief eval_msg_publish Evaluate the given mqtt_test against the * publish packing/unpacking routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_publish(struct mqtt_test *mqtt_test); /** * @brief eval_msg_subscribe Evaluate the given mqtt_test against the * subscribe packing/unpacking routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_subscribe(struct mqtt_test *mqtt_test); /** * @brief eval_msg_suback Evaluate the given mqtt_test against the * suback packing/unpacking routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_suback(struct mqtt_test *mqtt_test); /** * @brief eval_msg_pingreq Evaluate the given mqtt_test against the * pingreq packing/unpacking routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_pingreq(struct mqtt_test *mqtt_test); /** * @brief eval_msg_puback Evaluate the given mqtt_test against the * puback routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_puback(struct mqtt_test *mqtt_test); /** * @brief eval_msg_puback Evaluate the given mqtt_test against the * pubcomp routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_pubcomp(struct mqtt_test *mqtt_test); /** * @brief eval_msg_pubrec Evaluate the given mqtt_test against the * pubrec routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_pubrec(struct mqtt_test *mqtt_test); /** * @brief eval_msg_pubrel Evaluate the given mqtt_test against the * pubrel routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_pubrel(struct mqtt_test *mqtt_test); /** * @brief eval_msg_unsuback Evaluate the given mqtt_test against the * unsuback routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_unsuback(struct mqtt_test *mqtt_test); /** * @brief eval_msg_disconnect Evaluate the given mqtt_test against the * disconnect routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_disconnect(struct mqtt_test *mqtt_test); /** * @brief eval_buffers Evaluate if two given buffers are equal * @param [in] buf Input buffer 1, mostly used as the 'computed' * buffer * @param [in] expected Expected buffer * @param [in] len 'expected' len * @return TC_PASS on success * @return TC_FAIL on error and prints both buffers */ static int eval_buffers(const struct buf_ctx *buf, const u8_t *expected, u16_t len); /** * @brief print_array Prints the array 'a' of 'size' elements * @param a The array * @param size Array's size */ static void print_array(const u8_t *a, u16_t size); /* * MQTT CONNECT msg: * Clean session: 1 Client id: [6] 'zephyr' Will flag: 0 * Will QoS: 0 Will retain: 0 Will topic: [0] * Will msg: [0] Keep alive: 60 User name: [0] * Password: [0] * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -k 60 -t sensors */ static ZTEST_DMEM u8_t connect1[] = {0x10, 0x12, 0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x04, 0x02, 0x00, 0x3c, 0x00, 0x06, 0x7a, 0x65, 0x70, 0x68, 0x79, 0x72}; static ZTEST_DMEM struct mqtt_client client_connect1 = { .clean_session = 1, .client_id = CLIENTID, .will_retain = 0, .will_topic = NULL, .will_message = NULL, .user_name = NULL, .password = NULL }; /* * MQTT CONNECT msg: * Clean session: 1 Client id: [6] 'zephyr' Will flag: 1 * Will QoS: 0 Will retain: 0 Will topic: [8] quitting * Will msg: [3] bye Keep alive: 0 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -k 60 -t sensors --will-topic quitting \ * --will-qos 0 --will-payload bye */ static ZTEST_DMEM u8_t connect2[] = {0x10, 0x21, 0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x04, 0x06, 0x00, 0x3c, 0x00, 0x06, 0x7a, 0x65, 0x70, 0x68, 0x79, 0x72, 0x00, 0x08, 0x71, 0x75, 0x69, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x00, 0x03, 0x62, 0x79, 0x65}; static ZTEST_DMEM struct mqtt_client client_connect2 = { .clean_session = 1, .client_id = CLIENTID, .will_retain = 0, .will_topic = &will_topic_qos_0, .will_message = &will_msg, .user_name = NULL, .password = NULL }; /* * MQTT CONNECT msg: * Same message as connect3, but set Will retain: 1 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -k 60 -t sensors --will-topic quitting \ * --will-qos 0 --will-payload bye --will-retain */ static ZTEST_DMEM u8_t connect3[] = {0x10, 0x21, 0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x04, 0x26, 0x00, 0x3c, 0x00, 0x06, 0x7a, 0x65, 0x70, 0x68, 0x79, 0x72, 0x00, 0x08, 0x71, 0x75, 0x69, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x00, 0x03, 0x62, 0x79, 0x65}; static ZTEST_DMEM struct mqtt_client client_connect3 = { .clean_session = 1, .client_id = CLIENTID, .will_retain = 1, .will_topic = &will_topic_qos_0, .will_message = &will_msg, .user_name = NULL, .password = NULL }; /* * MQTT CONNECT msg: * Same message as connect3, but set Will QoS: 1 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -k 60 -t sensors --will-topic quitting \ * --will-qos 1 --will-payload bye */ static ZTEST_DMEM u8_t connect4[] = {0x10, 0x21, 0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x04, 0x0e, 0x00, 0x3c, 0x00, 0x06, 0x7a, 0x65, 0x70, 0x68, 0x79, 0x72, 0x00, 0x08, 0x71, 0x75, 0x69, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x00, 0x03, 0x62, 0x79, 0x65}; static ZTEST_DMEM struct mqtt_client client_connect4 = { .clean_session = 1, .client_id = CLIENTID, .will_retain = 0, .will_topic = &will_topic_qos_1, .will_message = &will_msg, .user_name = NULL, .password = NULL }; /* * MQTT CONNECT msg: * Same message as connect5, but set Will retain: 1 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -k 60 -t sensors --will-topic quitting \ * --will-qos 1 --will-payload bye --will-retain */ static ZTEST_DMEM u8_t connect5[] = {0x10, 0x21, 0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x04, 0x2e, 0x00, 0x3c, 0x00, 0x06, 0x7a, 0x65, 0x70, 0x68, 0x79, 0x72, 0x00, 0x08, 0x71, 0x75, 0x69, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x00, 0x03, 0x62, 0x79, 0x65}; static ZTEST_DMEM struct mqtt_client client_connect5 = { .clean_session = 1, .client_id = CLIENTID, .will_retain = 1, .will_topic = &will_topic_qos_1, .will_message = &will_msg, .user_name = NULL, .password = NULL }; /* * MQTT CONNECT msg: * Same message as connect6, but set username: zephyr1 and password: password * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -k 60 -t sensors --will-topic quitting \ * --will-qos 1 --will-payload bye --will-retain -u zephyr1 -P password */ static ZTEST_DMEM u8_t connect6[] = {0x10, 0x34, 0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x04, 0xee, 0x00, 0x3c, 0x00, 0x06, 0x7a, 0x65, 0x70, 0x68, 0x79, 0x72, 0x00, 0x08, 0x71, 0x75, 0x69, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x00, 0x03, 0x62, 0x79, 0x65, 0x00, 0x07, 0x7a, 0x65, 0x70, 0x68, 0x79, 0x72, 0x31, 0x00, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64}; static ZTEST_DMEM struct mqtt_client client_connect6 = { .clean_session = 1, .client_id = CLIENTID, .will_retain = 1, .will_topic = &will_topic_qos_1, .will_message = &will_msg, .user_name = &username, .password = &password }; static ZTEST_DMEM u8_t disconnect1[] = {0xe0, 0x00}; /* * MQTT PUBLISH msg: * DUP: 0, QoS: 0, Retain: 0, topic: sensors, message: OK * * Message can be generated by the following command: * mosquitto_pub -V mqttv311 -i zephyr -t sensors -q 0 -m "OK" */ static ZTEST_DMEM u8_t publish1[] = {0x30, 0x0b, 0x00, 0x07, 0x73, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x4f, 0x4b}; static ZTEST_DMEM struct mqtt_publish_param msg_publish1 = { .dup_flag = 0, .retain_flag = 0, .message_id = 0, .message.topic.qos = 0, .message.topic.topic = TOPIC, .message.payload.data = (u8_t *)"OK", .message.payload.len = 2, }; /* * MQTT PUBLISH msg: * DUP: 0, QoS: 0, Retain: 1, topic: sensors, message: OK * * Message can be generated by the following command: * mosquitto_pub -V mqttv311 -i zephyr -t sensors -q 0 -m "OK" -r */ static ZTEST_DMEM u8_t publish2[] = {0x31, 0x0b, 0x00, 0x07, 0x73, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x4f, 0x4b}; static ZTEST_DMEM struct mqtt_publish_param msg_publish2 = { .dup_flag = 0, .retain_flag = 1, .message_id = 0, .message.topic.qos = 0, .message.topic.topic = TOPIC, .message.payload.data = (u8_t *)"OK", .message.payload.len = 2, }; /* * MQTT PUBLISH msg: * DUP: 0, QoS: 1, Retain: 1, topic: sensors, message: OK, pkt_id: 1 * * Message can be generated by the following command: * mosquitto_pub -V mqttv311 -i zephyr -t sensors -q 1 -m "OK" -r */ static ZTEST_DMEM u8_t publish3[] = {0x33, 0x0d, 0x00, 0x07, 0x73, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x00, 0x01, 0x4f, 0x4b}; static ZTEST_DMEM struct mqtt_publish_param msg_publish3 = { .dup_flag = 0, .retain_flag = 1, .message_id = 1, .message.topic.qos = 1, .message.topic.topic = TOPIC, .message.payload.data = (u8_t *)"OK", .message.payload.len = 2, }; /* * MQTT PUBLISH msg: * DUP: 0, QoS: 2, Retain: 0, topic: sensors, message: OK, pkt_id: 1 * * Message can be generated by the following command: * mosquitto_pub -V mqttv311 -i zephyr -t sensors -q 2 -m "OK" */ static ZTEST_DMEM u8_t publish4[] = {0x34, 0x0d, 0x00, 0x07, 0x73, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x00, 0x01, 0x4f, 0x4b}; static ZTEST_DMEM struct mqtt_publish_param msg_publish4 = { .dup_flag = 0, .retain_flag = 0, .message_id = 1, .message.topic.qos = 2, .message.topic.topic = TOPIC, .message.payload.data = (u8_t *)"OK", .message.payload.len = 2, }; /* * MQTT SUBSCRIBE msg: * pkt_id: 1, topic: sensors, qos: 0 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -t sensors -q 0 */ static ZTEST_DMEM u8_t subscribe1[] = {0x82, 0x0c, 0x00, 0x01, 0x00, 0x07, 0x73, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x00}; static ZTEST_DMEM struct mqtt_subscription_list msg_subscribe1 = { .message_id = 1, .list_count = 1, .list = &topic_qos_0 }; /* * MQTT SUBSCRIBE msg: * pkt_id: 1, topic: sensors, qos: 1 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -t sensors -q 1 */ static ZTEST_DMEM u8_t subscribe2[] = {0x82, 0x0c, 0x00, 0x01, 0x00, 0x07, 0x73, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x01}; static ZTEST_DMEM struct mqtt_subscription_list msg_subscribe2 = { .message_id = 1, .list_count = 1, .list = &topic_qos_1 }; /* * MQTT SUBSCRIBE msg: * pkt_id: 1, topic: sensors, qos: 2 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -t sensors -q 2 */ static ZTEST_DMEM u8_t subscribe3[] = {0x82, 0x0c, 0x00, 0x01, 0x00, 0x07, 0x73, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x02}; static ZTEST_DMEM struct mqtt_subscription_list msg_subscribe3 = { .message_id = 1, .list_count = 1, .list = &topic_qos_2 }; /* * MQTT SUBACK msg * pkt_id: 1, qos: 0 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -t sensors -q 0 */ static ZTEST_DMEM u8_t suback1[] = {0x90, 0x03, 0x00, 0x01, 0x00}; static ZTEST_DMEM u8_t data_suback1[] = { MQTT_SUBACK_SUCCESS_QoS_0 }; static ZTEST_DMEM struct mqtt_suback_param msg_suback1 = { .message_id = 1, .return_codes.len = 1, .return_codes.data = data_suback1 }; /* * MQTT SUBACK message * pkt_id: 1, qos: 1 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -t sensors -q 1 */ static ZTEST_DMEM u8_t suback2[] = {0x90, 0x03, 0x00, 0x01, 0x01}; static ZTEST_DMEM u8_t data_suback2[] = { MQTT_SUBACK_SUCCESS_QoS_1 }; static ZTEST_DMEM struct mqtt_suback_param msg_suback2 = { .message_id = 1, .return_codes.len = 1, .return_codes.data = data_suback2 }; /* * MQTT SUBACK message * pkt_id: 1, qos: 2 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -t sensors -q 2 */ static ZTEST_DMEM u8_t suback3[] = {0x90, 0x03, 0x00, 0x01, 0x02}; static ZTEST_DMEM u8_t data_suback3[] = { MQTT_SUBACK_SUCCESS_QoS_2 }; static ZTEST_DMEM struct mqtt_suback_param msg_suback3 = { .message_id = 1, .return_codes.len = 1, .return_codes.data = data_suback3 }; static ZTEST_DMEM u8_t pingreq1[] = {0xc0, 0x00}; static ZTEST_DMEM u8_t puback1[] = {0x40, 0x02, 0x00, 0x01}; static ZTEST_DMEM struct mqtt_puback_param msg_puback1 = {.message_id = 1}; static ZTEST_DMEM u8_t pubrec1[] = {0x50, 0x02, 0x00, 0x01}; static ZTEST_DMEM struct mqtt_pubrec_param msg_pubrec1 = {.message_id = 1}; static ZTEST_DMEM u8_t pubrel1[] = {0x62, 0x02, 0x00, 0x01}; static ZTEST_DMEM struct mqtt_pubrel_param msg_pubrel1 = {.message_id = 1}; static ZTEST_DMEM u8_t pubcomp1[] = {0x70, 0x02, 0x00, 0x01}; static ZTEST_DMEM struct mqtt_pubcomp_param msg_pubcomp1 = {.message_id = 1}; static ZTEST_DMEM u8_t unsuback1[] = {0xb0, 0x02, 0x00, 0x01}; static ZTEST_DMEM struct mqtt_unsuback_param msg_unsuback1 = {.message_id = 1}; static ZTEST_DMEM struct mqtt_test mqtt_tests[] = { {.test_name = "CONNECT, new session, zeros", .ctx = &client_connect1, .eval_fcn = eval_msg_connect, .expected = connect1, .expected_len = sizeof(connect1)}, {.test_name = "CONNECT, new session, will", .ctx = &client_connect2, .eval_fcn = eval_msg_connect, .expected = connect2, .expected_len = sizeof(connect2)}, {.test_name = "CONNECT, new session, will retain", .ctx = &client_connect3, .eval_fcn = eval_msg_connect, .expected = connect3, .expected_len = sizeof(connect3)}, {.test_name = "CONNECT, new session, will qos = 1", .ctx = &client_connect4, .eval_fcn = eval_msg_connect, .expected = connect4, .expected_len = sizeof(connect4)}, {.test_name = "CONNECT, new session, will qos = 1, will retain", .ctx = &client_connect5, .eval_fcn = eval_msg_connect, .expected = connect5, .expected_len = sizeof(connect5)}, {.test_name = "CONNECT, new session, username and password", .ctx = &client_connect6, .eval_fcn = eval_msg_connect, .expected = connect6, .expected_len = sizeof(connect6)}, {.test_name = "DISCONNECT", .ctx = NULL, .eval_fcn = eval_msg_disconnect, .expected = disconnect1, .expected_len = sizeof(disconnect1)}, {.test_name = "PUBLISH, qos = 0", .ctx = &msg_publish1, .eval_fcn = eval_msg_publish, .expected = publish1, .expected_len = sizeof(publish1)}, {.test_name = "PUBLISH, retain = 1", .ctx = &msg_publish2, .eval_fcn = eval_msg_publish, .expected = publish2, .expected_len = sizeof(publish2)}, {.test_name = "PUBLISH, retain = 1, qos = 1", .ctx = &msg_publish3, .eval_fcn = eval_msg_publish, .expected = publish3, .expected_len = sizeof(publish3)}, {.test_name = "PUBLISH, qos = 2", .ctx = &msg_publish4, .eval_fcn = eval_msg_publish, .expected = publish4, .expected_len = sizeof(publish4)}, {.test_name = "SUBSCRIBE, one topic, qos = 0", .ctx = &msg_subscribe1, .eval_fcn = eval_msg_subscribe, .expected = subscribe1, .expected_len = sizeof(subscribe1)}, {.test_name = "SUBSCRIBE, one topic, qos = 1", .ctx = &msg_subscribe2, .eval_fcn = eval_msg_subscribe, .expected = subscribe2, .expected_len = sizeof(subscribe2)}, {.test_name = "SUBSCRIBE, one topic, qos = 2", .ctx = &msg_subscribe3, .eval_fcn = eval_msg_subscribe, .expected = subscribe3, .expected_len = sizeof(subscribe3)}, {.test_name = "SUBACK, one topic, qos = 0", .ctx = &msg_suback1, .eval_fcn = eval_msg_suback, .expected = suback1, .expected_len = sizeof(suback1)}, {.test_name = "SUBACK, one topic, qos = 1", .ctx = &msg_suback2, .eval_fcn = eval_msg_suback, .expected = suback2, .expected_len = sizeof(suback2)}, {.test_name = "SUBACK, one topic, qos = 2", .ctx = &msg_suback3, .eval_fcn = eval_msg_suback, .expected = suback3, .expected_len = sizeof(suback3)}, {.test_name = "PINGREQ", .ctx = NULL, .eval_fcn = eval_msg_pingreq, .expected = pingreq1, .expected_len = sizeof(pingreq1)}, {.test_name = "PUBACK", .ctx = &msg_puback1, .eval_fcn = eval_msg_puback, .expected = puback1, .expected_len = sizeof(puback1)}, {.test_name = "PUBREC", .ctx = &msg_pubrec1, .eval_fcn = eval_msg_pubrec, .expected = pubrec1, .expected_len = sizeof(pubrec1)}, {.test_name = "PUBREL", .ctx = &msg_pubrel1, .eval_fcn = eval_msg_pubrel, .expected = pubrel1, .expected_len = sizeof(pubrel1)}, {.test_name = "PUBCOMP", .ctx = &msg_pubcomp1, .eval_fcn = eval_msg_pubcomp, .expected = pubcomp1, .expected_len = sizeof(pubcomp1)}, {.test_name = "UNSUBACK", .ctx = &msg_unsuback1, .eval_fcn = eval_msg_unsuback, .expected = unsuback1, .expected_len = sizeof(unsuback1)}, /* last test case, do not remove it */ {.test_name = NULL} }; static void print_array(const u8_t *a, u16_t size) { u16_t i; TC_PRINT("\n"); for (i = 0U; i < size; i++) { TC_PRINT("%x ", a[i]); if ((i+1) % 8 == 0U) { TC_PRINT("\n"); } } TC_PRINT("\n"); } static int eval_buffers(const struct buf_ctx *buf, const u8_t *expected, u16_t len) { if (buf->end - buf->cur != len) { goto exit_eval; } if (memcmp(expected, buf->cur, buf->end - buf->cur) != 0) { goto exit_eval; } return TC_PASS; exit_eval: TC_PRINT("FAIL\n"); TC_PRINT("Computed:"); print_array(buf->cur, buf->end - buf->cur); TC_PRINT("Expected:"); print_array(expected, len); return TC_FAIL; } static int eval_msg_connect(struct mqtt_test *mqtt_test) { struct mqtt_client *test_client; int rc; struct buf_ctx buf; test_client = (struct mqtt_client *)mqtt_test->ctx; client.clean_session = test_client->clean_session; client.client_id = test_client->client_id; client.will_topic = test_client->will_topic; client.will_retain = test_client->will_retain; client.will_message = test_client->will_message; client.user_name = test_client->user_name; client.password = test_client->password; buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = connect_request_encode(&client, &buf); /**TESTPOINTS: Check connect_request_encode functions*/ zassert_false(rc, "connect_request_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); return TC_PASS; } static int eval_msg_disconnect(struct mqtt_test *mqtt_test) { int rc; struct buf_ctx buf; buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = disconnect_encode(&buf); /**TESTPOINTS: Check disconnect_encode functions*/ zassert_false(rc, "disconnect_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); return TC_PASS; } static int eval_msg_publish(struct mqtt_test *mqtt_test) { struct mqtt_publish_param *param = (struct mqtt_publish_param *)mqtt_test->ctx; struct mqtt_publish_param dec_param; int rc; u8_t type_and_flags; u32_t length; struct buf_ctx buf; memset(&dec_param, 0, sizeof(dec_param)); buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = publish_encode(param, &buf); /* Payload is not copied, copy it manually just after the header.*/ memcpy(buf.end, param->message.payload.data, param->message.payload.len); buf.end += param->message.payload.len; /**TESTPOINT: Check publish_encode function*/ zassert_false(rc, "publish_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); rc = fixed_header_decode(&buf, &type_and_flags, &length); zassert_false(rc, "fixed_header_decode failed"); rc = publish_decode(type_and_flags, length, &buf, &dec_param); /**TESTPOINT: Check publish_decode function*/ zassert_false(rc, "publish_decode failed"); zassert_equal(dec_param.message_id, param->message_id, "message_id error"); zassert_equal(dec_param.dup_flag, param->dup_flag, "dup flag error"); zassert_equal(dec_param.retain_flag, param->retain_flag, "retain flag error"); zassert_equal(dec_param.message.topic.qos, param->message.topic.qos, "topic qos error"); zassert_equal(dec_param.message.topic.topic.size, param->message.topic.topic.size, "topic len error"); if (memcmp(dec_param.message.topic.topic.utf8, param->message.topic.topic.utf8, dec_param.message.topic.topic.size) != 0) { zassert_unreachable("topic content error"); } zassert_equal(dec_param.message.payload.len, param->message.payload.len, "payload len error"); return TC_PASS; } static int eval_msg_subscribe(struct mqtt_test *mqtt_test) { struct mqtt_subscription_list *param = (struct mqtt_subscription_list *)mqtt_test->ctx; int rc; struct buf_ctx buf; buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = subscribe_encode(param, &buf); /**TESTPOINT: Check subscribe_encode function*/ zassert_false(rc, "subscribe_encode failed"); return eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); } static int eval_msg_suback(struct mqtt_test *mqtt_test) { struct mqtt_suback_param *param = (struct mqtt_suback_param *)mqtt_test->ctx; struct mqtt_suback_param dec_param; int rc; u8_t type_and_flags; u32_t length; struct buf_ctx buf; buf.cur = mqtt_test->expected; buf.end = mqtt_test->expected + mqtt_test->expected_len; memset(&dec_param, 0, sizeof(dec_param)); rc = fixed_header_decode(&buf, &type_and_flags, &length); zassert_false(rc, "fixed_header_decode failed"); rc = subscribe_ack_decode(&buf, &dec_param); /**TESTPOINT: Check subscribe_ack_decode function*/ zassert_false(rc, "subscribe_ack_decode failed"); zassert_equal(dec_param.message_id, param->message_id, "packet identifier error"); zassert_equal(dec_param.return_codes.len, param->return_codes.len, "topic count error"); if (memcmp(dec_param.return_codes.data, param->return_codes.data, dec_param.return_codes.len) != 0) { zassert_unreachable("subscribe result error"); } return TC_PASS; } static int eval_msg_pingreq(struct mqtt_test *mqtt_test) { int rc; struct buf_ctx buf; buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = ping_request_encode(&buf); /**TESTPOINTS: Check eval_msg_pingreq functions*/ zassert_false(rc, "ping_request_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); return TC_PASS; } static int eval_msg_puback(struct mqtt_test *mqtt_test) { struct mqtt_puback_param *param = (struct mqtt_puback_param *)mqtt_test->ctx; struct mqtt_puback_param dec_param; int rc; u8_t type_and_flags; u32_t length; struct buf_ctx buf; memset(&dec_param, 0, sizeof(dec_param)); buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = publish_ack_encode(param, &buf); /**TESTPOINTS: Check publish_ack_encode functions*/ zassert_false(rc, "publish_ack_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); rc = fixed_header_decode(&buf, &type_and_flags, &length); zassert_false(rc, "fixed_header_decode failed"); rc = publish_ack_decode(&buf, &dec_param); zassert_false(rc, "publish_ack_decode failed"); zassert_equal(dec_param.message_id, param->message_id, "packet identifier error"); return TC_PASS; } static int eval_msg_pubcomp(struct mqtt_test *mqtt_test) { struct mqtt_pubcomp_param *param = (struct mqtt_pubcomp_param *)mqtt_test->ctx; struct mqtt_pubcomp_param dec_param; int rc; u32_t length; u8_t type_and_flags; struct buf_ctx buf; memset(&dec_param, 0, sizeof(dec_param)); buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = publish_complete_encode(param, &buf); /**TESTPOINTS: Check publish_complete_encode functions*/ zassert_false(rc, "publish_complete_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); rc = fixed_header_decode(&buf, &type_and_flags, &length); zassert_false(rc, "fixed_header_decode failed"); rc = publish_complete_decode(&buf, &dec_param); zassert_false(rc, "publish_complete_decode failed"); zassert_equal(dec_param.message_id, param->message_id, "packet identifier error"); return TC_PASS; } static int eval_msg_pubrec(struct mqtt_test *mqtt_test) { struct mqtt_pubrec_param *param = (struct mqtt_pubrec_param *)mqtt_test->ctx; struct mqtt_pubrec_param dec_param; int rc; u32_t length; u8_t type_and_flags; struct buf_ctx buf; memset(&dec_param, 0, sizeof(dec_param)); buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = publish_receive_encode(param, &buf); /**TESTPOINTS: Check publish_receive_encode functions*/ zassert_false(rc, "publish_receive_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); rc = fixed_header_decode(&buf, &type_and_flags, &length); zassert_false(rc, "fixed_header_decode failed"); rc = publish_receive_decode(&buf, &dec_param); zassert_false(rc, "publish_receive_decode failed"); zassert_equal(dec_param.message_id, param->message_id, "packet identifier error"); return TC_PASS; } static int eval_msg_pubrel(struct mqtt_test *mqtt_test) { struct mqtt_pubrel_param *param = (struct mqtt_pubrel_param *)mqtt_test->ctx; struct mqtt_pubrel_param dec_param; int rc; u32_t length; u8_t type_and_flags; struct buf_ctx buf; memset(&dec_param, 0, sizeof(dec_param)); buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = publish_release_encode(param, &buf); /**TESTPOINTS: Check publish_release_encode functions*/ zassert_false(rc, "publish_release_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); rc = fixed_header_decode(&buf, &type_and_flags, &length); zassert_false(rc, "fixed_header_decode failed"); rc = publish_release_decode(&buf, &dec_param); zassert_false(rc, "publish_release_decode failed"); zassert_equal(dec_param.message_id, param->message_id, "packet identifier error"); return TC_PASS; } static int eval_msg_unsuback(struct mqtt_test *mqtt_test) { struct mqtt_unsuback_param *param = (struct mqtt_unsuback_param *)mqtt_test->ctx; struct mqtt_unsuback_param dec_param; int rc; u32_t length; u8_t type_and_flags; struct buf_ctx buf; memset(&dec_param, 0, sizeof(dec_param)); buf.cur = mqtt_test->expected; buf.end = mqtt_test->expected + mqtt_test->expected_len; rc = fixed_header_decode(&buf, &type_and_flags, &length); zassert_false(rc, "fixed_header_decode failed"); rc = unsubscribe_ack_decode(&buf, &dec_param); zassert_false(rc, "unsubscribe_ack_decode failed"); zassert_equal(dec_param.message_id, param->message_id, "packet identifier error"); return TC_PASS; } void test_mqtt_packet(void) { TC_START("MQTT Library test"); int rc; int i; mqtt_client_init(&client); client.protocol_version = MQTT_VERSION_3_1_1; client.rx_buf = rx_buffer; client.rx_buf_size = sizeof(rx_buffer); client.tx_buf = tx_buffer; client.tx_buf_size = sizeof(tx_buffer); i = 0; do { struct mqtt_test *test = &mqtt_tests[i]; if (test->test_name == NULL) { break; } rc = test->eval_fcn(test); TC_PRINT("[%s] %d - %s\n", TC_RESULT_TO_STR(rc), i + 1, test->test_name); /**TESTPOINT: Check eval_fcn*/ zassert_false(rc, "mqtt_packet test error"); i++; } while (1); mqtt_abort(&client); } void test_main(void) { ztest_test_suite(test_mqtt_packet_fn, ztest_user_unit_test(test_mqtt_packet)); ztest_run_test_suite(test_mqtt_packet_fn); }
./CrossVul/dataset_final_sorted/CWE-193/c/bad_3860_1
crossvul-cpp_data_bad_3860_0
/* * Copyright (c) 2018 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ /** @file mqtt_decoder.c * * @brief Decoder functions needed for decoding packets received from the * broker. */ #include <logging/log.h> LOG_MODULE_REGISTER(net_mqtt_dec, CONFIG_MQTT_LOG_LEVEL); #include "mqtt_internal.h" #include "mqtt_os.h" /** * @brief Unpacks unsigned 8 bit value from the buffer from the offset * requested. * * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] val Memory where the value is to be unpacked. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the buffer would be exceeded during the read */ static int unpack_uint8(struct buf_ctx *buf, u8_t *val) { MQTT_TRC(">> cur:%p, end:%p", buf->cur, buf->end); if ((buf->end - buf->cur) < sizeof(u8_t)) { return -EINVAL; } *val = *(buf->cur++); MQTT_TRC("<< val:%02x", *val); return 0; } /** * @brief Unpacks unsigned 16 bit value from the buffer from the offset * requested. * * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] val Memory where the value is to be unpacked. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the buffer would be exceeded during the read */ static int unpack_uint16(struct buf_ctx *buf, u16_t *val) { MQTT_TRC(">> cur:%p, end:%p", buf->cur, buf->end); if ((buf->end - buf->cur) < sizeof(u16_t)) { return -EINVAL; } *val = *(buf->cur++) << 8; /* MSB */ *val |= *(buf->cur++); /* LSB */ MQTT_TRC("<< val:%04x", *val); return 0; } /** * @brief Unpacks utf8 string from the buffer from the offset requested. * * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] str Pointer to a string that will hold the string location * in the buffer. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the buffer would be exceeded during the read */ static int unpack_utf8_str(struct buf_ctx *buf, struct mqtt_utf8 *str) { u16_t utf8_strlen; int err_code; MQTT_TRC(">> cur:%p, end:%p", buf->cur, buf->end); err_code = unpack_uint16(buf, &utf8_strlen); if (err_code != 0) { return err_code; } if ((buf->end - buf->cur) < utf8_strlen) { return -EINVAL; } str->size = utf8_strlen; /* Zero length UTF8 strings permitted. */ if (utf8_strlen) { /* Point to right location in buffer. */ str->utf8 = buf->cur; buf->cur += utf8_strlen; } else { str->utf8 = NULL; } MQTT_TRC("<< str_size:%08x", (u32_t)GET_UT8STR_BUFFER_SIZE(str)); return 0; } /** * @brief Unpacks binary string from the buffer from the offset requested. * * @param[in] length Binary string length. * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] str Pointer to a binary string that will hold the binary string * location in the buffer. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the buffer would be exceeded during the read */ static int unpack_data(u32_t length, struct buf_ctx *buf, struct mqtt_binstr *str) { MQTT_TRC(">> cur:%p, end:%p", buf->cur, buf->end); if ((buf->end - buf->cur) < length) { return -EINVAL; } str->len = length; /* Zero length binary strings are permitted. */ if (length > 0) { str->data = buf->cur; buf->cur += length; } else { str->data = NULL; } MQTT_TRC("<< bin len:%08x", GET_BINSTR_BUFFER_SIZE(str)); return 0; } /**@brief Decode MQTT Packet Length in the MQTT fixed header. * * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] length Length of variable header and payload in the * MQTT message. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the length decoding would use more that 4 bytes. * @retval -EAGAIN if the buffer would be exceeded during the read. */ int packet_length_decode(struct buf_ctx *buf, u32_t *length) { u8_t shift = 0U; u8_t bytes = 0U; *length = 0U; do { if (bytes > MQTT_MAX_LENGTH_BYTES) { return -EINVAL; } if (buf->cur >= buf->end) { return -EAGAIN; } *length += ((u32_t)*(buf->cur) & MQTT_LENGTH_VALUE_MASK) << shift; shift += MQTT_LENGTH_SHIFT; bytes++; } while ((*(buf->cur++) & MQTT_LENGTH_CONTINUATION_BIT) != 0U); MQTT_TRC("length:0x%08x", *length); return 0; } int fixed_header_decode(struct buf_ctx *buf, u8_t *type_and_flags, u32_t *length) { int err_code; err_code = unpack_uint8(buf, type_and_flags); if (err_code != 0) { return err_code; } return packet_length_decode(buf, length); } int connect_ack_decode(const struct mqtt_client *client, struct buf_ctx *buf, struct mqtt_connack_param *param) { int err_code; u8_t flags, ret_code; err_code = unpack_uint8(buf, &flags); if (err_code != 0) { return err_code; } err_code = unpack_uint8(buf, &ret_code); if (err_code != 0) { return err_code; } if (client->protocol_version == MQTT_VERSION_3_1_1) { param->session_present_flag = flags & MQTT_CONNACK_FLAG_SESSION_PRESENT; MQTT_TRC("[CID %p]: session_present_flag: %d", client, param->session_present_flag); } param->return_code = (enum mqtt_conn_return_code)ret_code; return 0; } int publish_decode(u8_t flags, u32_t var_length, struct buf_ctx *buf, struct mqtt_publish_param *param) { int err_code; u32_t var_header_length; param->dup_flag = flags & MQTT_HEADER_DUP_MASK; param->retain_flag = flags & MQTT_HEADER_RETAIN_MASK; param->message.topic.qos = ((flags & MQTT_HEADER_QOS_MASK) >> 1); err_code = unpack_utf8_str(buf, &param->message.topic.topic); if (err_code != 0) { return err_code; } var_header_length = param->message.topic.topic.size + sizeof(u16_t); if (param->message.topic.qos > MQTT_QOS_0_AT_MOST_ONCE) { err_code = unpack_uint16(buf, &param->message_id); if (err_code != 0) { return err_code; } var_header_length += sizeof(u16_t); } param->message.payload.data = NULL; param->message.payload.len = var_length - var_header_length; return 0; } int publish_ack_decode(struct buf_ctx *buf, struct mqtt_puback_param *param) { return unpack_uint16(buf, &param->message_id); } int publish_receive_decode(struct buf_ctx *buf, struct mqtt_pubrec_param *param) { return unpack_uint16(buf, &param->message_id); } int publish_release_decode(struct buf_ctx *buf, struct mqtt_pubrel_param *param) { return unpack_uint16(buf, &param->message_id); } int publish_complete_decode(struct buf_ctx *buf, struct mqtt_pubcomp_param *param) { return unpack_uint16(buf, &param->message_id); } int subscribe_ack_decode(struct buf_ctx *buf, struct mqtt_suback_param *param) { int err_code; err_code = unpack_uint16(buf, &param->message_id); if (err_code != 0) { return err_code; } return unpack_data(buf->end - buf->cur, buf, &param->return_codes); } int unsubscribe_ack_decode(struct buf_ctx *buf, struct mqtt_unsuback_param *param) { return unpack_uint16(buf, &param->message_id); }
./CrossVul/dataset_final_sorted/CWE-193/c/bad_3860_0
crossvul-cpp_data_good_2801_0
/*- * Copyright (c) 2003-2007 Tim Kientzle * Copyright (c) 2011 Andres Mejia * 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(S) ``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(S) 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 "archive_platform.h" #ifdef HAVE_ERRNO_H #include <errno.h> #endif #include <time.h> #include <limits.h> #ifdef HAVE_ZLIB_H #include <zlib.h> /* crc32 */ #endif #include "archive.h" #ifndef HAVE_ZLIB_H #include "archive_crc32.h" #endif #include "archive_endian.h" #include "archive_entry.h" #include "archive_entry_locale.h" #include "archive_ppmd7_private.h" #include "archive_private.h" #include "archive_read_private.h" /* RAR signature, also known as the mark header */ #define RAR_SIGNATURE "\x52\x61\x72\x21\x1A\x07\x00" /* Header types */ #define MARK_HEAD 0x72 #define MAIN_HEAD 0x73 #define FILE_HEAD 0x74 #define COMM_HEAD 0x75 #define AV_HEAD 0x76 #define SUB_HEAD 0x77 #define PROTECT_HEAD 0x78 #define SIGN_HEAD 0x79 #define NEWSUB_HEAD 0x7a #define ENDARC_HEAD 0x7b /* Main Header Flags */ #define MHD_VOLUME 0x0001 #define MHD_COMMENT 0x0002 #define MHD_LOCK 0x0004 #define MHD_SOLID 0x0008 #define MHD_NEWNUMBERING 0x0010 #define MHD_AV 0x0020 #define MHD_PROTECT 0x0040 #define MHD_PASSWORD 0x0080 #define MHD_FIRSTVOLUME 0x0100 #define MHD_ENCRYPTVER 0x0200 /* Flags common to all headers */ #define HD_MARKDELETION 0x4000 #define HD_ADD_SIZE_PRESENT 0x8000 /* File Header Flags */ #define FHD_SPLIT_BEFORE 0x0001 #define FHD_SPLIT_AFTER 0x0002 #define FHD_PASSWORD 0x0004 #define FHD_COMMENT 0x0008 #define FHD_SOLID 0x0010 #define FHD_LARGE 0x0100 #define FHD_UNICODE 0x0200 #define FHD_SALT 0x0400 #define FHD_VERSION 0x0800 #define FHD_EXTTIME 0x1000 #define FHD_EXTFLAGS 0x2000 /* File dictionary sizes */ #define DICTIONARY_SIZE_64 0x00 #define DICTIONARY_SIZE_128 0x20 #define DICTIONARY_SIZE_256 0x40 #define DICTIONARY_SIZE_512 0x60 #define DICTIONARY_SIZE_1024 0x80 #define DICTIONARY_SIZE_2048 0xA0 #define DICTIONARY_SIZE_4096 0xC0 #define FILE_IS_DIRECTORY 0xE0 #define DICTIONARY_MASK FILE_IS_DIRECTORY /* OS Flags */ #define OS_MSDOS 0 #define OS_OS2 1 #define OS_WIN32 2 #define OS_UNIX 3 #define OS_MAC_OS 4 #define OS_BEOS 5 /* Compression Methods */ #define COMPRESS_METHOD_STORE 0x30 /* LZSS */ #define COMPRESS_METHOD_FASTEST 0x31 #define COMPRESS_METHOD_FAST 0x32 #define COMPRESS_METHOD_NORMAL 0x33 /* PPMd Variant H */ #define COMPRESS_METHOD_GOOD 0x34 #define COMPRESS_METHOD_BEST 0x35 #define CRC_POLYNOMIAL 0xEDB88320 #define NS_UNIT 10000000 #define DICTIONARY_MAX_SIZE 0x400000 #define MAINCODE_SIZE 299 #define OFFSETCODE_SIZE 60 #define LOWOFFSETCODE_SIZE 17 #define LENGTHCODE_SIZE 28 #define HUFFMAN_TABLE_SIZE \ MAINCODE_SIZE + OFFSETCODE_SIZE + LOWOFFSETCODE_SIZE + LENGTHCODE_SIZE #define MAX_SYMBOL_LENGTH 0xF #define MAX_SYMBOLS 20 /* * Considering L1,L2 cache miss and a calling of write system-call, * the best size of the output buffer(uncompressed buffer) is 128K. * If the structure of extracting process is changed, this value * might be researched again. */ #define UNP_BUFFER_SIZE (128 * 1024) /* Define this here for non-Windows platforms */ #if !((defined(__WIN32__) || defined(_WIN32) || defined(__WIN32)) && !defined(__CYGWIN__)) #define FILE_ATTRIBUTE_DIRECTORY 0x10 #endif /* Fields common to all headers */ struct rar_header { char crc[2]; char type; char flags[2]; char size[2]; }; /* Fields common to all file headers */ struct rar_file_header { char pack_size[4]; char unp_size[4]; char host_os; char file_crc[4]; char file_time[4]; char unp_ver; char method; char name_size[2]; char file_attr[4]; }; struct huffman_tree_node { int branches[2]; }; struct huffman_table_entry { unsigned int length; int value; }; struct huffman_code { struct huffman_tree_node *tree; int numentries; int numallocatedentries; int minlength; int maxlength; int tablesize; struct huffman_table_entry *table; }; struct lzss { unsigned char *window; int mask; int64_t position; }; struct data_block_offsets { int64_t header_size; int64_t start_offset; int64_t end_offset; }; struct rar { /* Entries from main RAR header */ unsigned main_flags; unsigned long file_crc; char reserved1[2]; char reserved2[4]; char encryptver; /* File header entries */ char compression_method; unsigned file_flags; int64_t packed_size; int64_t unp_size; time_t mtime; long mnsec; mode_t mode; char *filename; char *filename_save; size_t filename_save_size; size_t filename_allocated; /* File header optional entries */ char salt[8]; time_t atime; long ansec; time_t ctime; long cnsec; time_t arctime; long arcnsec; /* Fields to help with tracking decompression of files. */ int64_t bytes_unconsumed; int64_t bytes_remaining; int64_t bytes_uncopied; int64_t offset; int64_t offset_outgoing; int64_t offset_seek; char valid; unsigned int unp_offset; unsigned int unp_buffer_size; unsigned char *unp_buffer; unsigned int dictionary_size; char start_new_block; char entry_eof; unsigned long crc_calculated; int found_first_header; char has_endarc_header; struct data_block_offsets *dbo; unsigned int cursor; unsigned int nodes; /* LZSS members */ struct huffman_code maincode; struct huffman_code offsetcode; struct huffman_code lowoffsetcode; struct huffman_code lengthcode; unsigned char lengthtable[HUFFMAN_TABLE_SIZE]; struct lzss lzss; char output_last_match; unsigned int lastlength; unsigned int lastoffset; unsigned int oldoffset[4]; unsigned int lastlowoffset; unsigned int numlowoffsetrepeats; int64_t filterstart; char start_new_table; /* PPMd Variant H members */ char ppmd_valid; char ppmd_eod; char is_ppmd_block; int ppmd_escape; CPpmd7 ppmd7_context; CPpmd7z_RangeDec range_dec; IByteIn bytein; /* * String conversion object. */ int init_default_conversion; struct archive_string_conv *sconv_default; struct archive_string_conv *opt_sconv; struct archive_string_conv *sconv_utf8; struct archive_string_conv *sconv_utf16be; /* * Bit stream reader. */ struct rar_br { #define CACHE_TYPE uint64_t #define CACHE_BITS (8 * sizeof(CACHE_TYPE)) /* Cache buffer. */ CACHE_TYPE cache_buffer; /* Indicates how many bits avail in cache_buffer. */ int cache_avail; ssize_t avail_in; const unsigned char *next_in; } br; /* * Custom field to denote that this archive contains encrypted entries */ int has_encrypted_entries; }; static int archive_read_support_format_rar_capabilities(struct archive_read *); static int archive_read_format_rar_has_encrypted_entries(struct archive_read *); static int archive_read_format_rar_bid(struct archive_read *, int); static int archive_read_format_rar_options(struct archive_read *, const char *, const char *); static int archive_read_format_rar_read_header(struct archive_read *, struct archive_entry *); static int archive_read_format_rar_read_data(struct archive_read *, const void **, size_t *, int64_t *); static int archive_read_format_rar_read_data_skip(struct archive_read *a); static int64_t archive_read_format_rar_seek_data(struct archive_read *, int64_t, int); static int archive_read_format_rar_cleanup(struct archive_read *); /* Support functions */ static int read_header(struct archive_read *, struct archive_entry *, char); static time_t get_time(int); static int read_exttime(const char *, struct rar *, const char *); static int read_symlink_stored(struct archive_read *, struct archive_entry *, struct archive_string_conv *); static int read_data_stored(struct archive_read *, const void **, size_t *, int64_t *); static int read_data_compressed(struct archive_read *, const void **, size_t *, int64_t *); static int rar_br_preparation(struct archive_read *, struct rar_br *); static int parse_codes(struct archive_read *); static void free_codes(struct archive_read *); static int read_next_symbol(struct archive_read *, struct huffman_code *); static int create_code(struct archive_read *, struct huffman_code *, unsigned char *, int, char); static int add_value(struct archive_read *, struct huffman_code *, int, int, int); static int new_node(struct huffman_code *); static int make_table(struct archive_read *, struct huffman_code *); static int make_table_recurse(struct archive_read *, struct huffman_code *, int, struct huffman_table_entry *, int, int); static int64_t expand(struct archive_read *, int64_t); static int copy_from_lzss_window(struct archive_read *, const void **, int64_t, int); static const void *rar_read_ahead(struct archive_read *, size_t, ssize_t *); /* * Bit stream reader. */ /* Check that the cache buffer has enough bits. */ #define rar_br_has(br, n) ((br)->cache_avail >= n) /* Get compressed data by bit. */ #define rar_br_bits(br, n) \ (((uint32_t)((br)->cache_buffer >> \ ((br)->cache_avail - (n)))) & cache_masks[n]) #define rar_br_bits_forced(br, n) \ (((uint32_t)((br)->cache_buffer << \ ((n) - (br)->cache_avail))) & cache_masks[n]) /* Read ahead to make sure the cache buffer has enough compressed data we * will use. * True : completed, there is enough data in the cache buffer. * False : there is no data in the stream. */ #define rar_br_read_ahead(a, br, n) \ ((rar_br_has(br, (n)) || rar_br_fillup(a, br)) || rar_br_has(br, (n))) /* Notify how many bits we consumed. */ #define rar_br_consume(br, n) ((br)->cache_avail -= (n)) #define rar_br_consume_unalined_bits(br) ((br)->cache_avail &= ~7) static const uint32_t cache_masks[] = { 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF, 0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF, 0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }; /* * Shift away used bits in the cache data and fill it up with following bits. * Call this when cache buffer does not have enough bits you need. * * Returns 1 if the cache buffer is full. * Returns 0 if the cache buffer is not full; input buffer is empty. */ static int rar_br_fillup(struct archive_read *a, struct rar_br *br) { struct rar *rar = (struct rar *)(a->format->data); int n = CACHE_BITS - br->cache_avail; for (;;) { switch (n >> 3) { case 8: if (br->avail_in >= 8) { br->cache_buffer = ((uint64_t)br->next_in[0]) << 56 | ((uint64_t)br->next_in[1]) << 48 | ((uint64_t)br->next_in[2]) << 40 | ((uint64_t)br->next_in[3]) << 32 | ((uint32_t)br->next_in[4]) << 24 | ((uint32_t)br->next_in[5]) << 16 | ((uint32_t)br->next_in[6]) << 8 | (uint32_t)br->next_in[7]; br->next_in += 8; br->avail_in -= 8; br->cache_avail += 8 * 8; rar->bytes_unconsumed += 8; rar->bytes_remaining -= 8; return (1); } break; case 7: if (br->avail_in >= 7) { br->cache_buffer = (br->cache_buffer << 56) | ((uint64_t)br->next_in[0]) << 48 | ((uint64_t)br->next_in[1]) << 40 | ((uint64_t)br->next_in[2]) << 32 | ((uint32_t)br->next_in[3]) << 24 | ((uint32_t)br->next_in[4]) << 16 | ((uint32_t)br->next_in[5]) << 8 | (uint32_t)br->next_in[6]; br->next_in += 7; br->avail_in -= 7; br->cache_avail += 7 * 8; rar->bytes_unconsumed += 7; rar->bytes_remaining -= 7; return (1); } break; case 6: if (br->avail_in >= 6) { br->cache_buffer = (br->cache_buffer << 48) | ((uint64_t)br->next_in[0]) << 40 | ((uint64_t)br->next_in[1]) << 32 | ((uint32_t)br->next_in[2]) << 24 | ((uint32_t)br->next_in[3]) << 16 | ((uint32_t)br->next_in[4]) << 8 | (uint32_t)br->next_in[5]; br->next_in += 6; br->avail_in -= 6; br->cache_avail += 6 * 8; rar->bytes_unconsumed += 6; rar->bytes_remaining -= 6; return (1); } break; case 0: /* We have enough compressed data in * the cache buffer.*/ return (1); default: break; } if (br->avail_in <= 0) { if (rar->bytes_unconsumed > 0) { /* Consume as much as the decompressor * actually used. */ __archive_read_consume(a, rar->bytes_unconsumed); rar->bytes_unconsumed = 0; } br->next_in = rar_read_ahead(a, 1, &(br->avail_in)); if (br->next_in == NULL) return (0); if (br->avail_in == 0) return (0); } br->cache_buffer = (br->cache_buffer << 8) | *br->next_in++; br->avail_in--; br->cache_avail += 8; n -= 8; rar->bytes_unconsumed++; rar->bytes_remaining--; } } static int rar_br_preparation(struct archive_read *a, struct rar_br *br) { struct rar *rar = (struct rar *)(a->format->data); if (rar->bytes_remaining > 0) { br->next_in = rar_read_ahead(a, 1, &(br->avail_in)); if (br->next_in == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); return (ARCHIVE_FATAL); } if (br->cache_avail == 0) (void)rar_br_fillup(a, br); } return (ARCHIVE_OK); } /* Find last bit set */ static inline int rar_fls(unsigned int word) { word |= (word >> 1); word |= (word >> 2); word |= (word >> 4); word |= (word >> 8); word |= (word >> 16); return word - (word >> 1); } /* LZSS functions */ static inline int64_t lzss_position(struct lzss *lzss) { return lzss->position; } static inline int lzss_mask(struct lzss *lzss) { return lzss->mask; } static inline int lzss_size(struct lzss *lzss) { return lzss->mask + 1; } static inline int lzss_offset_for_position(struct lzss *lzss, int64_t pos) { return (int)(pos & lzss->mask); } static inline unsigned char * lzss_pointer_for_position(struct lzss *lzss, int64_t pos) { return &lzss->window[lzss_offset_for_position(lzss, pos)]; } static inline int lzss_current_offset(struct lzss *lzss) { return lzss_offset_for_position(lzss, lzss->position); } static inline uint8_t * lzss_current_pointer(struct lzss *lzss) { return lzss_pointer_for_position(lzss, lzss->position); } static inline void lzss_emit_literal(struct rar *rar, uint8_t literal) { *lzss_current_pointer(&rar->lzss) = literal; rar->lzss.position++; } static inline void lzss_emit_match(struct rar *rar, int offset, int length) { int dstoffs = lzss_current_offset(&rar->lzss); int srcoffs = (dstoffs - offset) & lzss_mask(&rar->lzss); int l, li, remaining; unsigned char *d, *s; remaining = length; while (remaining > 0) { l = remaining; if (dstoffs > srcoffs) { if (l > lzss_size(&rar->lzss) - dstoffs) l = lzss_size(&rar->lzss) - dstoffs; } else { if (l > lzss_size(&rar->lzss) - srcoffs) l = lzss_size(&rar->lzss) - srcoffs; } d = &(rar->lzss.window[dstoffs]); s = &(rar->lzss.window[srcoffs]); if ((dstoffs + l < srcoffs) || (srcoffs + l < dstoffs)) memcpy(d, s, l); else { for (li = 0; li < l; li++) d[li] = s[li]; } remaining -= l; dstoffs = (dstoffs + l) & lzss_mask(&(rar->lzss)); srcoffs = (srcoffs + l) & lzss_mask(&(rar->lzss)); } rar->lzss.position += length; } static void * ppmd_alloc(void *p, size_t size) { (void)p; return malloc(size); } static void ppmd_free(void *p, void *address) { (void)p; free(address); } static ISzAlloc g_szalloc = { ppmd_alloc, ppmd_free }; static Byte ppmd_read(void *p) { struct archive_read *a = ((IByteIn*)p)->a; struct rar *rar = (struct rar *)(a->format->data); struct rar_br *br = &(rar->br); Byte b; if (!rar_br_read_ahead(a, br, 8)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return 0; } b = rar_br_bits(br, 8); rar_br_consume(br, 8); return b; } int archive_read_support_format_rar(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; struct rar *rar; int r; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_support_format_rar"); rar = (struct rar *)calloc(sizeof(*rar), 1); if (rar == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate rar data"); return (ARCHIVE_FATAL); } /* * Until enough data has been read, we cannot tell about * any encrypted entries yet. */ rar->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; r = __archive_read_register_format(a, rar, "rar", archive_read_format_rar_bid, archive_read_format_rar_options, archive_read_format_rar_read_header, archive_read_format_rar_read_data, archive_read_format_rar_read_data_skip, archive_read_format_rar_seek_data, archive_read_format_rar_cleanup, archive_read_support_format_rar_capabilities, archive_read_format_rar_has_encrypted_entries); if (r != ARCHIVE_OK) free(rar); return (r); } static int archive_read_support_format_rar_capabilities(struct archive_read * a) { (void)a; /* UNUSED */ return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA | ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA); } static int archive_read_format_rar_has_encrypted_entries(struct archive_read *_a) { if (_a && _a->format) { struct rar * rar = (struct rar *)_a->format->data; if (rar) { return rar->has_encrypted_entries; } } return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; } static int archive_read_format_rar_bid(struct archive_read *a, int best_bid) { const char *p; /* If there's already a bid > 30, we'll never win. */ if (best_bid > 30) return (-1); if ((p = __archive_read_ahead(a, 7, NULL)) == NULL) return (-1); if (memcmp(p, RAR_SIGNATURE, 7) == 0) return (30); if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) { /* This is a PE file */ ssize_t offset = 0x10000; ssize_t window = 4096; ssize_t bytes_avail; while (offset + window <= (1024 * 128)) { const char *buff = __archive_read_ahead(a, offset + window, &bytes_avail); if (buff == NULL) { /* Remaining bytes are less than window. */ window >>= 1; if (window < 0x40) return (0); continue; } p = buff + offset; while (p + 7 < buff + bytes_avail) { if (memcmp(p, RAR_SIGNATURE, 7) == 0) return (30); p += 0x10; } offset = p - buff; } } return (0); } static int skip_sfx(struct archive_read *a) { const void *h; const char *p, *q; size_t skip, total; ssize_t bytes, window; total = 0; window = 4096; while (total + window <= (1024 * 128)) { h = __archive_read_ahead(a, window, &bytes); if (h == NULL) { /* Remaining bytes are less than window. */ window >>= 1; if (window < 0x40) goto fatal; continue; } if (bytes < 0x40) goto fatal; p = h; q = p + bytes; /* * Scan ahead until we find something that looks * like the RAR header. */ while (p + 7 < q) { if (memcmp(p, RAR_SIGNATURE, 7) == 0) { skip = p - (const char *)h; __archive_read_consume(a, skip); return (ARCHIVE_OK); } p += 0x10; } skip = p - (const char *)h; __archive_read_consume(a, skip); total += skip; } fatal: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Couldn't find out RAR header"); return (ARCHIVE_FATAL); } static int archive_read_format_rar_options(struct archive_read *a, const char *key, const char *val) { struct rar *rar; int ret = ARCHIVE_FAILED; rar = (struct rar *)(a->format->data); if (strcmp(key, "hdrcharset") == 0) { if (val == NULL || val[0] == 0) archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "rar: hdrcharset option needs a character-set name"); else { rar->opt_sconv = archive_string_conversion_from_charset( &a->archive, val, 0); if (rar->opt_sconv != NULL) ret = ARCHIVE_OK; else ret = ARCHIVE_FATAL; } return (ret); } /* Note: The "warn" return is just to inform the options * supervisor that we didn't handle it. It will generate * a suitable error if no one used this option. */ return (ARCHIVE_WARN); } static int archive_read_format_rar_read_header(struct archive_read *a, struct archive_entry *entry) { const void *h; const char *p; struct rar *rar; size_t skip; char head_type; int ret; unsigned flags; unsigned long crc32_expected; a->archive.archive_format = ARCHIVE_FORMAT_RAR; if (a->archive.archive_format_name == NULL) a->archive.archive_format_name = "RAR"; rar = (struct rar *)(a->format->data); /* * It should be sufficient to call archive_read_next_header() for * a reader to determine if an entry is encrypted or not. If the * encryption of an entry is only detectable when calling * archive_read_data(), so be it. We'll do the same check there * as well. */ if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { rar->has_encrypted_entries = 0; } /* RAR files can be generated without EOF headers, so return ARCHIVE_EOF if * this fails. */ if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_EOF); p = h; if (rar->found_first_header == 0 && ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0)) { /* This is an executable ? Must be self-extracting... */ ret = skip_sfx(a); if (ret < ARCHIVE_WARN) return (ret); } rar->found_first_header = 1; while (1) { unsigned long crc32_val; if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; head_type = p[2]; switch(head_type) { case MARK_HEAD: if (memcmp(p, RAR_SIGNATURE, 7) != 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid marker header"); return (ARCHIVE_FATAL); } __archive_read_consume(a, 7); break; case MAIN_HEAD: rar->main_flags = archive_le16dec(p + 3); skip = archive_le16dec(p + 5); if (skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, skip, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; memcpy(rar->reserved1, p + 7, sizeof(rar->reserved1)); memcpy(rar->reserved2, p + 7 + sizeof(rar->reserved1), sizeof(rar->reserved2)); if (rar->main_flags & MHD_ENCRYPTVER) { if (skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)+1) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } rar->encryptver = *(p + 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)); } /* Main header is password encrypted, so we cannot read any file names or any other info about files from the header. */ if (rar->main_flags & MHD_PASSWORD) { archive_entry_set_is_metadata_encrypted(entry, 1); archive_entry_set_is_data_encrypted(entry, 1); rar->has_encrypted_entries = 1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR encryption support unavailable."); return (ARCHIVE_FATAL); } crc32_val = crc32(0, (const unsigned char *)p + 2, (unsigned)skip - 2); if ((crc32_val & 0xffff) != archive_le16dec(p)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } __archive_read_consume(a, skip); break; case FILE_HEAD: return read_header(a, entry, head_type); case COMM_HEAD: case AV_HEAD: case SUB_HEAD: case PROTECT_HEAD: case SIGN_HEAD: case ENDARC_HEAD: flags = archive_le16dec(p + 3); skip = archive_le16dec(p + 5); if (skip < 7) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size too small"); return (ARCHIVE_FATAL); } if (flags & HD_ADD_SIZE_PRESENT) { if (skip < 7 + 4) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size too small"); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, skip, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; skip += archive_le32dec(p + 7); } /* Skip over the 2-byte CRC at the beginning of the header. */ crc32_expected = archive_le16dec(p); __archive_read_consume(a, 2); skip -= 2; /* Skim the entire header and compute the CRC. */ crc32_val = 0; while (skip > 0) { size_t to_read = skip; ssize_t did_read; if (to_read > 32 * 1024) { to_read = 32 * 1024; } if ((h = __archive_read_ahead(a, to_read, &did_read)) == NULL) { return (ARCHIVE_FATAL); } p = h; crc32_val = crc32(crc32_val, (const unsigned char *)p, (unsigned)did_read); __archive_read_consume(a, did_read); skip -= did_read; } if ((crc32_val & 0xffff) != crc32_expected) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } if (head_type == ENDARC_HEAD) return (ARCHIVE_EOF); break; case NEWSUB_HEAD: if ((ret = read_header(a, entry, head_type)) < ARCHIVE_WARN) return ret; break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file"); return (ARCHIVE_FATAL); } } } static int archive_read_format_rar_read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct rar *rar = (struct rar *)(a->format->data); int ret; if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { rar->has_encrypted_entries = 0; } if (rar->bytes_unconsumed > 0) { /* Consume as much as the decompressor actually used. */ __archive_read_consume(a, rar->bytes_unconsumed); rar->bytes_unconsumed = 0; } *buff = NULL; if (rar->entry_eof || rar->offset_seek >= rar->unp_size) { *size = 0; *offset = rar->offset; if (*offset < rar->unp_size) *offset = rar->unp_size; return (ARCHIVE_EOF); } switch (rar->compression_method) { case COMPRESS_METHOD_STORE: ret = read_data_stored(a, buff, size, offset); break; case COMPRESS_METHOD_FASTEST: case COMPRESS_METHOD_FAST: case COMPRESS_METHOD_NORMAL: case COMPRESS_METHOD_GOOD: case COMPRESS_METHOD_BEST: ret = read_data_compressed(a, buff, size, offset); if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN) __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unsupported compression method for RAR file."); ret = ARCHIVE_FATAL; break; } return (ret); } static int archive_read_format_rar_read_data_skip(struct archive_read *a) { struct rar *rar; int64_t bytes_skipped; int ret; rar = (struct rar *)(a->format->data); if (rar->bytes_unconsumed > 0) { /* Consume as much as the decompressor actually used. */ __archive_read_consume(a, rar->bytes_unconsumed); rar->bytes_unconsumed = 0; } if (rar->bytes_remaining > 0) { bytes_skipped = __archive_read_consume(a, rar->bytes_remaining); if (bytes_skipped < 0) return (ARCHIVE_FATAL); } /* Compressed data to skip must be read from each header in a multivolume * archive. */ if (rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER) { ret = archive_read_format_rar_read_header(a, a->entry); if (ret == (ARCHIVE_EOF)) ret = archive_read_format_rar_read_header(a, a->entry); if (ret != (ARCHIVE_OK)) return ret; return archive_read_format_rar_read_data_skip(a); } return (ARCHIVE_OK); } static int64_t archive_read_format_rar_seek_data(struct archive_read *a, int64_t offset, int whence) { int64_t client_offset, ret; unsigned int i; struct rar *rar = (struct rar *)(a->format->data); if (rar->compression_method == COMPRESS_METHOD_STORE) { /* Modify the offset for use with SEEK_SET */ switch (whence) { case SEEK_CUR: client_offset = rar->offset_seek; break; case SEEK_END: client_offset = rar->unp_size; break; case SEEK_SET: default: client_offset = 0; } client_offset += offset; if (client_offset < 0) { /* Can't seek past beginning of data block */ return -1; } else if (client_offset > rar->unp_size) { /* * Set the returned offset but only seek to the end of * the data block. */ rar->offset_seek = client_offset; client_offset = rar->unp_size; } client_offset += rar->dbo[0].start_offset; i = 0; while (i < rar->cursor) { i++; client_offset += rar->dbo[i].start_offset - rar->dbo[i-1].end_offset; } if (rar->main_flags & MHD_VOLUME) { /* Find the appropriate offset among the multivolume archive */ while (1) { if (client_offset < rar->dbo[rar->cursor].start_offset && rar->file_flags & FHD_SPLIT_BEFORE) { /* Search backwards for the correct data block */ if (rar->cursor == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Attempt to seek past beginning of RAR data block"); return (ARCHIVE_FAILED); } rar->cursor--; client_offset -= rar->dbo[rar->cursor+1].start_offset - rar->dbo[rar->cursor].end_offset; if (client_offset < rar->dbo[rar->cursor].start_offset) continue; ret = __archive_read_seek(a, rar->dbo[rar->cursor].start_offset - rar->dbo[rar->cursor].header_size, SEEK_SET); if (ret < (ARCHIVE_OK)) return ret; ret = archive_read_format_rar_read_header(a, a->entry); if (ret != (ARCHIVE_OK)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Error during seek of RAR file"); return (ARCHIVE_FAILED); } rar->cursor--; break; } else if (client_offset > rar->dbo[rar->cursor].end_offset && rar->file_flags & FHD_SPLIT_AFTER) { /* Search forward for the correct data block */ rar->cursor++; if (rar->cursor < rar->nodes && client_offset > rar->dbo[rar->cursor].end_offset) { client_offset += rar->dbo[rar->cursor].start_offset - rar->dbo[rar->cursor-1].end_offset; continue; } rar->cursor--; ret = __archive_read_seek(a, rar->dbo[rar->cursor].end_offset, SEEK_SET); if (ret < (ARCHIVE_OK)) return ret; ret = archive_read_format_rar_read_header(a, a->entry); if (ret == (ARCHIVE_EOF)) { rar->has_endarc_header = 1; ret = archive_read_format_rar_read_header(a, a->entry); } if (ret != (ARCHIVE_OK)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Error during seek of RAR file"); return (ARCHIVE_FAILED); } client_offset += rar->dbo[rar->cursor].start_offset - rar->dbo[rar->cursor-1].end_offset; continue; } break; } } ret = __archive_read_seek(a, client_offset, SEEK_SET); if (ret < (ARCHIVE_OK)) return ret; rar->bytes_remaining = rar->dbo[rar->cursor].end_offset - ret; i = rar->cursor; while (i > 0) { i--; ret -= rar->dbo[i+1].start_offset - rar->dbo[i].end_offset; } ret -= rar->dbo[0].start_offset; /* Always restart reading the file after a seek */ __archive_reset_read_data(&a->archive); rar->bytes_unconsumed = 0; rar->offset = 0; /* * If a seek past the end of file was requested, return the requested * offset. */ if (ret == rar->unp_size && rar->offset_seek > rar->unp_size) return rar->offset_seek; /* Return the new offset */ rar->offset_seek = ret; return rar->offset_seek; } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Seeking of compressed RAR files is unsupported"); } return (ARCHIVE_FAILED); } static int archive_read_format_rar_cleanup(struct archive_read *a) { struct rar *rar; rar = (struct rar *)(a->format->data); free_codes(a); free(rar->filename); free(rar->filename_save); free(rar->dbo); free(rar->unp_buffer); free(rar->lzss.window); __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); free(rar); (a->format->data) = NULL; return (ARCHIVE_OK); } static int read_header(struct archive_read *a, struct archive_entry *entry, char head_type) { const void *h; const char *p, *endp; struct rar *rar; struct rar_header rar_header; struct rar_file_header file_header; int64_t header_size; unsigned filename_size, end; char *filename; char *strp; char packed_size[8]; char unp_size[8]; int ttime; struct archive_string_conv *sconv, *fn_sconv; unsigned long crc32_val; int ret = (ARCHIVE_OK), ret2; rar = (struct rar *)(a->format->data); /* Setup a string conversion object for non-rar-unicode filenames. */ sconv = rar->opt_sconv; if (sconv == NULL) { if (!rar->init_default_conversion) { rar->sconv_default = archive_string_default_conversion_for_read( &(a->archive)); rar->init_default_conversion = 1; } sconv = rar->sconv_default; } if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; memcpy(&rar_header, p, sizeof(rar_header)); rar->file_flags = archive_le16dec(rar_header.flags); header_size = archive_le16dec(rar_header.size); if (header_size < (int64_t)sizeof(file_header) + 7) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2); __archive_read_consume(a, 7); if (!(rar->file_flags & FHD_SOLID)) { rar->compression_method = 0; rar->packed_size = 0; rar->unp_size = 0; rar->mtime = 0; rar->ctime = 0; rar->atime = 0; rar->arctime = 0; rar->mode = 0; memset(&rar->salt, 0, sizeof(rar->salt)); rar->atime = 0; rar->ansec = 0; rar->ctime = 0; rar->cnsec = 0; rar->mtime = 0; rar->mnsec = 0; rar->arctime = 0; rar->arcnsec = 0; } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR solid archive support unavailable."); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); /* File Header CRC check. */ crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7)); if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } /* If no CRC error, Go on parsing File Header. */ p = h; endp = p + header_size - 7; memcpy(&file_header, p, sizeof(file_header)); p += sizeof(file_header); rar->compression_method = file_header.method; ttime = archive_le32dec(file_header.file_time); rar->mtime = get_time(ttime); rar->file_crc = archive_le32dec(file_header.file_crc); if (rar->file_flags & FHD_PASSWORD) { archive_entry_set_is_data_encrypted(entry, 1); rar->has_encrypted_entries = 1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR encryption support unavailable."); /* Since it is only the data part itself that is encrypted we can at least extract information about the currently processed entry and don't need to return ARCHIVE_FATAL here. */ /*return (ARCHIVE_FATAL);*/ } if (rar->file_flags & FHD_LARGE) { memcpy(packed_size, file_header.pack_size, 4); memcpy(packed_size + 4, p, 4); /* High pack size */ p += 4; memcpy(unp_size, file_header.unp_size, 4); memcpy(unp_size + 4, p, 4); /* High unpack size */ p += 4; rar->packed_size = archive_le64dec(&packed_size); rar->unp_size = archive_le64dec(&unp_size); } else { rar->packed_size = archive_le32dec(file_header.pack_size); rar->unp_size = archive_le32dec(file_header.unp_size); } if (rar->packed_size < 0 || rar->unp_size < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid sizes specified."); return (ARCHIVE_FATAL); } rar->bytes_remaining = rar->packed_size; /* TODO: RARv3 subblocks contain comments. For now the complete block is * consumed at the end. */ if (head_type == NEWSUB_HEAD) { size_t distance = p - (const char *)h; header_size += rar->packed_size; /* Make sure we have the extended data. */ if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; endp = p + header_size - 7; p += distance; } filename_size = archive_le16dec(file_header.name_size); if (p + filename_size > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename size"); return (ARCHIVE_FATAL); } if (rar->filename_allocated < filename_size * 2 + 2) { char *newptr; size_t newsize = filename_size * 2 + 2; newptr = realloc(rar->filename, newsize); if (newptr == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->filename = newptr; rar->filename_allocated = newsize; } filename = rar->filename; memcpy(filename, p, filename_size); filename[filename_size] = '\0'; if (rar->file_flags & FHD_UNICODE) { if (filename_size != strlen(filename)) { unsigned char highbyte, flagbits, flagbyte; unsigned fn_end, offset; end = filename_size; fn_end = filename_size * 2; filename_size = 0; offset = (unsigned)strlen(filename) + 1; highbyte = *(p + offset++); flagbits = 0; flagbyte = 0; while (offset < end && filename_size < fn_end) { if (!flagbits) { flagbyte = *(p + offset++); flagbits = 8; } flagbits -= 2; switch((flagbyte >> flagbits) & 3) { case 0: filename[filename_size++] = '\0'; filename[filename_size++] = *(p + offset++); break; case 1: filename[filename_size++] = highbyte; filename[filename_size++] = *(p + offset++); break; case 2: filename[filename_size++] = *(p + offset + 1); filename[filename_size++] = *(p + offset); offset += 2; break; case 3: { char extra, high; uint8_t length = *(p + offset++); if (length & 0x80) { extra = *(p + offset++); high = (char)highbyte; } else extra = high = 0; length = (length & 0x7f) + 2; while (length && filename_size < fn_end) { unsigned cp = filename_size >> 1; filename[filename_size++] = high; filename[filename_size++] = p[cp] + extra; length--; } } break; } } if (filename_size > fn_end) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename"); return (ARCHIVE_FATAL); } filename[filename_size++] = '\0'; /* * Do not increment filename_size here as the computations below * add the space for the terminating NUL explicitly. */ filename[filename_size] = '\0'; /* Decoded unicode form is UTF-16BE, so we have to update a string * conversion object for it. */ if (rar->sconv_utf16be == NULL) { rar->sconv_utf16be = archive_string_conversion_from_charset( &a->archive, "UTF-16BE", 1); if (rar->sconv_utf16be == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf16be; strp = filename; while (memcmp(strp, "\x00\x00", 2)) { if (!memcmp(strp, "\x00\\", 2)) *(strp + 1) = '/'; strp += 2; } p += offset; } else { /* * If FHD_UNICODE is set but no unicode data, this file name form * is UTF-8, so we have to update a string conversion object for * it accordingly. */ if (rar->sconv_utf8 == NULL) { rar->sconv_utf8 = archive_string_conversion_from_charset( &a->archive, "UTF-8", 1); if (rar->sconv_utf8 == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf8; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } } else { fn_sconv = sconv; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } /* Split file in multivolume RAR. No more need to process header. */ if (rar->filename_save && filename_size == rar->filename_save_size && !memcmp(rar->filename, rar->filename_save, filename_size + 1)) { __archive_read_consume(a, header_size - 7); rar->cursor++; if (rar->cursor >= rar->nodes) { rar->nodes++; if ((rar->dbo = realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[rar->cursor].header_size = header_size; rar->dbo[rar->cursor].start_offset = -1; rar->dbo[rar->cursor].end_offset = -1; } if (rar->dbo[rar->cursor].start_offset < 0) { rar->dbo[rar->cursor].start_offset = a->filter->position; rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset + rar->packed_size; } return ret; } rar->filename_save = (char*)realloc(rar->filename_save, filename_size + 1); memcpy(rar->filename_save, rar->filename, filename_size + 1); rar->filename_save_size = filename_size; /* Set info for seeking */ free(rar->dbo); if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[0].header_size = header_size; rar->dbo[0].start_offset = -1; rar->dbo[0].end_offset = -1; rar->cursor = 0; rar->nodes = 1; if (rar->file_flags & FHD_SALT) { if (p + 8 > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } memcpy(rar->salt, p, 8); p += 8; } if (rar->file_flags & FHD_EXTTIME) { if (read_exttime(p, rar, endp) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } } __archive_read_consume(a, header_size - 7); rar->dbo[0].start_offset = a->filter->position; rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size; switch(file_header.host_os) { case OS_MSDOS: case OS_OS2: case OS_WIN32: rar->mode = archive_le32dec(file_header.file_attr); if (rar->mode & FILE_ATTRIBUTE_DIRECTORY) rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH; else rar->mode = AE_IFREG; rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; break; case OS_UNIX: case OS_MAC_OS: case OS_BEOS: rar->mode = archive_le32dec(file_header.file_attr); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unknown file attributes from RAR file's host OS"); return (ARCHIVE_FATAL); } rar->bytes_uncopied = rar->bytes_unconsumed = 0; rar->lzss.position = rar->offset = 0; rar->offset_seek = 0; rar->dictionary_size = 0; rar->offset_outgoing = 0; rar->br.cache_avail = 0; rar->br.avail_in = 0; rar->crc_calculated = 0; rar->entry_eof = 0; rar->valid = 1; rar->is_ppmd_block = 0; rar->start_new_table = 1; free(rar->unp_buffer); rar->unp_buffer = NULL; rar->unp_offset = 0; rar->unp_buffer_size = UNP_BUFFER_SIZE; memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); rar->ppmd_valid = rar->ppmd_eod = 0; /* Don't set any archive entries for non-file header types */ if (head_type == NEWSUB_HEAD) return ret; archive_entry_set_mtime(entry, rar->mtime, rar->mnsec); archive_entry_set_ctime(entry, rar->ctime, rar->cnsec); archive_entry_set_atime(entry, rar->atime, rar->ansec); archive_entry_set_size(entry, rar->unp_size); archive_entry_set_mode(entry, rar->mode); if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv)) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(fn_sconv)); ret = (ARCHIVE_WARN); } if (((rar->mode) & AE_IFMT) == AE_IFLNK) { /* Make sure a symbolic-link file does not have its body. */ rar->bytes_remaining = 0; archive_entry_set_size(entry, 0); /* Read a symbolic-link name. */ if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN)) return ret2; if (ret > ret2) ret = ret2; } if (rar->bytes_remaining == 0) rar->entry_eof = 1; return ret; } static time_t get_time(int ttime) { struct tm tm; tm.tm_sec = 2 * (ttime & 0x1f); tm.tm_min = (ttime >> 5) & 0x3f; tm.tm_hour = (ttime >> 11) & 0x1f; tm.tm_mday = (ttime >> 16) & 0x1f; tm.tm_mon = ((ttime >> 21) & 0x0f) - 1; tm.tm_year = ((ttime >> 25) & 0x7f) + 80; tm.tm_isdst = -1; return mktime(&tm); } static int read_exttime(const char *p, struct rar *rar, const char *endp) { unsigned rmode, flags, rem, j, count; int ttime, i; struct tm *tm; time_t t; long nsec; if (p + 2 > endp) return (-1); flags = archive_le16dec(p); p += 2; for (i = 3; i >= 0; i--) { t = 0; if (i == 3) t = rar->mtime; rmode = flags >> i * 4; if (rmode & 8) { if (!t) { if (p + 4 > endp) return (-1); ttime = archive_le32dec(p); t = get_time(ttime); p += 4; } rem = 0; count = rmode & 3; if (p + count > endp) return (-1); for (j = 0; j < count; j++) { rem = (((unsigned)(unsigned char)*p) << 16) | (rem >> 8); p++; } tm = localtime(&t); nsec = tm->tm_sec + rem / NS_UNIT; if (rmode & 4) { tm->tm_sec++; t = mktime(tm); } if (i == 3) { rar->mtime = t; rar->mnsec = nsec; } else if (i == 2) { rar->ctime = t; rar->cnsec = nsec; } else if (i == 1) { rar->atime = t; rar->ansec = nsec; } else { rar->arctime = t; rar->arcnsec = nsec; } } } return (0); } static int read_symlink_stored(struct archive_read *a, struct archive_entry *entry, struct archive_string_conv *sconv) { const void *h; const char *p; struct rar *rar; int ret = (ARCHIVE_OK); rar = (struct rar *)(a->format->data); if ((h = rar_read_ahead(a, (size_t)rar->packed_size, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; if (archive_entry_copy_symlink_l(entry, p, (size_t)rar->packed_size, sconv)) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for link"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "link cannot be converted from %s to current locale.", archive_string_conversion_charset_name(sconv)); ret = (ARCHIVE_WARN); } __archive_read_consume(a, rar->packed_size); return ret; } static int read_data_stored(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct rar *rar; ssize_t bytes_avail; rar = (struct rar *)(a->format->data); if (rar->bytes_remaining == 0 && !(rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER)) { *buff = NULL; *size = 0; *offset = rar->offset; if (rar->file_crc != rar->crc_calculated) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "File CRC error"); return (ARCHIVE_FATAL); } rar->entry_eof = 1; return (ARCHIVE_EOF); } *buff = rar_read_ahead(a, 1, &bytes_avail); if (bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); return (ARCHIVE_FATAL); } *size = bytes_avail; *offset = rar->offset; rar->offset += bytes_avail; rar->offset_seek += bytes_avail; rar->bytes_remaining -= bytes_avail; rar->bytes_unconsumed = bytes_avail; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)bytes_avail); return (ARCHIVE_OK); } static int read_data_compressed(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct rar *rar; int64_t start, end, actualend; size_t bs; int ret = (ARCHIVE_OK), sym, code, lzss_offset, length, i; rar = (struct rar *)(a->format->data); do { if (!rar->valid) return (ARCHIVE_FATAL); if (rar->ppmd_eod || (rar->dictionary_size && rar->offset >= rar->unp_size)) { if (rar->unp_offset > 0) { /* * We have unprocessed extracted data. write it out. */ *buff = rar->unp_buffer; *size = rar->unp_offset; *offset = rar->offset_outgoing; rar->offset_outgoing += *size; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size); rar->unp_offset = 0; return (ARCHIVE_OK); } *buff = NULL; *size = 0; *offset = rar->offset; if (rar->file_crc != rar->crc_calculated) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "File CRC error"); return (ARCHIVE_FATAL); } rar->entry_eof = 1; return (ARCHIVE_EOF); } if (!rar->is_ppmd_block && rar->dictionary_size && rar->bytes_uncopied > 0) { if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset)) bs = rar->unp_buffer_size - rar->unp_offset; else bs = (size_t)rar->bytes_uncopied; ret = copy_from_lzss_window(a, buff, rar->offset, (int)bs); if (ret != ARCHIVE_OK) return (ret); rar->offset += bs; rar->bytes_uncopied -= bs; if (*buff != NULL) { rar->unp_offset = 0; *size = rar->unp_buffer_size; *offset = rar->offset_outgoing; rar->offset_outgoing += *size; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size); return (ret); } continue; } if (!rar->br.next_in && (ret = rar_br_preparation(a, &(rar->br))) < ARCHIVE_WARN) return (ret); if (rar->start_new_table && ((ret = parse_codes(a)) < (ARCHIVE_WARN))) return (ret); if (rar->is_ppmd_block) { if ((sym = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } if(sym != rar->ppmd_escape) { lzss_emit_literal(rar, sym); rar->bytes_uncopied++; } else { if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } switch(code) { case 0: rar->start_new_table = 1; return read_data_compressed(a, buff, size, offset); case 2: rar->ppmd_eod = 1;/* End Of ppmd Data. */ continue; case 3: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Parsing filters is unsupported."); return (ARCHIVE_FAILED); case 4: lzss_offset = 0; for (i = 2; i >= 0; i--) { if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } lzss_offset |= code << (i * 8); } if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } lzss_emit_match(rar, lzss_offset + 2, length + 32); rar->bytes_uncopied += length + 32; break; case 5: if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } lzss_emit_match(rar, 1, length + 4); rar->bytes_uncopied += length + 4; break; default: lzss_emit_literal(rar, sym); rar->bytes_uncopied++; } } } else { start = rar->offset; end = start + rar->dictionary_size; rar->filterstart = INT64_MAX; if ((actualend = expand(a, end)) < 0) return ((int)actualend); rar->bytes_uncopied = actualend - start; if (rar->bytes_uncopied == 0) { /* Broken RAR files cause this case. * NOTE: If this case were possible on a normal RAR file * we would find out where it was actually bad and * what we would do to solve it. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Internal error extracting RAR file"); return (ARCHIVE_FATAL); } } if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset)) bs = rar->unp_buffer_size - rar->unp_offset; else bs = (size_t)rar->bytes_uncopied; ret = copy_from_lzss_window(a, buff, rar->offset, (int)bs); if (ret != ARCHIVE_OK) return (ret); rar->offset += bs; rar->bytes_uncopied -= bs; /* * If *buff is NULL, it means unp_buffer is not full. * So we have to continue extracting a RAR file. */ } while (*buff == NULL); rar->unp_offset = 0; *size = rar->unp_buffer_size; *offset = rar->offset_outgoing; rar->offset_outgoing += *size; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size); return ret; } static int parse_codes(struct archive_read *a) { int i, j, val, n, r; unsigned char bitlengths[MAX_SYMBOLS], zerocount, ppmd_flags; unsigned int maxorder; struct huffman_code precode; struct rar *rar = (struct rar *)(a->format->data); struct rar_br *br = &(rar->br); free_codes(a); /* Skip to the next byte */ rar_br_consume_unalined_bits(br); /* PPMd block flag */ if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; if ((rar->is_ppmd_block = rar_br_bits(br, 1)) != 0) { rar_br_consume(br, 1); if (!rar_br_read_ahead(a, br, 7)) goto truncated_data; ppmd_flags = rar_br_bits(br, 7); rar_br_consume(br, 7); /* Memory is allocated in MB */ if (ppmd_flags & 0x20) { if (!rar_br_read_ahead(a, br, 8)) goto truncated_data; rar->dictionary_size = (rar_br_bits(br, 8) + 1) << 20; rar_br_consume(br, 8); } if (ppmd_flags & 0x40) { if (!rar_br_read_ahead(a, br, 8)) goto truncated_data; rar->ppmd_escape = rar->ppmd7_context.InitEsc = rar_br_bits(br, 8); rar_br_consume(br, 8); } else rar->ppmd_escape = 2; if (ppmd_flags & 0x20) { maxorder = (ppmd_flags & 0x1F) + 1; if(maxorder > 16) maxorder = 16 + (maxorder - 16) * 3; if (maxorder == 1) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); return (ARCHIVE_FATAL); } /* Make sure ppmd7_contest is freed before Ppmd7_Construct * because reading a broken file cause this abnormal sequence. */ __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); rar->bytein.a = a; rar->bytein.Read = &ppmd_read; __archive_ppmd7_functions.PpmdRAR_RangeDec_CreateVTable(&rar->range_dec); rar->range_dec.Stream = &rar->bytein; __archive_ppmd7_functions.Ppmd7_Construct(&rar->ppmd7_context); if (rar->dictionary_size == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid zero dictionary size"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.Ppmd7_Alloc(&rar->ppmd7_context, rar->dictionary_size, &g_szalloc)) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unable to initialize PPMd range decoder"); return (ARCHIVE_FATAL); } __archive_ppmd7_functions.Ppmd7_Init(&rar->ppmd7_context, maxorder); rar->ppmd_valid = 1; } else { if (!rar->ppmd_valid) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid PPMd sequence"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unable to initialize PPMd range decoder"); return (ARCHIVE_FATAL); } } } else { rar_br_consume(br, 1); /* Keep existing table flag */ if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; if (!rar_br_bits(br, 1)) memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); rar_br_consume(br, 1); memset(&bitlengths, 0, sizeof(bitlengths)); for (i = 0; i < MAX_SYMBOLS;) { if (!rar_br_read_ahead(a, br, 4)) goto truncated_data; bitlengths[i++] = rar_br_bits(br, 4); rar_br_consume(br, 4); if (bitlengths[i-1] == 0xF) { if (!rar_br_read_ahead(a, br, 4)) goto truncated_data; zerocount = rar_br_bits(br, 4); rar_br_consume(br, 4); if (zerocount) { i--; for (j = 0; j < zerocount + 2 && i < MAX_SYMBOLS; j++) bitlengths[i++] = 0; } } } memset(&precode, 0, sizeof(precode)); r = create_code(a, &precode, bitlengths, MAX_SYMBOLS, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) { free(precode.tree); free(precode.table); return (r); } for (i = 0; i < HUFFMAN_TABLE_SIZE;) { if ((val = read_next_symbol(a, &precode)) < 0) { free(precode.tree); free(precode.table); return (ARCHIVE_FATAL); } if (val < 16) { rar->lengthtable[i] = (rar->lengthtable[i] + val) & 0xF; i++; } else if (val < 18) { if (i == 0) { free(precode.tree); free(precode.table); archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Internal error extracting RAR file."); return (ARCHIVE_FATAL); } if(val == 16) { if (!rar_br_read_ahead(a, br, 3)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 3) + 3; rar_br_consume(br, 3); } else { if (!rar_br_read_ahead(a, br, 7)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 7) + 11; rar_br_consume(br, 7); } for (j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++) { rar->lengthtable[i] = rar->lengthtable[i-1]; i++; } } else { if(val == 18) { if (!rar_br_read_ahead(a, br, 3)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 3) + 3; rar_br_consume(br, 3); } else { if (!rar_br_read_ahead(a, br, 7)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 7) + 11; rar_br_consume(br, 7); } for(j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++) rar->lengthtable[i++] = 0; } } free(precode.tree); free(precode.table); r = create_code(a, &rar->maincode, &rar->lengthtable[0], MAINCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->offsetcode, &rar->lengthtable[MAINCODE_SIZE], OFFSETCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->lowoffsetcode, &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE], LOWOFFSETCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->lengthcode, &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE + LOWOFFSETCODE_SIZE], LENGTHCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); } if (!rar->dictionary_size || !rar->lzss.window) { /* Seems as though dictionary sizes are not used. Even so, minimize * memory usage as much as possible. */ void *new_window; unsigned int new_size; if (rar->unp_size >= DICTIONARY_MAX_SIZE) new_size = DICTIONARY_MAX_SIZE; else new_size = rar_fls((unsigned int)rar->unp_size) << 1; new_window = realloc(rar->lzss.window, new_size); if (new_window == NULL) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for uncompressed data."); return (ARCHIVE_FATAL); } rar->lzss.window = (unsigned char *)new_window; rar->dictionary_size = new_size; memset(rar->lzss.window, 0, rar->dictionary_size); rar->lzss.mask = rar->dictionary_size - 1; } rar->start_new_table = 0; return (ARCHIVE_OK); truncated_data: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return (ARCHIVE_FATAL); } static void free_codes(struct archive_read *a) { struct rar *rar = (struct rar *)(a->format->data); free(rar->maincode.tree); free(rar->offsetcode.tree); free(rar->lowoffsetcode.tree); free(rar->lengthcode.tree); free(rar->maincode.table); free(rar->offsetcode.table); free(rar->lowoffsetcode.table); free(rar->lengthcode.table); memset(&rar->maincode, 0, sizeof(rar->maincode)); memset(&rar->offsetcode, 0, sizeof(rar->offsetcode)); memset(&rar->lowoffsetcode, 0, sizeof(rar->lowoffsetcode)); memset(&rar->lengthcode, 0, sizeof(rar->lengthcode)); } static int read_next_symbol(struct archive_read *a, struct huffman_code *code) { unsigned char bit; unsigned int bits; int length, value, node; struct rar *rar; struct rar_br *br; if (!code->table) { if (make_table(a, code) != (ARCHIVE_OK)) return -1; } rar = (struct rar *)(a->format->data); br = &(rar->br); /* Look ahead (peek) at bits */ if (!rar_br_read_ahead(a, br, code->tablesize)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return -1; } bits = rar_br_bits(br, code->tablesize); length = code->table[bits].length; value = code->table[bits].value; if (length < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid prefix code in bitstream"); return -1; } if (length <= code->tablesize) { /* Skip length bits */ rar_br_consume(br, length); return value; } /* Skip tablesize bits */ rar_br_consume(br, code->tablesize); node = value; while (!(code->tree[node].branches[0] == code->tree[node].branches[1])) { if (!rar_br_read_ahead(a, br, 1)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return -1; } bit = rar_br_bits(br, 1); rar_br_consume(br, 1); if (code->tree[node].branches[bit] < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid prefix code in bitstream"); return -1; } node = code->tree[node].branches[bit]; } return code->tree[node].branches[0]; } static int create_code(struct archive_read *a, struct huffman_code *code, unsigned char *lengths, int numsymbols, char maxlength) { int i, j, codebits = 0, symbolsleft = numsymbols; code->numentries = 0; code->numallocatedentries = 0; if (new_node(code) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } code->numentries = 1; code->minlength = INT_MAX; code->maxlength = INT_MIN; codebits = 0; for(i = 1; i <= maxlength; i++) { for(j = 0; j < numsymbols; j++) { if (lengths[j] != i) continue; if (add_value(a, code, j, codebits, i) != ARCHIVE_OK) return (ARCHIVE_FATAL); codebits++; if (--symbolsleft <= 0) { break; break; } } codebits <<= 1; } return (ARCHIVE_OK); } static int add_value(struct archive_read *a, struct huffman_code *code, int value, int codebits, int length) { int repeatpos, lastnode, bitpos, bit, repeatnode, nextnode; free(code->table); code->table = NULL; if(length > code->maxlength) code->maxlength = length; if(length < code->minlength) code->minlength = length; repeatpos = -1; if (repeatpos == 0 || (repeatpos >= 0 && (((codebits >> (repeatpos - 1)) & 3) == 0 || ((codebits >> (repeatpos - 1)) & 3) == 3))) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid repeat position"); return (ARCHIVE_FATAL); } lastnode = 0; for (bitpos = length - 1; bitpos >= 0; bitpos--) { bit = (codebits >> bitpos) & 1; /* Leaf node check */ if (code->tree[lastnode].branches[0] == code->tree[lastnode].branches[1]) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Prefix found"); return (ARCHIVE_FATAL); } if (bitpos == repeatpos) { /* Open branch check */ if (!(code->tree[lastnode].branches[bit] < 0)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid repeating code"); return (ARCHIVE_FATAL); } if ((repeatnode = new_node(code)) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } if ((nextnode = new_node(code)) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } /* Set branches */ code->tree[lastnode].branches[bit] = repeatnode; code->tree[repeatnode].branches[bit] = repeatnode; code->tree[repeatnode].branches[bit^1] = nextnode; lastnode = nextnode; bitpos++; /* terminating bit already handled, skip it */ } else { /* Open branch check */ if (code->tree[lastnode].branches[bit] < 0) { if (new_node(code) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } code->tree[lastnode].branches[bit] = code->numentries++; } /* set to branch */ lastnode = code->tree[lastnode].branches[bit]; } } if (!(code->tree[lastnode].branches[0] == -1 && code->tree[lastnode].branches[1] == -2)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Prefix found"); return (ARCHIVE_FATAL); } /* Set leaf value */ code->tree[lastnode].branches[0] = value; code->tree[lastnode].branches[1] = value; return (ARCHIVE_OK); } static int new_node(struct huffman_code *code) { void *new_tree; if (code->numallocatedentries == code->numentries) { int new_num_entries = 256; if (code->numentries > 0) { new_num_entries = code->numentries * 2; } new_tree = realloc(code->tree, new_num_entries * sizeof(*code->tree)); if (new_tree == NULL) return (-1); code->tree = (struct huffman_tree_node *)new_tree; code->numallocatedentries = new_num_entries; } code->tree[code->numentries].branches[0] = -1; code->tree[code->numentries].branches[1] = -2; return 1; } static int make_table(struct archive_read *a, struct huffman_code *code) { if (code->maxlength < code->minlength || code->maxlength > 10) code->tablesize = 10; else code->tablesize = code->maxlength; code->table = (struct huffman_table_entry *)calloc(1, sizeof(*code->table) * ((size_t)1 << code->tablesize)); return make_table_recurse(a, code, 0, code->table, 0, code->tablesize); } static int make_table_recurse(struct archive_read *a, struct huffman_code *code, int node, struct huffman_table_entry *table, int depth, int maxdepth) { int currtablesize, i, ret = (ARCHIVE_OK); if (!code->tree) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Huffman tree was not created."); return (ARCHIVE_FATAL); } if (node < 0 || node >= code->numentries) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid location to Huffman tree specified."); return (ARCHIVE_FATAL); } currtablesize = 1 << (maxdepth - depth); if (code->tree[node].branches[0] == code->tree[node].branches[1]) { for(i = 0; i < currtablesize; i++) { table[i].length = depth; table[i].value = code->tree[node].branches[0]; } } else if (node < 0) { for(i = 0; i < currtablesize; i++) table[i].length = -1; } else { if(depth == maxdepth) { table[0].length = maxdepth + 1; table[0].value = node; } else { ret |= make_table_recurse(a, code, code->tree[node].branches[0], table, depth + 1, maxdepth); ret |= make_table_recurse(a, code, code->tree[node].branches[1], table + currtablesize / 2, depth + 1, maxdepth); } } return ret; } static int64_t expand(struct archive_read *a, int64_t end) { static const unsigned char lengthbases[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224 }; static const unsigned char lengthbits[] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 }; static const unsigned int offsetbases[] = { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576, 32768, 49152, 65536, 98304, 131072, 196608, 262144, 327680, 393216, 458752, 524288, 589824, 655360, 720896, 786432, 851968, 917504, 983040, 1048576, 1310720, 1572864, 1835008, 2097152, 2359296, 2621440, 2883584, 3145728, 3407872, 3670016, 3932160 }; static const unsigned char offsetbits[] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18 }; static const unsigned char shortbases[] = { 0, 4, 8, 16, 32, 64, 128, 192 }; static const unsigned char shortbits[] = { 2, 2, 3, 4, 5, 6, 6, 6 }; int symbol, offs, len, offsindex, lensymbol, i, offssymbol, lowoffsetsymbol; unsigned char newfile; struct rar *rar = (struct rar *)(a->format->data); struct rar_br *br = &(rar->br); if (rar->filterstart < end) end = rar->filterstart; while (1) { if (rar->output_last_match && lzss_position(&rar->lzss) + rar->lastlength <= end) { lzss_emit_match(rar, rar->lastoffset, rar->lastlength); rar->output_last_match = 0; } if(rar->is_ppmd_block || rar->output_last_match || lzss_position(&rar->lzss) >= end) return lzss_position(&rar->lzss); if ((symbol = read_next_symbol(a, &rar->maincode)) < 0) return (ARCHIVE_FATAL); rar->output_last_match = 0; if (symbol < 256) { lzss_emit_literal(rar, symbol); continue; } else if (symbol == 256) { if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; newfile = !rar_br_bits(br, 1); rar_br_consume(br, 1); if(newfile) { rar->start_new_block = 1; if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; rar->start_new_table = rar_br_bits(br, 1); rar_br_consume(br, 1); return lzss_position(&rar->lzss); } else { if (parse_codes(a) != ARCHIVE_OK) return (ARCHIVE_FATAL); continue; } } else if(symbol==257) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Parsing filters is unsupported."); return (ARCHIVE_FAILED); } else if(symbol==258) { if(rar->lastlength == 0) continue; offs = rar->lastoffset; len = rar->lastlength; } else if (symbol <= 262) { offsindex = symbol - 259; offs = rar->oldoffset[offsindex]; if ((lensymbol = read_next_symbol(a, &rar->lengthcode)) < 0) goto bad_data; if (lensymbol > (int)(sizeof(lengthbases)/sizeof(lengthbases[0]))) goto bad_data; if (lensymbol > (int)(sizeof(lengthbits)/sizeof(lengthbits[0]))) goto bad_data; len = lengthbases[lensymbol] + 2; if (lengthbits[lensymbol] > 0) { if (!rar_br_read_ahead(a, br, lengthbits[lensymbol])) goto truncated_data; len += rar_br_bits(br, lengthbits[lensymbol]); rar_br_consume(br, lengthbits[lensymbol]); } for (i = offsindex; i > 0; i--) rar->oldoffset[i] = rar->oldoffset[i-1]; rar->oldoffset[0] = offs; } else if(symbol<=270) { offs = shortbases[symbol-263] + 1; if(shortbits[symbol-263] > 0) { if (!rar_br_read_ahead(a, br, shortbits[symbol-263])) goto truncated_data; offs += rar_br_bits(br, shortbits[symbol-263]); rar_br_consume(br, shortbits[symbol-263]); } len = 2; for(i = 3; i > 0; i--) rar->oldoffset[i] = rar->oldoffset[i-1]; rar->oldoffset[0] = offs; } else { if (symbol-271 > (int)(sizeof(lengthbases)/sizeof(lengthbases[0]))) goto bad_data; if (symbol-271 > (int)(sizeof(lengthbits)/sizeof(lengthbits[0]))) goto bad_data; len = lengthbases[symbol-271]+3; if(lengthbits[symbol-271] > 0) { if (!rar_br_read_ahead(a, br, lengthbits[symbol-271])) goto truncated_data; len += rar_br_bits(br, lengthbits[symbol-271]); rar_br_consume(br, lengthbits[symbol-271]); } if ((offssymbol = read_next_symbol(a, &rar->offsetcode)) < 0) goto bad_data; if (offssymbol > (int)(sizeof(offsetbases)/sizeof(offsetbases[0]))) goto bad_data; if (offssymbol > (int)(sizeof(offsetbits)/sizeof(offsetbits[0]))) goto bad_data; offs = offsetbases[offssymbol]+1; if(offsetbits[offssymbol] > 0) { if(offssymbol > 9) { if(offsetbits[offssymbol] > 4) { if (!rar_br_read_ahead(a, br, offsetbits[offssymbol] - 4)) goto truncated_data; offs += rar_br_bits(br, offsetbits[offssymbol] - 4) << 4; rar_br_consume(br, offsetbits[offssymbol] - 4); } if(rar->numlowoffsetrepeats > 0) { rar->numlowoffsetrepeats--; offs += rar->lastlowoffset; } else { if ((lowoffsetsymbol = read_next_symbol(a, &rar->lowoffsetcode)) < 0) return (ARCHIVE_FATAL); if(lowoffsetsymbol == 16) { rar->numlowoffsetrepeats = 15; offs += rar->lastlowoffset; } else { offs += lowoffsetsymbol; rar->lastlowoffset = lowoffsetsymbol; } } } else { if (!rar_br_read_ahead(a, br, offsetbits[offssymbol])) goto truncated_data; offs += rar_br_bits(br, offsetbits[offssymbol]); rar_br_consume(br, offsetbits[offssymbol]); } } if (offs >= 0x40000) len++; if (offs >= 0x2000) len++; for(i = 3; i > 0; i--) rar->oldoffset[i] = rar->oldoffset[i-1]; rar->oldoffset[0] = offs; } rar->lastoffset = offs; rar->lastlength = len; rar->output_last_match = 1; } truncated_data: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return (ARCHIVE_FATAL); bad_data: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file data"); return (ARCHIVE_FATAL); } static int copy_from_lzss_window(struct archive_read *a, const void **buffer, int64_t startpos, int length) { int windowoffs, firstpart; struct rar *rar = (struct rar *)(a->format->data); if (!rar->unp_buffer) { if ((rar->unp_buffer = malloc(rar->unp_buffer_size)) == NULL) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for uncompressed data."); return (ARCHIVE_FATAL); } } windowoffs = lzss_offset_for_position(&rar->lzss, startpos); if(windowoffs + length <= lzss_size(&rar->lzss)) { memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs], length); } else if (length <= lzss_size(&rar->lzss)) { firstpart = lzss_size(&rar->lzss) - windowoffs; if (firstpart < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file data"); return (ARCHIVE_FATAL); } if (firstpart < length) { memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs], firstpart); memcpy(&rar->unp_buffer[rar->unp_offset + firstpart], &rar->lzss.window[0], length - firstpart); } else { memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs], length); } } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file data"); return (ARCHIVE_FATAL); } rar->unp_offset += length; if (rar->unp_offset >= rar->unp_buffer_size) *buffer = rar->unp_buffer; else *buffer = NULL; return (ARCHIVE_OK); } static const void * rar_read_ahead(struct archive_read *a, size_t min, ssize_t *avail) { struct rar *rar = (struct rar *)(a->format->data); const void *h = __archive_read_ahead(a, min, avail); int ret; if (avail) { if (a->archive.read_data_is_posix_read && *avail > (ssize_t)a->archive.read_data_requested) *avail = a->archive.read_data_requested; if (*avail > rar->bytes_remaining) *avail = (ssize_t)rar->bytes_remaining; if (*avail < 0) return NULL; else if (*avail == 0 && rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER) { ret = archive_read_format_rar_read_header(a, a->entry); if (ret == (ARCHIVE_EOF)) { rar->has_endarc_header = 1; ret = archive_read_format_rar_read_header(a, a->entry); } if (ret != (ARCHIVE_OK)) return NULL; return rar_read_ahead(a, min, avail); } } return h; }
./CrossVul/dataset_final_sorted/CWE-193/c/good_2801_0
crossvul-cpp_data_good_3860_1
/* * Copyright (c) 2016 Intel Corporation. * * SPDX-License-Identifier: Apache-2.0 */ #include <tc_util.h> #include <mqtt_internal.h> #include <sys/util.h> /* for ARRAY_SIZE */ #include <ztest.h> #define CLIENTID MQTT_UTF8_LITERAL("zephyr") #define TOPIC MQTT_UTF8_LITERAL("sensors") #define WILL_TOPIC MQTT_UTF8_LITERAL("quitting") #define WILL_MSG MQTT_UTF8_LITERAL("bye") #define USERNAME MQTT_UTF8_LITERAL("zephyr1") #define PASSWORD MQTT_UTF8_LITERAL("password") #define BUFFER_SIZE 128 static ZTEST_DMEM u8_t rx_buffer[BUFFER_SIZE]; static ZTEST_DMEM u8_t tx_buffer[BUFFER_SIZE]; static ZTEST_DMEM struct mqtt_client client; static ZTEST_DMEM struct mqtt_topic topic_qos_0 = { .qos = 0, .topic = TOPIC, }; static ZTEST_DMEM struct mqtt_topic topic_qos_1 = { .qos = 1, .topic = TOPIC, }; static ZTEST_DMEM struct mqtt_topic topic_qos_2 = { .qos = 2, .topic = TOPIC, }; static ZTEST_DMEM struct mqtt_topic will_topic_qos_0 = { .qos = 0, .topic = WILL_TOPIC, }; static ZTEST_DMEM struct mqtt_topic will_topic_qos_1 = { .qos = 1, .topic = WILL_TOPIC, }; static ZTEST_DMEM struct mqtt_utf8 will_msg = WILL_MSG; static ZTEST_DMEM struct mqtt_utf8 username = USERNAME; static ZTEST_DMEM struct mqtt_utf8 password = PASSWORD; /** * @brief MQTT test structure */ struct mqtt_test { /* test name, for example: "test connect 1" */ const char *test_name; /* cast to something like: * struct mqtt_publish_param *msg_publish = * (struct mqtt_publish_param *)ctx */ void *ctx; /* pointer to the eval routine, for example: * eval_fcn = eval_msg_connect */ int (*eval_fcn)(struct mqtt_test *); /* expected result */ u8_t *expected; /* length of 'expected' */ u16_t expected_len; }; /** * @brief eval_msg_connect Evaluate the given mqtt_test against the * connect packing/unpacking routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_connect(struct mqtt_test *mqtt_test); /** * @brief eval_msg_publish Evaluate the given mqtt_test against the * publish packing/unpacking routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_publish(struct mqtt_test *mqtt_test); /** * @brief eval_msg_subscribe Evaluate the given mqtt_test against the * subscribe packing/unpacking routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_subscribe(struct mqtt_test *mqtt_test); /** * @brief eval_msg_suback Evaluate the given mqtt_test against the * suback packing/unpacking routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_suback(struct mqtt_test *mqtt_test); /** * @brief eval_msg_pingreq Evaluate the given mqtt_test against the * pingreq packing/unpacking routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_pingreq(struct mqtt_test *mqtt_test); /** * @brief eval_msg_puback Evaluate the given mqtt_test against the * puback routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_puback(struct mqtt_test *mqtt_test); /** * @brief eval_msg_puback Evaluate the given mqtt_test against the * pubcomp routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_pubcomp(struct mqtt_test *mqtt_test); /** * @brief eval_msg_pubrec Evaluate the given mqtt_test against the * pubrec routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_pubrec(struct mqtt_test *mqtt_test); /** * @brief eval_msg_pubrel Evaluate the given mqtt_test against the * pubrel routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_pubrel(struct mqtt_test *mqtt_test); /** * @brief eval_msg_unsuback Evaluate the given mqtt_test against the * unsuback routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_unsuback(struct mqtt_test *mqtt_test); /** * @brief eval_msg_disconnect Evaluate the given mqtt_test against the * disconnect routines. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_msg_disconnect(struct mqtt_test *mqtt_test); /** * @brief eval_max_pkt_len Evaluate header with maximum allowed packet * length. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_max_pkt_len(struct mqtt_test *mqtt_test); /** * @brief eval_corrupted_pkt_len Evaluate header exceeding maximum * allowed packet length. * @param [in] mqtt_test MQTT test structure * @return TC_PASS on success * @return TC_FAIL on error */ static int eval_corrupted_pkt_len(struct mqtt_test *mqtt_test); /** * @brief eval_buffers Evaluate if two given buffers are equal * @param [in] buf Input buffer 1, mostly used as the 'computed' * buffer * @param [in] expected Expected buffer * @param [in] len 'expected' len * @return TC_PASS on success * @return TC_FAIL on error and prints both buffers */ static int eval_buffers(const struct buf_ctx *buf, const u8_t *expected, u16_t len); /** * @brief print_array Prints the array 'a' of 'size' elements * @param a The array * @param size Array's size */ static void print_array(const u8_t *a, u16_t size); /* * MQTT CONNECT msg: * Clean session: 1 Client id: [6] 'zephyr' Will flag: 0 * Will QoS: 0 Will retain: 0 Will topic: [0] * Will msg: [0] Keep alive: 60 User name: [0] * Password: [0] * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -k 60 -t sensors */ static ZTEST_DMEM u8_t connect1[] = {0x10, 0x12, 0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x04, 0x02, 0x00, 0x3c, 0x00, 0x06, 0x7a, 0x65, 0x70, 0x68, 0x79, 0x72}; static ZTEST_DMEM struct mqtt_client client_connect1 = { .clean_session = 1, .client_id = CLIENTID, .will_retain = 0, .will_topic = NULL, .will_message = NULL, .user_name = NULL, .password = NULL }; /* * MQTT CONNECT msg: * Clean session: 1 Client id: [6] 'zephyr' Will flag: 1 * Will QoS: 0 Will retain: 0 Will topic: [8] quitting * Will msg: [3] bye Keep alive: 0 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -k 60 -t sensors --will-topic quitting \ * --will-qos 0 --will-payload bye */ static ZTEST_DMEM u8_t connect2[] = {0x10, 0x21, 0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x04, 0x06, 0x00, 0x3c, 0x00, 0x06, 0x7a, 0x65, 0x70, 0x68, 0x79, 0x72, 0x00, 0x08, 0x71, 0x75, 0x69, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x00, 0x03, 0x62, 0x79, 0x65}; static ZTEST_DMEM struct mqtt_client client_connect2 = { .clean_session = 1, .client_id = CLIENTID, .will_retain = 0, .will_topic = &will_topic_qos_0, .will_message = &will_msg, .user_name = NULL, .password = NULL }; /* * MQTT CONNECT msg: * Same message as connect3, but set Will retain: 1 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -k 60 -t sensors --will-topic quitting \ * --will-qos 0 --will-payload bye --will-retain */ static ZTEST_DMEM u8_t connect3[] = {0x10, 0x21, 0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x04, 0x26, 0x00, 0x3c, 0x00, 0x06, 0x7a, 0x65, 0x70, 0x68, 0x79, 0x72, 0x00, 0x08, 0x71, 0x75, 0x69, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x00, 0x03, 0x62, 0x79, 0x65}; static ZTEST_DMEM struct mqtt_client client_connect3 = { .clean_session = 1, .client_id = CLIENTID, .will_retain = 1, .will_topic = &will_topic_qos_0, .will_message = &will_msg, .user_name = NULL, .password = NULL }; /* * MQTT CONNECT msg: * Same message as connect3, but set Will QoS: 1 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -k 60 -t sensors --will-topic quitting \ * --will-qos 1 --will-payload bye */ static ZTEST_DMEM u8_t connect4[] = {0x10, 0x21, 0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x04, 0x0e, 0x00, 0x3c, 0x00, 0x06, 0x7a, 0x65, 0x70, 0x68, 0x79, 0x72, 0x00, 0x08, 0x71, 0x75, 0x69, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x00, 0x03, 0x62, 0x79, 0x65}; static ZTEST_DMEM struct mqtt_client client_connect4 = { .clean_session = 1, .client_id = CLIENTID, .will_retain = 0, .will_topic = &will_topic_qos_1, .will_message = &will_msg, .user_name = NULL, .password = NULL }; /* * MQTT CONNECT msg: * Same message as connect5, but set Will retain: 1 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -k 60 -t sensors --will-topic quitting \ * --will-qos 1 --will-payload bye --will-retain */ static ZTEST_DMEM u8_t connect5[] = {0x10, 0x21, 0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x04, 0x2e, 0x00, 0x3c, 0x00, 0x06, 0x7a, 0x65, 0x70, 0x68, 0x79, 0x72, 0x00, 0x08, 0x71, 0x75, 0x69, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x00, 0x03, 0x62, 0x79, 0x65}; static ZTEST_DMEM struct mqtt_client client_connect5 = { .clean_session = 1, .client_id = CLIENTID, .will_retain = 1, .will_topic = &will_topic_qos_1, .will_message = &will_msg, .user_name = NULL, .password = NULL }; /* * MQTT CONNECT msg: * Same message as connect6, but set username: zephyr1 and password: password * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -k 60 -t sensors --will-topic quitting \ * --will-qos 1 --will-payload bye --will-retain -u zephyr1 -P password */ static ZTEST_DMEM u8_t connect6[] = {0x10, 0x34, 0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x04, 0xee, 0x00, 0x3c, 0x00, 0x06, 0x7a, 0x65, 0x70, 0x68, 0x79, 0x72, 0x00, 0x08, 0x71, 0x75, 0x69, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x00, 0x03, 0x62, 0x79, 0x65, 0x00, 0x07, 0x7a, 0x65, 0x70, 0x68, 0x79, 0x72, 0x31, 0x00, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64}; static ZTEST_DMEM struct mqtt_client client_connect6 = { .clean_session = 1, .client_id = CLIENTID, .will_retain = 1, .will_topic = &will_topic_qos_1, .will_message = &will_msg, .user_name = &username, .password = &password }; static ZTEST_DMEM u8_t disconnect1[] = {0xe0, 0x00}; /* * MQTT PUBLISH msg: * DUP: 0, QoS: 0, Retain: 0, topic: sensors, message: OK * * Message can be generated by the following command: * mosquitto_pub -V mqttv311 -i zephyr -t sensors -q 0 -m "OK" */ static ZTEST_DMEM u8_t publish1[] = {0x30, 0x0b, 0x00, 0x07, 0x73, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x4f, 0x4b}; static ZTEST_DMEM struct mqtt_publish_param msg_publish1 = { .dup_flag = 0, .retain_flag = 0, .message_id = 0, .message.topic.qos = 0, .message.topic.topic = TOPIC, .message.payload.data = (u8_t *)"OK", .message.payload.len = 2, }; /* * MQTT PUBLISH msg: * DUP: 0, QoS: 0, Retain: 1, topic: sensors, message: OK * * Message can be generated by the following command: * mosquitto_pub -V mqttv311 -i zephyr -t sensors -q 0 -m "OK" -r */ static ZTEST_DMEM u8_t publish2[] = {0x31, 0x0b, 0x00, 0x07, 0x73, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x4f, 0x4b}; static ZTEST_DMEM struct mqtt_publish_param msg_publish2 = { .dup_flag = 0, .retain_flag = 1, .message_id = 0, .message.topic.qos = 0, .message.topic.topic = TOPIC, .message.payload.data = (u8_t *)"OK", .message.payload.len = 2, }; /* * MQTT PUBLISH msg: * DUP: 0, QoS: 1, Retain: 1, topic: sensors, message: OK, pkt_id: 1 * * Message can be generated by the following command: * mosquitto_pub -V mqttv311 -i zephyr -t sensors -q 1 -m "OK" -r */ static ZTEST_DMEM u8_t publish3[] = {0x33, 0x0d, 0x00, 0x07, 0x73, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x00, 0x01, 0x4f, 0x4b}; static ZTEST_DMEM struct mqtt_publish_param msg_publish3 = { .dup_flag = 0, .retain_flag = 1, .message_id = 1, .message.topic.qos = 1, .message.topic.topic = TOPIC, .message.payload.data = (u8_t *)"OK", .message.payload.len = 2, }; /* * MQTT PUBLISH msg: * DUP: 0, QoS: 2, Retain: 0, topic: sensors, message: OK, pkt_id: 1 * * Message can be generated by the following command: * mosquitto_pub -V mqttv311 -i zephyr -t sensors -q 2 -m "OK" */ static ZTEST_DMEM u8_t publish4[] = {0x34, 0x0d, 0x00, 0x07, 0x73, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x00, 0x01, 0x4f, 0x4b}; static ZTEST_DMEM struct mqtt_publish_param msg_publish4 = { .dup_flag = 0, .retain_flag = 0, .message_id = 1, .message.topic.qos = 2, .message.topic.topic = TOPIC, .message.payload.data = (u8_t *)"OK", .message.payload.len = 2, }; /* * MQTT SUBSCRIBE msg: * pkt_id: 1, topic: sensors, qos: 0 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -t sensors -q 0 */ static ZTEST_DMEM u8_t subscribe1[] = {0x82, 0x0c, 0x00, 0x01, 0x00, 0x07, 0x73, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x00}; static ZTEST_DMEM struct mqtt_subscription_list msg_subscribe1 = { .message_id = 1, .list_count = 1, .list = &topic_qos_0 }; /* * MQTT SUBSCRIBE msg: * pkt_id: 1, topic: sensors, qos: 1 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -t sensors -q 1 */ static ZTEST_DMEM u8_t subscribe2[] = {0x82, 0x0c, 0x00, 0x01, 0x00, 0x07, 0x73, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x01}; static ZTEST_DMEM struct mqtt_subscription_list msg_subscribe2 = { .message_id = 1, .list_count = 1, .list = &topic_qos_1 }; /* * MQTT SUBSCRIBE msg: * pkt_id: 1, topic: sensors, qos: 2 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -t sensors -q 2 */ static ZTEST_DMEM u8_t subscribe3[] = {0x82, 0x0c, 0x00, 0x01, 0x00, 0x07, 0x73, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x73, 0x02}; static ZTEST_DMEM struct mqtt_subscription_list msg_subscribe3 = { .message_id = 1, .list_count = 1, .list = &topic_qos_2 }; /* * MQTT SUBACK msg * pkt_id: 1, qos: 0 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -t sensors -q 0 */ static ZTEST_DMEM u8_t suback1[] = {0x90, 0x03, 0x00, 0x01, 0x00}; static ZTEST_DMEM u8_t data_suback1[] = { MQTT_SUBACK_SUCCESS_QoS_0 }; static ZTEST_DMEM struct mqtt_suback_param msg_suback1 = { .message_id = 1, .return_codes.len = 1, .return_codes.data = data_suback1 }; /* * MQTT SUBACK message * pkt_id: 1, qos: 1 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -t sensors -q 1 */ static ZTEST_DMEM u8_t suback2[] = {0x90, 0x03, 0x00, 0x01, 0x01}; static ZTEST_DMEM u8_t data_suback2[] = { MQTT_SUBACK_SUCCESS_QoS_1 }; static ZTEST_DMEM struct mqtt_suback_param msg_suback2 = { .message_id = 1, .return_codes.len = 1, .return_codes.data = data_suback2 }; /* * MQTT SUBACK message * pkt_id: 1, qos: 2 * * Message can be generated by the following command: * mosquitto_sub -V mqttv311 -i zephyr -t sensors -q 2 */ static ZTEST_DMEM u8_t suback3[] = {0x90, 0x03, 0x00, 0x01, 0x02}; static ZTEST_DMEM u8_t data_suback3[] = { MQTT_SUBACK_SUCCESS_QoS_2 }; static ZTEST_DMEM struct mqtt_suback_param msg_suback3 = { .message_id = 1, .return_codes.len = 1, .return_codes.data = data_suback3 }; static ZTEST_DMEM u8_t pingreq1[] = {0xc0, 0x00}; static ZTEST_DMEM u8_t puback1[] = {0x40, 0x02, 0x00, 0x01}; static ZTEST_DMEM struct mqtt_puback_param msg_puback1 = {.message_id = 1}; static ZTEST_DMEM u8_t pubrec1[] = {0x50, 0x02, 0x00, 0x01}; static ZTEST_DMEM struct mqtt_pubrec_param msg_pubrec1 = {.message_id = 1}; static ZTEST_DMEM u8_t pubrel1[] = {0x62, 0x02, 0x00, 0x01}; static ZTEST_DMEM struct mqtt_pubrel_param msg_pubrel1 = {.message_id = 1}; static ZTEST_DMEM u8_t pubcomp1[] = {0x70, 0x02, 0x00, 0x01}; static ZTEST_DMEM struct mqtt_pubcomp_param msg_pubcomp1 = {.message_id = 1}; static ZTEST_DMEM u8_t unsuback1[] = {0xb0, 0x02, 0x00, 0x01}; static ZTEST_DMEM struct mqtt_unsuback_param msg_unsuback1 = {.message_id = 1}; static ZTEST_DMEM u8_t max_pkt_len[] = {0x30, 0xff, 0xff, 0xff, 0x7f}; static ZTEST_DMEM struct buf_ctx max_pkt_len_buf = { .cur = max_pkt_len, .end = max_pkt_len + sizeof(max_pkt_len) }; static ZTEST_DMEM u8_t corrupted_pkt_len[] = {0x30, 0xff, 0xff, 0xff, 0xff, 0x01}; static ZTEST_DMEM struct buf_ctx corrupted_pkt_len_buf = { .cur = corrupted_pkt_len, .end = corrupted_pkt_len + sizeof(corrupted_pkt_len) }; static ZTEST_DMEM struct mqtt_test mqtt_tests[] = { {.test_name = "CONNECT, new session, zeros", .ctx = &client_connect1, .eval_fcn = eval_msg_connect, .expected = connect1, .expected_len = sizeof(connect1)}, {.test_name = "CONNECT, new session, will", .ctx = &client_connect2, .eval_fcn = eval_msg_connect, .expected = connect2, .expected_len = sizeof(connect2)}, {.test_name = "CONNECT, new session, will retain", .ctx = &client_connect3, .eval_fcn = eval_msg_connect, .expected = connect3, .expected_len = sizeof(connect3)}, {.test_name = "CONNECT, new session, will qos = 1", .ctx = &client_connect4, .eval_fcn = eval_msg_connect, .expected = connect4, .expected_len = sizeof(connect4)}, {.test_name = "CONNECT, new session, will qos = 1, will retain", .ctx = &client_connect5, .eval_fcn = eval_msg_connect, .expected = connect5, .expected_len = sizeof(connect5)}, {.test_name = "CONNECT, new session, username and password", .ctx = &client_connect6, .eval_fcn = eval_msg_connect, .expected = connect6, .expected_len = sizeof(connect6)}, {.test_name = "DISCONNECT", .ctx = NULL, .eval_fcn = eval_msg_disconnect, .expected = disconnect1, .expected_len = sizeof(disconnect1)}, {.test_name = "PUBLISH, qos = 0", .ctx = &msg_publish1, .eval_fcn = eval_msg_publish, .expected = publish1, .expected_len = sizeof(publish1)}, {.test_name = "PUBLISH, retain = 1", .ctx = &msg_publish2, .eval_fcn = eval_msg_publish, .expected = publish2, .expected_len = sizeof(publish2)}, {.test_name = "PUBLISH, retain = 1, qos = 1", .ctx = &msg_publish3, .eval_fcn = eval_msg_publish, .expected = publish3, .expected_len = sizeof(publish3)}, {.test_name = "PUBLISH, qos = 2", .ctx = &msg_publish4, .eval_fcn = eval_msg_publish, .expected = publish4, .expected_len = sizeof(publish4)}, {.test_name = "SUBSCRIBE, one topic, qos = 0", .ctx = &msg_subscribe1, .eval_fcn = eval_msg_subscribe, .expected = subscribe1, .expected_len = sizeof(subscribe1)}, {.test_name = "SUBSCRIBE, one topic, qos = 1", .ctx = &msg_subscribe2, .eval_fcn = eval_msg_subscribe, .expected = subscribe2, .expected_len = sizeof(subscribe2)}, {.test_name = "SUBSCRIBE, one topic, qos = 2", .ctx = &msg_subscribe3, .eval_fcn = eval_msg_subscribe, .expected = subscribe3, .expected_len = sizeof(subscribe3)}, {.test_name = "SUBACK, one topic, qos = 0", .ctx = &msg_suback1, .eval_fcn = eval_msg_suback, .expected = suback1, .expected_len = sizeof(suback1)}, {.test_name = "SUBACK, one topic, qos = 1", .ctx = &msg_suback2, .eval_fcn = eval_msg_suback, .expected = suback2, .expected_len = sizeof(suback2)}, {.test_name = "SUBACK, one topic, qos = 2", .ctx = &msg_suback3, .eval_fcn = eval_msg_suback, .expected = suback3, .expected_len = sizeof(suback3)}, {.test_name = "PINGREQ", .ctx = NULL, .eval_fcn = eval_msg_pingreq, .expected = pingreq1, .expected_len = sizeof(pingreq1)}, {.test_name = "PUBACK", .ctx = &msg_puback1, .eval_fcn = eval_msg_puback, .expected = puback1, .expected_len = sizeof(puback1)}, {.test_name = "PUBREC", .ctx = &msg_pubrec1, .eval_fcn = eval_msg_pubrec, .expected = pubrec1, .expected_len = sizeof(pubrec1)}, {.test_name = "PUBREL", .ctx = &msg_pubrel1, .eval_fcn = eval_msg_pubrel, .expected = pubrel1, .expected_len = sizeof(pubrel1)}, {.test_name = "PUBCOMP", .ctx = &msg_pubcomp1, .eval_fcn = eval_msg_pubcomp, .expected = pubcomp1, .expected_len = sizeof(pubcomp1)}, {.test_name = "UNSUBACK", .ctx = &msg_unsuback1, .eval_fcn = eval_msg_unsuback, .expected = unsuback1, .expected_len = sizeof(unsuback1)}, {.test_name = "Maximum packet length", .ctx = &max_pkt_len_buf, .eval_fcn = eval_max_pkt_len}, {.test_name = "Corrupted packet length", .ctx = &corrupted_pkt_len_buf, .eval_fcn = eval_corrupted_pkt_len}, /* last test case, do not remove it */ {.test_name = NULL} }; static void print_array(const u8_t *a, u16_t size) { u16_t i; TC_PRINT("\n"); for (i = 0U; i < size; i++) { TC_PRINT("%x ", a[i]); if ((i+1) % 8 == 0U) { TC_PRINT("\n"); } } TC_PRINT("\n"); } static int eval_buffers(const struct buf_ctx *buf, const u8_t *expected, u16_t len) { if (buf->end - buf->cur != len) { goto exit_eval; } if (memcmp(expected, buf->cur, buf->end - buf->cur) != 0) { goto exit_eval; } return TC_PASS; exit_eval: TC_PRINT("FAIL\n"); TC_PRINT("Computed:"); print_array(buf->cur, buf->end - buf->cur); TC_PRINT("Expected:"); print_array(expected, len); return TC_FAIL; } static int eval_msg_connect(struct mqtt_test *mqtt_test) { struct mqtt_client *test_client; int rc; struct buf_ctx buf; test_client = (struct mqtt_client *)mqtt_test->ctx; client.clean_session = test_client->clean_session; client.client_id = test_client->client_id; client.will_topic = test_client->will_topic; client.will_retain = test_client->will_retain; client.will_message = test_client->will_message; client.user_name = test_client->user_name; client.password = test_client->password; buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = connect_request_encode(&client, &buf); /**TESTPOINTS: Check connect_request_encode functions*/ zassert_false(rc, "connect_request_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); return TC_PASS; } static int eval_msg_disconnect(struct mqtt_test *mqtt_test) { int rc; struct buf_ctx buf; buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = disconnect_encode(&buf); /**TESTPOINTS: Check disconnect_encode functions*/ zassert_false(rc, "disconnect_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); return TC_PASS; } static int eval_msg_publish(struct mqtt_test *mqtt_test) { struct mqtt_publish_param *param = (struct mqtt_publish_param *)mqtt_test->ctx; struct mqtt_publish_param dec_param; int rc; u8_t type_and_flags; u32_t length; struct buf_ctx buf; memset(&dec_param, 0, sizeof(dec_param)); buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = publish_encode(param, &buf); /* Payload is not copied, copy it manually just after the header.*/ memcpy(buf.end, param->message.payload.data, param->message.payload.len); buf.end += param->message.payload.len; /**TESTPOINT: Check publish_encode function*/ zassert_false(rc, "publish_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); rc = fixed_header_decode(&buf, &type_and_flags, &length); zassert_false(rc, "fixed_header_decode failed"); rc = publish_decode(type_and_flags, length, &buf, &dec_param); /**TESTPOINT: Check publish_decode function*/ zassert_false(rc, "publish_decode failed"); zassert_equal(dec_param.message_id, param->message_id, "message_id error"); zassert_equal(dec_param.dup_flag, param->dup_flag, "dup flag error"); zassert_equal(dec_param.retain_flag, param->retain_flag, "retain flag error"); zassert_equal(dec_param.message.topic.qos, param->message.topic.qos, "topic qos error"); zassert_equal(dec_param.message.topic.topic.size, param->message.topic.topic.size, "topic len error"); if (memcmp(dec_param.message.topic.topic.utf8, param->message.topic.topic.utf8, dec_param.message.topic.topic.size) != 0) { zassert_unreachable("topic content error"); } zassert_equal(dec_param.message.payload.len, param->message.payload.len, "payload len error"); return TC_PASS; } static int eval_msg_subscribe(struct mqtt_test *mqtt_test) { struct mqtt_subscription_list *param = (struct mqtt_subscription_list *)mqtt_test->ctx; int rc; struct buf_ctx buf; buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = subscribe_encode(param, &buf); /**TESTPOINT: Check subscribe_encode function*/ zassert_false(rc, "subscribe_encode failed"); return eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); } static int eval_msg_suback(struct mqtt_test *mqtt_test) { struct mqtt_suback_param *param = (struct mqtt_suback_param *)mqtt_test->ctx; struct mqtt_suback_param dec_param; int rc; u8_t type_and_flags; u32_t length; struct buf_ctx buf; buf.cur = mqtt_test->expected; buf.end = mqtt_test->expected + mqtt_test->expected_len; memset(&dec_param, 0, sizeof(dec_param)); rc = fixed_header_decode(&buf, &type_and_flags, &length); zassert_false(rc, "fixed_header_decode failed"); rc = subscribe_ack_decode(&buf, &dec_param); /**TESTPOINT: Check subscribe_ack_decode function*/ zassert_false(rc, "subscribe_ack_decode failed"); zassert_equal(dec_param.message_id, param->message_id, "packet identifier error"); zassert_equal(dec_param.return_codes.len, param->return_codes.len, "topic count error"); if (memcmp(dec_param.return_codes.data, param->return_codes.data, dec_param.return_codes.len) != 0) { zassert_unreachable("subscribe result error"); } return TC_PASS; } static int eval_msg_pingreq(struct mqtt_test *mqtt_test) { int rc; struct buf_ctx buf; buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = ping_request_encode(&buf); /**TESTPOINTS: Check eval_msg_pingreq functions*/ zassert_false(rc, "ping_request_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); return TC_PASS; } static int eval_msg_puback(struct mqtt_test *mqtt_test) { struct mqtt_puback_param *param = (struct mqtt_puback_param *)mqtt_test->ctx; struct mqtt_puback_param dec_param; int rc; u8_t type_and_flags; u32_t length; struct buf_ctx buf; memset(&dec_param, 0, sizeof(dec_param)); buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = publish_ack_encode(param, &buf); /**TESTPOINTS: Check publish_ack_encode functions*/ zassert_false(rc, "publish_ack_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); rc = fixed_header_decode(&buf, &type_and_flags, &length); zassert_false(rc, "fixed_header_decode failed"); rc = publish_ack_decode(&buf, &dec_param); zassert_false(rc, "publish_ack_decode failed"); zassert_equal(dec_param.message_id, param->message_id, "packet identifier error"); return TC_PASS; } static int eval_msg_pubcomp(struct mqtt_test *mqtt_test) { struct mqtt_pubcomp_param *param = (struct mqtt_pubcomp_param *)mqtt_test->ctx; struct mqtt_pubcomp_param dec_param; int rc; u32_t length; u8_t type_and_flags; struct buf_ctx buf; memset(&dec_param, 0, sizeof(dec_param)); buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = publish_complete_encode(param, &buf); /**TESTPOINTS: Check publish_complete_encode functions*/ zassert_false(rc, "publish_complete_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); rc = fixed_header_decode(&buf, &type_and_flags, &length); zassert_false(rc, "fixed_header_decode failed"); rc = publish_complete_decode(&buf, &dec_param); zassert_false(rc, "publish_complete_decode failed"); zassert_equal(dec_param.message_id, param->message_id, "packet identifier error"); return TC_PASS; } static int eval_msg_pubrec(struct mqtt_test *mqtt_test) { struct mqtt_pubrec_param *param = (struct mqtt_pubrec_param *)mqtt_test->ctx; struct mqtt_pubrec_param dec_param; int rc; u32_t length; u8_t type_and_flags; struct buf_ctx buf; memset(&dec_param, 0, sizeof(dec_param)); buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = publish_receive_encode(param, &buf); /**TESTPOINTS: Check publish_receive_encode functions*/ zassert_false(rc, "publish_receive_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); rc = fixed_header_decode(&buf, &type_and_flags, &length); zassert_false(rc, "fixed_header_decode failed"); rc = publish_receive_decode(&buf, &dec_param); zassert_false(rc, "publish_receive_decode failed"); zassert_equal(dec_param.message_id, param->message_id, "packet identifier error"); return TC_PASS; } static int eval_msg_pubrel(struct mqtt_test *mqtt_test) { struct mqtt_pubrel_param *param = (struct mqtt_pubrel_param *)mqtt_test->ctx; struct mqtt_pubrel_param dec_param; int rc; u32_t length; u8_t type_and_flags; struct buf_ctx buf; memset(&dec_param, 0, sizeof(dec_param)); buf.cur = client.tx_buf; buf.end = client.tx_buf + client.tx_buf_size; rc = publish_release_encode(param, &buf); /**TESTPOINTS: Check publish_release_encode functions*/ zassert_false(rc, "publish_release_encode failed"); rc = eval_buffers(&buf, mqtt_test->expected, mqtt_test->expected_len); zassert_false(rc, "eval_buffers failed"); rc = fixed_header_decode(&buf, &type_and_flags, &length); zassert_false(rc, "fixed_header_decode failed"); rc = publish_release_decode(&buf, &dec_param); zassert_false(rc, "publish_release_decode failed"); zassert_equal(dec_param.message_id, param->message_id, "packet identifier error"); return TC_PASS; } static int eval_msg_unsuback(struct mqtt_test *mqtt_test) { struct mqtt_unsuback_param *param = (struct mqtt_unsuback_param *)mqtt_test->ctx; struct mqtt_unsuback_param dec_param; int rc; u32_t length; u8_t type_and_flags; struct buf_ctx buf; memset(&dec_param, 0, sizeof(dec_param)); buf.cur = mqtt_test->expected; buf.end = mqtt_test->expected + mqtt_test->expected_len; rc = fixed_header_decode(&buf, &type_and_flags, &length); zassert_false(rc, "fixed_header_decode failed"); rc = unsubscribe_ack_decode(&buf, &dec_param); zassert_false(rc, "unsubscribe_ack_decode failed"); zassert_equal(dec_param.message_id, param->message_id, "packet identifier error"); return TC_PASS; } static int eval_max_pkt_len(struct mqtt_test *mqtt_test) { struct buf_ctx *buf = (struct buf_ctx *)mqtt_test->ctx; int rc; u8_t flags; u32_t length; rc = fixed_header_decode(buf, &flags, &length); zassert_equal(rc, 0, "fixed_header_decode failed"); zassert_equal(length, MQTT_MAX_PAYLOAD_SIZE, "Invalid packet length decoded"); return TC_PASS; } static int eval_corrupted_pkt_len(struct mqtt_test *mqtt_test) { struct buf_ctx *buf = (struct buf_ctx *)mqtt_test->ctx; int rc; u8_t flags; u32_t length; rc = fixed_header_decode(buf, &flags, &length); zassert_equal(rc, -EINVAL, "fixed_header_decode should fail"); return TC_PASS; } void test_mqtt_packet(void) { TC_START("MQTT Library test"); int rc; int i; mqtt_client_init(&client); client.protocol_version = MQTT_VERSION_3_1_1; client.rx_buf = rx_buffer; client.rx_buf_size = sizeof(rx_buffer); client.tx_buf = tx_buffer; client.tx_buf_size = sizeof(tx_buffer); i = 0; do { struct mqtt_test *test = &mqtt_tests[i]; if (test->test_name == NULL) { break; } rc = test->eval_fcn(test); TC_PRINT("[%s] %d - %s\n", TC_RESULT_TO_STR(rc), i + 1, test->test_name); /**TESTPOINT: Check eval_fcn*/ zassert_false(rc, "mqtt_packet test error"); i++; } while (1); mqtt_abort(&client); } void test_main(void) { ztest_test_suite(test_mqtt_packet_fn, ztest_user_unit_test(test_mqtt_packet)); ztest_run_test_suite(test_mqtt_packet_fn); }
./CrossVul/dataset_final_sorted/CWE-193/c/good_3860_1
crossvul-cpp_data_good_4732_1
/* * Copyright 2007-8 Advanced Micro Devices, Inc. * Copyright 2008 Red Hat Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. * * Authors: Dave Airlie * Alex Deucher */ #include "drmP.h" #include "radeon_drm.h" #include "radeon.h" #include "atom.h" #include "atom-bits.h" /* from radeon_encoder.c */ extern uint32_t radeon_get_encoder_id(struct drm_device *dev, uint32_t supported_device, uint8_t dac); extern void radeon_link_encoder_connector(struct drm_device *dev); extern void radeon_add_atom_encoder(struct drm_device *dev, uint32_t encoder_id, uint32_t supported_device); /* from radeon_connector.c */ extern void radeon_add_atom_connector(struct drm_device *dev, uint32_t connector_id, uint32_t supported_device, int connector_type, struct radeon_i2c_bus_rec *i2c_bus, bool linkb, uint32_t igp_lane_info, uint16_t connector_object_id, struct radeon_hpd *hpd); /* from radeon_legacy_encoder.c */ extern void radeon_add_legacy_encoder(struct drm_device *dev, uint32_t encoder_id, uint32_t supported_device); union atom_supported_devices { struct _ATOM_SUPPORTED_DEVICES_INFO info; struct _ATOM_SUPPORTED_DEVICES_INFO_2 info_2; struct _ATOM_SUPPORTED_DEVICES_INFO_2d1 info_2d1; }; static inline struct radeon_i2c_bus_rec radeon_lookup_i2c_gpio(struct radeon_device *rdev, uint8_t id) { struct atom_context *ctx = rdev->mode_info.atom_context; ATOM_GPIO_I2C_ASSIGMENT *gpio; struct radeon_i2c_bus_rec i2c; int index = GetIndexIntoMasterTable(DATA, GPIO_I2C_Info); struct _ATOM_GPIO_I2C_INFO *i2c_info; uint16_t data_offset, size; int i, num_indices; memset(&i2c, 0, sizeof(struct radeon_i2c_bus_rec)); i2c.valid = false; if (atom_parse_data_header(ctx, index, &size, NULL, NULL, &data_offset)) { i2c_info = (struct _ATOM_GPIO_I2C_INFO *)(ctx->bios + data_offset); num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) / sizeof(ATOM_GPIO_I2C_ASSIGMENT); for (i = 0; i < num_indices; i++) { gpio = &i2c_info->asGPIO_Info[i]; if (gpio->sucI2cId.ucAccess == id) { i2c.mask_clk_reg = le16_to_cpu(gpio->usClkMaskRegisterIndex) * 4; i2c.mask_data_reg = le16_to_cpu(gpio->usDataMaskRegisterIndex) * 4; i2c.en_clk_reg = le16_to_cpu(gpio->usClkEnRegisterIndex) * 4; i2c.en_data_reg = le16_to_cpu(gpio->usDataEnRegisterIndex) * 4; i2c.y_clk_reg = le16_to_cpu(gpio->usClkY_RegisterIndex) * 4; i2c.y_data_reg = le16_to_cpu(gpio->usDataY_RegisterIndex) * 4; i2c.a_clk_reg = le16_to_cpu(gpio->usClkA_RegisterIndex) * 4; i2c.a_data_reg = le16_to_cpu(gpio->usDataA_RegisterIndex) * 4; i2c.mask_clk_mask = (1 << gpio->ucClkMaskShift); i2c.mask_data_mask = (1 << gpio->ucDataMaskShift); i2c.en_clk_mask = (1 << gpio->ucClkEnShift); i2c.en_data_mask = (1 << gpio->ucDataEnShift); i2c.y_clk_mask = (1 << gpio->ucClkY_Shift); i2c.y_data_mask = (1 << gpio->ucDataY_Shift); i2c.a_clk_mask = (1 << gpio->ucClkA_Shift); i2c.a_data_mask = (1 << gpio->ucDataA_Shift); if (gpio->sucI2cId.sbfAccess.bfHW_Capable) i2c.hw_capable = true; else i2c.hw_capable = false; if (gpio->sucI2cId.ucAccess == 0xa0) i2c.mm_i2c = true; else i2c.mm_i2c = false; i2c.i2c_id = gpio->sucI2cId.ucAccess; i2c.valid = true; break; } } } return i2c; } static inline struct radeon_gpio_rec radeon_lookup_gpio(struct radeon_device *rdev, u8 id) { struct atom_context *ctx = rdev->mode_info.atom_context; struct radeon_gpio_rec gpio; int index = GetIndexIntoMasterTable(DATA, GPIO_Pin_LUT); struct _ATOM_GPIO_PIN_LUT *gpio_info; ATOM_GPIO_PIN_ASSIGNMENT *pin; u16 data_offset, size; int i, num_indices; memset(&gpio, 0, sizeof(struct radeon_gpio_rec)); gpio.valid = false; if (atom_parse_data_header(ctx, index, &size, NULL, NULL, &data_offset)) { gpio_info = (struct _ATOM_GPIO_PIN_LUT *)(ctx->bios + data_offset); num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) / sizeof(ATOM_GPIO_PIN_ASSIGNMENT); for (i = 0; i < num_indices; i++) { pin = &gpio_info->asGPIO_Pin[i]; if (id == pin->ucGPIO_ID) { gpio.id = pin->ucGPIO_ID; gpio.reg = pin->usGpioPin_AIndex * 4; gpio.mask = (1 << pin->ucGpioPinBitShift); gpio.valid = true; break; } } } return gpio; } static struct radeon_hpd radeon_atom_get_hpd_info_from_gpio(struct radeon_device *rdev, struct radeon_gpio_rec *gpio) { struct radeon_hpd hpd; u32 reg; if (ASIC_IS_DCE4(rdev)) reg = EVERGREEN_DC_GPIO_HPD_A; else reg = AVIVO_DC_GPIO_HPD_A; hpd.gpio = *gpio; if (gpio->reg == reg) { switch(gpio->mask) { case (1 << 0): hpd.hpd = RADEON_HPD_1; break; case (1 << 8): hpd.hpd = RADEON_HPD_2; break; case (1 << 16): hpd.hpd = RADEON_HPD_3; break; case (1 << 24): hpd.hpd = RADEON_HPD_4; break; case (1 << 26): hpd.hpd = RADEON_HPD_5; break; case (1 << 28): hpd.hpd = RADEON_HPD_6; break; default: hpd.hpd = RADEON_HPD_NONE; break; } } else hpd.hpd = RADEON_HPD_NONE; return hpd; } static bool radeon_atom_apply_quirks(struct drm_device *dev, uint32_t supported_device, int *connector_type, struct radeon_i2c_bus_rec *i2c_bus, uint16_t *line_mux, struct radeon_hpd *hpd) { /* Asus M2A-VM HDMI board lists the DVI port as HDMI */ if ((dev->pdev->device == 0x791e) && (dev->pdev->subsystem_vendor == 0x1043) && (dev->pdev->subsystem_device == 0x826d)) { if ((*connector_type == DRM_MODE_CONNECTOR_HDMIA) && (supported_device == ATOM_DEVICE_DFP3_SUPPORT)) *connector_type = DRM_MODE_CONNECTOR_DVID; } /* Asrock RS600 board lists the DVI port as HDMI */ if ((dev->pdev->device == 0x7941) && (dev->pdev->subsystem_vendor == 0x1849) && (dev->pdev->subsystem_device == 0x7941)) { if ((*connector_type == DRM_MODE_CONNECTOR_HDMIA) && (supported_device == ATOM_DEVICE_DFP3_SUPPORT)) *connector_type = DRM_MODE_CONNECTOR_DVID; } /* a-bit f-i90hd - ciaranm on #radeonhd - this board has no DVI */ if ((dev->pdev->device == 0x7941) && (dev->pdev->subsystem_vendor == 0x147b) && (dev->pdev->subsystem_device == 0x2412)) { if (*connector_type == DRM_MODE_CONNECTOR_DVII) return false; } /* Falcon NW laptop lists vga ddc line for LVDS */ if ((dev->pdev->device == 0x5653) && (dev->pdev->subsystem_vendor == 0x1462) && (dev->pdev->subsystem_device == 0x0291)) { if (*connector_type == DRM_MODE_CONNECTOR_LVDS) { i2c_bus->valid = false; *line_mux = 53; } } /* HIS X1300 is DVI+VGA, not DVI+DVI */ if ((dev->pdev->device == 0x7146) && (dev->pdev->subsystem_vendor == 0x17af) && (dev->pdev->subsystem_device == 0x2058)) { if (supported_device == ATOM_DEVICE_DFP1_SUPPORT) return false; } /* Gigabyte X1300 is DVI+VGA, not DVI+DVI */ if ((dev->pdev->device == 0x7142) && (dev->pdev->subsystem_vendor == 0x1458) && (dev->pdev->subsystem_device == 0x2134)) { if (supported_device == ATOM_DEVICE_DFP1_SUPPORT) return false; } /* Funky macbooks */ if ((dev->pdev->device == 0x71C5) && (dev->pdev->subsystem_vendor == 0x106b) && (dev->pdev->subsystem_device == 0x0080)) { if ((supported_device == ATOM_DEVICE_CRT1_SUPPORT) || (supported_device == ATOM_DEVICE_DFP2_SUPPORT)) return false; if (supported_device == ATOM_DEVICE_CRT2_SUPPORT) *line_mux = 0x90; } /* ASUS HD 3600 XT board lists the DVI port as HDMI */ if ((dev->pdev->device == 0x9598) && (dev->pdev->subsystem_vendor == 0x1043) && (dev->pdev->subsystem_device == 0x01da)) { if (*connector_type == DRM_MODE_CONNECTOR_HDMIA) { *connector_type = DRM_MODE_CONNECTOR_DVII; } } /* ASUS HD 3450 board lists the DVI port as HDMI */ if ((dev->pdev->device == 0x95C5) && (dev->pdev->subsystem_vendor == 0x1043) && (dev->pdev->subsystem_device == 0x01e2)) { if (*connector_type == DRM_MODE_CONNECTOR_HDMIA) { *connector_type = DRM_MODE_CONNECTOR_DVII; } } /* some BIOSes seem to report DAC on HDMI - usually this is a board with * HDMI + VGA reporting as HDMI */ if (*connector_type == DRM_MODE_CONNECTOR_HDMIA) { if (supported_device & (ATOM_DEVICE_CRT_SUPPORT)) { *connector_type = DRM_MODE_CONNECTOR_VGA; *line_mux = 0; } } /* Acer laptop reports DVI-D as DVI-I */ if ((dev->pdev->device == 0x95c4) && (dev->pdev->subsystem_vendor == 0x1025) && (dev->pdev->subsystem_device == 0x013c)) { if ((*connector_type == DRM_MODE_CONNECTOR_DVII) && (supported_device == ATOM_DEVICE_DFP1_SUPPORT)) *connector_type = DRM_MODE_CONNECTOR_DVID; } /* XFX Pine Group device rv730 reports no VGA DDC lines * even though they are wired up to record 0x93 */ if ((dev->pdev->device == 0x9498) && (dev->pdev->subsystem_vendor == 0x1682) && (dev->pdev->subsystem_device == 0x2452)) { struct radeon_device *rdev = dev->dev_private; *i2c_bus = radeon_lookup_i2c_gpio(rdev, 0x93); } return true; } const int supported_devices_connector_convert[] = { DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_VGA, DRM_MODE_CONNECTOR_DVII, DRM_MODE_CONNECTOR_DVID, DRM_MODE_CONNECTOR_DVIA, DRM_MODE_CONNECTOR_SVIDEO, DRM_MODE_CONNECTOR_Composite, DRM_MODE_CONNECTOR_LVDS, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_HDMIA, DRM_MODE_CONNECTOR_HDMIB, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_9PinDIN, DRM_MODE_CONNECTOR_DisplayPort }; const uint16_t supported_devices_connector_object_id_convert[] = { CONNECTOR_OBJECT_ID_NONE, CONNECTOR_OBJECT_ID_VGA, CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_I, /* not all boards support DL */ CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_D, /* not all boards support DL */ CONNECTOR_OBJECT_ID_VGA, /* technically DVI-A */ CONNECTOR_OBJECT_ID_COMPOSITE, CONNECTOR_OBJECT_ID_SVIDEO, CONNECTOR_OBJECT_ID_LVDS, CONNECTOR_OBJECT_ID_9PIN_DIN, CONNECTOR_OBJECT_ID_9PIN_DIN, CONNECTOR_OBJECT_ID_DISPLAYPORT, CONNECTOR_OBJECT_ID_HDMI_TYPE_A, CONNECTOR_OBJECT_ID_HDMI_TYPE_B, CONNECTOR_OBJECT_ID_SVIDEO }; const int object_connector_convert[] = { DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_DVII, DRM_MODE_CONNECTOR_DVII, DRM_MODE_CONNECTOR_DVID, DRM_MODE_CONNECTOR_DVID, DRM_MODE_CONNECTOR_VGA, DRM_MODE_CONNECTOR_Composite, DRM_MODE_CONNECTOR_SVIDEO, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_9PinDIN, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_HDMIA, DRM_MODE_CONNECTOR_HDMIB, DRM_MODE_CONNECTOR_LVDS, DRM_MODE_CONNECTOR_9PinDIN, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_DisplayPort, DRM_MODE_CONNECTOR_eDP, DRM_MODE_CONNECTOR_Unknown }; bool radeon_get_atom_connector_info_from_object_table(struct drm_device *dev) { struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; struct atom_context *ctx = mode_info->atom_context; int index = GetIndexIntoMasterTable(DATA, Object_Header); u16 size, data_offset; u8 frev, crev; ATOM_CONNECTOR_OBJECT_TABLE *con_obj; ATOM_DISPLAY_OBJECT_PATH_TABLE *path_obj; ATOM_OBJECT_HEADER *obj_header; int i, j, path_size, device_support; int connector_type; u16 igp_lane_info, conn_id, connector_object_id; bool linkb; struct radeon_i2c_bus_rec ddc_bus; struct radeon_gpio_rec gpio; struct radeon_hpd hpd; if (!atom_parse_data_header(ctx, index, &size, &frev, &crev, &data_offset)) return false; if (crev < 2) return false; obj_header = (ATOM_OBJECT_HEADER *) (ctx->bios + data_offset); path_obj = (ATOM_DISPLAY_OBJECT_PATH_TABLE *) (ctx->bios + data_offset + le16_to_cpu(obj_header->usDisplayPathTableOffset)); con_obj = (ATOM_CONNECTOR_OBJECT_TABLE *) (ctx->bios + data_offset + le16_to_cpu(obj_header->usConnectorObjectTableOffset)); device_support = le16_to_cpu(obj_header->usDeviceSupport); path_size = 0; for (i = 0; i < path_obj->ucNumOfDispPath; i++) { uint8_t *addr = (uint8_t *) path_obj->asDispPath; ATOM_DISPLAY_OBJECT_PATH *path; addr += path_size; path = (ATOM_DISPLAY_OBJECT_PATH *) addr; path_size += le16_to_cpu(path->usSize); linkb = false; if (device_support & le16_to_cpu(path->usDeviceTag)) { uint8_t con_obj_id, con_obj_num, con_obj_type; con_obj_id = (le16_to_cpu(path->usConnObjectId) & OBJECT_ID_MASK) >> OBJECT_ID_SHIFT; con_obj_num = (le16_to_cpu(path->usConnObjectId) & ENUM_ID_MASK) >> ENUM_ID_SHIFT; con_obj_type = (le16_to_cpu(path->usConnObjectId) & OBJECT_TYPE_MASK) >> OBJECT_TYPE_SHIFT; /* TODO CV support */ if (le16_to_cpu(path->usDeviceTag) == ATOM_DEVICE_CV_SUPPORT) continue; /* IGP chips */ if ((rdev->flags & RADEON_IS_IGP) && (con_obj_id == CONNECTOR_OBJECT_ID_PCIE_CONNECTOR)) { uint16_t igp_offset = 0; ATOM_INTEGRATED_SYSTEM_INFO_V2 *igp_obj; index = GetIndexIntoMasterTable(DATA, IntegratedSystemInfo); if (atom_parse_data_header(ctx, index, &size, &frev, &crev, &igp_offset)) { if (crev >= 2) { igp_obj = (ATOM_INTEGRATED_SYSTEM_INFO_V2 *) (ctx->bios + igp_offset); if (igp_obj) { uint32_t slot_config, ct; if (con_obj_num == 1) slot_config = igp_obj-> ulDDISlot1Config; else slot_config = igp_obj-> ulDDISlot2Config; ct = (slot_config >> 16) & 0xff; connector_type = object_connector_convert [ct]; connector_object_id = ct; igp_lane_info = slot_config & 0xffff; } else continue; } else continue; } else { igp_lane_info = 0; connector_type = object_connector_convert[con_obj_id]; connector_object_id = con_obj_id; } } else { igp_lane_info = 0; connector_type = object_connector_convert[con_obj_id]; connector_object_id = con_obj_id; } if (connector_type == DRM_MODE_CONNECTOR_Unknown) continue; for (j = 0; j < ((le16_to_cpu(path->usSize) - 8) / 2); j++) { uint8_t enc_obj_id, enc_obj_num, enc_obj_type; enc_obj_id = (le16_to_cpu(path->usGraphicObjIds[j]) & OBJECT_ID_MASK) >> OBJECT_ID_SHIFT; enc_obj_num = (le16_to_cpu(path->usGraphicObjIds[j]) & ENUM_ID_MASK) >> ENUM_ID_SHIFT; enc_obj_type = (le16_to_cpu(path->usGraphicObjIds[j]) & OBJECT_TYPE_MASK) >> OBJECT_TYPE_SHIFT; /* FIXME: add support for router objects */ if (enc_obj_type == GRAPH_OBJECT_TYPE_ENCODER) { if (enc_obj_num == 2) linkb = true; else linkb = false; radeon_add_atom_encoder(dev, enc_obj_id, le16_to_cpu (path-> usDeviceTag)); } } /* look up gpio for ddc, hpd */ if ((le16_to_cpu(path->usDeviceTag) & (ATOM_DEVICE_TV_SUPPORT | ATOM_DEVICE_CV_SUPPORT)) == 0) { for (j = 0; j < con_obj->ucNumberOfObjects; j++) { if (le16_to_cpu(path->usConnObjectId) == le16_to_cpu(con_obj->asObjects[j]. usObjectID)) { ATOM_COMMON_RECORD_HEADER *record = (ATOM_COMMON_RECORD_HEADER *) (ctx->bios + data_offset + le16_to_cpu(con_obj-> asObjects[j]. usRecordOffset)); ATOM_I2C_RECORD *i2c_record; ATOM_HPD_INT_RECORD *hpd_record; ATOM_I2C_ID_CONFIG_ACCESS *i2c_config; hpd.hpd = RADEON_HPD_NONE; while (record->ucRecordType > 0 && record-> ucRecordType <= ATOM_MAX_OBJECT_RECORD_NUMBER) { switch (record->ucRecordType) { case ATOM_I2C_RECORD_TYPE: i2c_record = (ATOM_I2C_RECORD *) record; i2c_config = (ATOM_I2C_ID_CONFIG_ACCESS *) &i2c_record->sucI2cId; ddc_bus = radeon_lookup_i2c_gpio(rdev, i2c_config-> ucAccess); break; case ATOM_HPD_INT_RECORD_TYPE: hpd_record = (ATOM_HPD_INT_RECORD *) record; gpio = radeon_lookup_gpio(rdev, hpd_record->ucHPDIntGPIOID); hpd = radeon_atom_get_hpd_info_from_gpio(rdev, &gpio); hpd.plugged_state = hpd_record->ucPlugged_PinState; break; } record = (ATOM_COMMON_RECORD_HEADER *) ((char *)record + record-> ucRecordSize); } break; } } } else { hpd.hpd = RADEON_HPD_NONE; ddc_bus.valid = false; } /* needed for aux chan transactions */ ddc_bus.hpd_id = hpd.hpd ? (hpd.hpd - 1) : 0; conn_id = le16_to_cpu(path->usConnObjectId); if (!radeon_atom_apply_quirks (dev, le16_to_cpu(path->usDeviceTag), &connector_type, &ddc_bus, &conn_id, &hpd)) continue; radeon_add_atom_connector(dev, conn_id, le16_to_cpu(path-> usDeviceTag), connector_type, &ddc_bus, linkb, igp_lane_info, connector_object_id, &hpd); } } radeon_link_encoder_connector(dev); return true; } static uint16_t atombios_get_connector_object_id(struct drm_device *dev, int connector_type, uint16_t devices) { struct radeon_device *rdev = dev->dev_private; if (rdev->flags & RADEON_IS_IGP) { return supported_devices_connector_object_id_convert [connector_type]; } else if (((connector_type == DRM_MODE_CONNECTOR_DVII) || (connector_type == DRM_MODE_CONNECTOR_DVID)) && (devices & ATOM_DEVICE_DFP2_SUPPORT)) { struct radeon_mode_info *mode_info = &rdev->mode_info; struct atom_context *ctx = mode_info->atom_context; int index = GetIndexIntoMasterTable(DATA, XTMDS_Info); uint16_t size, data_offset; uint8_t frev, crev; ATOM_XTMDS_INFO *xtmds; if (atom_parse_data_header(ctx, index, &size, &frev, &crev, &data_offset)) { xtmds = (ATOM_XTMDS_INFO *)(ctx->bios + data_offset); if (xtmds->ucSupportedLink & ATOM_XTMDS_SUPPORTED_DUALLINK) { if (connector_type == DRM_MODE_CONNECTOR_DVII) return CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_I; else return CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_D; } else { if (connector_type == DRM_MODE_CONNECTOR_DVII) return CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_I; else return CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_D; } } else return supported_devices_connector_object_id_convert [connector_type]; } else { return supported_devices_connector_object_id_convert [connector_type]; } } struct bios_connector { bool valid; uint16_t line_mux; uint16_t devices; int connector_type; struct radeon_i2c_bus_rec ddc_bus; struct radeon_hpd hpd; }; bool radeon_get_atom_connector_info_from_supported_devices_table(struct drm_device *dev) { struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; struct atom_context *ctx = mode_info->atom_context; int index = GetIndexIntoMasterTable(DATA, SupportedDevicesInfo); uint16_t size, data_offset; uint8_t frev, crev; uint16_t device_support; uint8_t dac; union atom_supported_devices *supported_devices; int i, j, max_device; struct bios_connector bios_connectors[ATOM_MAX_SUPPORTED_DEVICE]; if (!atom_parse_data_header(ctx, index, &size, &frev, &crev, &data_offset)) return false; supported_devices = (union atom_supported_devices *)(ctx->bios + data_offset); device_support = le16_to_cpu(supported_devices->info.usDeviceSupport); if (frev > 1) max_device = ATOM_MAX_SUPPORTED_DEVICE; else max_device = ATOM_MAX_SUPPORTED_DEVICE_INFO; for (i = 0; i < max_device; i++) { ATOM_CONNECTOR_INFO_I2C ci = supported_devices->info.asConnInfo[i]; bios_connectors[i].valid = false; if (!(device_support & (1 << i))) { continue; } if (i == ATOM_DEVICE_CV_INDEX) { DRM_DEBUG("Skipping Component Video\n"); continue; } bios_connectors[i].connector_type = supported_devices_connector_convert[ci.sucConnectorInfo. sbfAccess. bfConnectorType]; if (bios_connectors[i].connector_type == DRM_MODE_CONNECTOR_Unknown) continue; dac = ci.sucConnectorInfo.sbfAccess.bfAssociatedDAC; bios_connectors[i].line_mux = ci.sucI2cId.ucAccess; /* give tv unique connector ids */ if (i == ATOM_DEVICE_TV1_INDEX) { bios_connectors[i].ddc_bus.valid = false; bios_connectors[i].line_mux = 50; } else if (i == ATOM_DEVICE_TV2_INDEX) { bios_connectors[i].ddc_bus.valid = false; bios_connectors[i].line_mux = 51; } else if (i == ATOM_DEVICE_CV_INDEX) { bios_connectors[i].ddc_bus.valid = false; bios_connectors[i].line_mux = 52; } else bios_connectors[i].ddc_bus = radeon_lookup_i2c_gpio(rdev, bios_connectors[i].line_mux); if ((crev > 1) && (frev > 1)) { u8 isb = supported_devices->info_2d1.asIntSrcInfo[i].ucIntSrcBitmap; switch (isb) { case 0x4: bios_connectors[i].hpd.hpd = RADEON_HPD_1; break; case 0xa: bios_connectors[i].hpd.hpd = RADEON_HPD_2; break; default: bios_connectors[i].hpd.hpd = RADEON_HPD_NONE; break; } } else { if (i == ATOM_DEVICE_DFP1_INDEX) bios_connectors[i].hpd.hpd = RADEON_HPD_1; else if (i == ATOM_DEVICE_DFP2_INDEX) bios_connectors[i].hpd.hpd = RADEON_HPD_2; else bios_connectors[i].hpd.hpd = RADEON_HPD_NONE; } /* Always set the connector type to VGA for CRT1/CRT2. if they are * shared with a DVI port, we'll pick up the DVI connector when we * merge the outputs. Some bioses incorrectly list VGA ports as DVI. */ if (i == ATOM_DEVICE_CRT1_INDEX || i == ATOM_DEVICE_CRT2_INDEX) bios_connectors[i].connector_type = DRM_MODE_CONNECTOR_VGA; if (!radeon_atom_apply_quirks (dev, (1 << i), &bios_connectors[i].connector_type, &bios_connectors[i].ddc_bus, &bios_connectors[i].line_mux, &bios_connectors[i].hpd)) continue; bios_connectors[i].valid = true; bios_connectors[i].devices = (1 << i); if (ASIC_IS_AVIVO(rdev) || radeon_r4xx_atom) radeon_add_atom_encoder(dev, radeon_get_encoder_id(dev, (1 << i), dac), (1 << i)); else radeon_add_legacy_encoder(dev, radeon_get_encoder_id(dev, (1 << i), dac), (1 << i)); } /* combine shared connectors */ for (i = 0; i < max_device; i++) { if (bios_connectors[i].valid) { for (j = 0; j < max_device; j++) { if (bios_connectors[j].valid && (i != j)) { if (bios_connectors[i].line_mux == bios_connectors[j].line_mux) { /* make sure not to combine LVDS */ if (bios_connectors[i].devices & (ATOM_DEVICE_LCD_SUPPORT)) { bios_connectors[i].line_mux = 53; bios_connectors[i].ddc_bus.valid = false; continue; } if (bios_connectors[j].devices & (ATOM_DEVICE_LCD_SUPPORT)) { bios_connectors[j].line_mux = 53; bios_connectors[j].ddc_bus.valid = false; continue; } /* combine analog and digital for DVI-I */ if (((bios_connectors[i].devices & (ATOM_DEVICE_DFP_SUPPORT)) && (bios_connectors[j].devices & (ATOM_DEVICE_CRT_SUPPORT))) || ((bios_connectors[j].devices & (ATOM_DEVICE_DFP_SUPPORT)) && (bios_connectors[i].devices & (ATOM_DEVICE_CRT_SUPPORT)))) { bios_connectors[i].devices |= bios_connectors[j].devices; bios_connectors[i].connector_type = DRM_MODE_CONNECTOR_DVII; if (bios_connectors[j].devices & (ATOM_DEVICE_DFP_SUPPORT)) bios_connectors[i].hpd = bios_connectors[j].hpd; bios_connectors[j].valid = false; } } } } } } /* add the connectors */ for (i = 0; i < max_device; i++) { if (bios_connectors[i].valid) { uint16_t connector_object_id = atombios_get_connector_object_id(dev, bios_connectors[i].connector_type, bios_connectors[i].devices); radeon_add_atom_connector(dev, bios_connectors[i].line_mux, bios_connectors[i].devices, bios_connectors[i]. connector_type, &bios_connectors[i].ddc_bus, false, 0, connector_object_id, &bios_connectors[i].hpd); } } radeon_link_encoder_connector(dev); return true; } union firmware_info { ATOM_FIRMWARE_INFO info; ATOM_FIRMWARE_INFO_V1_2 info_12; ATOM_FIRMWARE_INFO_V1_3 info_13; ATOM_FIRMWARE_INFO_V1_4 info_14; ATOM_FIRMWARE_INFO_V2_1 info_21; }; bool radeon_atom_get_clock_info(struct drm_device *dev) { struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, FirmwareInfo); union firmware_info *firmware_info; uint8_t frev, crev; struct radeon_pll *p1pll = &rdev->clock.p1pll; struct radeon_pll *p2pll = &rdev->clock.p2pll; struct radeon_pll *dcpll = &rdev->clock.dcpll; struct radeon_pll *spll = &rdev->clock.spll; struct radeon_pll *mpll = &rdev->clock.mpll; uint16_t data_offset; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { firmware_info = (union firmware_info *)(mode_info->atom_context->bios + data_offset); /* pixel clocks */ p1pll->reference_freq = le16_to_cpu(firmware_info->info.usReferenceClock); p1pll->reference_div = 0; if (crev < 2) p1pll->pll_out_min = le16_to_cpu(firmware_info->info.usMinPixelClockPLL_Output); else p1pll->pll_out_min = le32_to_cpu(firmware_info->info_12.ulMinPixelClockPLL_Output); p1pll->pll_out_max = le32_to_cpu(firmware_info->info.ulMaxPixelClockPLL_Output); if (crev >= 4) { p1pll->lcd_pll_out_min = le16_to_cpu(firmware_info->info_14.usLcdMinPixelClockPLL_Output) * 100; if (p1pll->lcd_pll_out_min == 0) p1pll->lcd_pll_out_min = p1pll->pll_out_min; p1pll->lcd_pll_out_max = le16_to_cpu(firmware_info->info_14.usLcdMaxPixelClockPLL_Output) * 100; if (p1pll->lcd_pll_out_max == 0) p1pll->lcd_pll_out_max = p1pll->pll_out_max; } else { p1pll->lcd_pll_out_min = p1pll->pll_out_min; p1pll->lcd_pll_out_max = p1pll->pll_out_max; } if (p1pll->pll_out_min == 0) { if (ASIC_IS_AVIVO(rdev)) p1pll->pll_out_min = 64800; else p1pll->pll_out_min = 20000; } else if (p1pll->pll_out_min > 64800) { /* Limiting the pll output range is a good thing generally as * it limits the number of possible pll combinations for a given * frequency presumably to the ones that work best on each card. * However, certain duallink DVI monitors seem to like * pll combinations that would be limited by this at least on * pre-DCE 3.0 r6xx hardware. This might need to be adjusted per * family. */ if (!radeon_new_pll) p1pll->pll_out_min = 64800; } p1pll->pll_in_min = le16_to_cpu(firmware_info->info.usMinPixelClockPLL_Input); p1pll->pll_in_max = le16_to_cpu(firmware_info->info.usMaxPixelClockPLL_Input); *p2pll = *p1pll; /* system clock */ spll->reference_freq = le16_to_cpu(firmware_info->info.usReferenceClock); spll->reference_div = 0; spll->pll_out_min = le16_to_cpu(firmware_info->info.usMinEngineClockPLL_Output); spll->pll_out_max = le32_to_cpu(firmware_info->info.ulMaxEngineClockPLL_Output); /* ??? */ if (spll->pll_out_min == 0) { if (ASIC_IS_AVIVO(rdev)) spll->pll_out_min = 64800; else spll->pll_out_min = 20000; } spll->pll_in_min = le16_to_cpu(firmware_info->info.usMinEngineClockPLL_Input); spll->pll_in_max = le16_to_cpu(firmware_info->info.usMaxEngineClockPLL_Input); /* memory clock */ mpll->reference_freq = le16_to_cpu(firmware_info->info.usReferenceClock); mpll->reference_div = 0; mpll->pll_out_min = le16_to_cpu(firmware_info->info.usMinMemoryClockPLL_Output); mpll->pll_out_max = le32_to_cpu(firmware_info->info.ulMaxMemoryClockPLL_Output); /* ??? */ if (mpll->pll_out_min == 0) { if (ASIC_IS_AVIVO(rdev)) mpll->pll_out_min = 64800; else mpll->pll_out_min = 20000; } mpll->pll_in_min = le16_to_cpu(firmware_info->info.usMinMemoryClockPLL_Input); mpll->pll_in_max = le16_to_cpu(firmware_info->info.usMaxMemoryClockPLL_Input); rdev->clock.default_sclk = le32_to_cpu(firmware_info->info.ulDefaultEngineClock); rdev->clock.default_mclk = le32_to_cpu(firmware_info->info.ulDefaultMemoryClock); if (ASIC_IS_DCE4(rdev)) { rdev->clock.default_dispclk = le32_to_cpu(firmware_info->info_21.ulDefaultDispEngineClkFreq); if (rdev->clock.default_dispclk == 0) rdev->clock.default_dispclk = 60000; /* 600 Mhz */ rdev->clock.dp_extclk = le16_to_cpu(firmware_info->info_21.usUniphyDPModeExtClkFreq); } *dcpll = *p1pll; return true; } return false; } union igp_info { struct _ATOM_INTEGRATED_SYSTEM_INFO info; struct _ATOM_INTEGRATED_SYSTEM_INFO_V2 info_2; }; bool radeon_atombios_sideport_present(struct radeon_device *rdev) { struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, IntegratedSystemInfo); union igp_info *igp_info; u8 frev, crev; u16 data_offset; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { igp_info = (union igp_info *)(mode_info->atom_context->bios + data_offset); switch (crev) { case 1: if (igp_info->info.ucMemoryType & 0xf0) return true; break; case 2: if (igp_info->info_2.ucMemoryType & 0x0f) return true; break; default: DRM_ERROR("Unsupported IGP table: %d %d\n", frev, crev); break; } } return false; } bool radeon_atombios_get_tmds_info(struct radeon_encoder *encoder, struct radeon_encoder_int_tmds *tmds) { struct drm_device *dev = encoder->base.dev; struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, TMDS_Info); uint16_t data_offset; struct _ATOM_TMDS_INFO *tmds_info; uint8_t frev, crev; uint16_t maxfreq; int i; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { tmds_info = (struct _ATOM_TMDS_INFO *)(mode_info->atom_context->bios + data_offset); maxfreq = le16_to_cpu(tmds_info->usMaxFrequency); for (i = 0; i < 4; i++) { tmds->tmds_pll[i].freq = le16_to_cpu(tmds_info->asMiscInfo[i].usFrequency); tmds->tmds_pll[i].value = tmds_info->asMiscInfo[i].ucPLL_ChargePump & 0x3f; tmds->tmds_pll[i].value |= (tmds_info->asMiscInfo[i]. ucPLL_VCO_Gain & 0x3f) << 6; tmds->tmds_pll[i].value |= (tmds_info->asMiscInfo[i]. ucPLL_DutyCycle & 0xf) << 12; tmds->tmds_pll[i].value |= (tmds_info->asMiscInfo[i]. ucPLL_VoltageSwing & 0xf) << 16; DRM_DEBUG("TMDS PLL From ATOMBIOS %u %x\n", tmds->tmds_pll[i].freq, tmds->tmds_pll[i].value); if (maxfreq == tmds->tmds_pll[i].freq) { tmds->tmds_pll[i].freq = 0xffffffff; break; } } return true; } return false; } static struct radeon_atom_ss *radeon_atombios_get_ss_info(struct radeon_encoder *encoder, int id) { struct drm_device *dev = encoder->base.dev; struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, PPLL_SS_Info); uint16_t data_offset; struct _ATOM_SPREAD_SPECTRUM_INFO *ss_info; uint8_t frev, crev; struct radeon_atom_ss *ss = NULL; int i; if (id > ATOM_MAX_SS_ENTRY) return NULL; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { ss_info = (struct _ATOM_SPREAD_SPECTRUM_INFO *)(mode_info->atom_context->bios + data_offset); ss = kzalloc(sizeof(struct radeon_atom_ss), GFP_KERNEL); if (!ss) return NULL; for (i = 0; i < ATOM_MAX_SS_ENTRY; i++) { if (ss_info->asSS_Info[i].ucSS_Id == id) { ss->percentage = le16_to_cpu(ss_info->asSS_Info[i].usSpreadSpectrumPercentage); ss->type = ss_info->asSS_Info[i].ucSpreadSpectrumType; ss->step = ss_info->asSS_Info[i].ucSS_Step; ss->delay = ss_info->asSS_Info[i].ucSS_Delay; ss->range = ss_info->asSS_Info[i].ucSS_Range; ss->refdiv = ss_info->asSS_Info[i].ucRecommendedRef_Div; break; } } } return ss; } union lvds_info { struct _ATOM_LVDS_INFO info; struct _ATOM_LVDS_INFO_V12 info_12; }; struct radeon_encoder_atom_dig *radeon_atombios_get_lvds_info(struct radeon_encoder *encoder) { struct drm_device *dev = encoder->base.dev; struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, LVDS_Info); uint16_t data_offset, misc; union lvds_info *lvds_info; uint8_t frev, crev; struct radeon_encoder_atom_dig *lvds = NULL; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { lvds_info = (union lvds_info *)(mode_info->atom_context->bios + data_offset); lvds = kzalloc(sizeof(struct radeon_encoder_atom_dig), GFP_KERNEL); if (!lvds) return NULL; lvds->native_mode.clock = le16_to_cpu(lvds_info->info.sLCDTiming.usPixClk) * 10; lvds->native_mode.hdisplay = le16_to_cpu(lvds_info->info.sLCDTiming.usHActive); lvds->native_mode.vdisplay = le16_to_cpu(lvds_info->info.sLCDTiming.usVActive); lvds->native_mode.htotal = lvds->native_mode.hdisplay + le16_to_cpu(lvds_info->info.sLCDTiming.usHBlanking_Time); lvds->native_mode.hsync_start = lvds->native_mode.hdisplay + le16_to_cpu(lvds_info->info.sLCDTiming.usHSyncOffset); lvds->native_mode.hsync_end = lvds->native_mode.hsync_start + le16_to_cpu(lvds_info->info.sLCDTiming.usHSyncWidth); lvds->native_mode.vtotal = lvds->native_mode.vdisplay + le16_to_cpu(lvds_info->info.sLCDTiming.usVBlanking_Time); lvds->native_mode.vsync_start = lvds->native_mode.vdisplay + le16_to_cpu(lvds_info->info.sLCDTiming.usVSyncWidth); lvds->native_mode.vsync_end = lvds->native_mode.vsync_start + le16_to_cpu(lvds_info->info.sLCDTiming.usVSyncWidth); lvds->panel_pwr_delay = le16_to_cpu(lvds_info->info.usOffDelayInMs); lvds->lvds_misc = lvds_info->info.ucLVDS_Misc; misc = le16_to_cpu(lvds_info->info.sLCDTiming.susModeMiscInfo.usAccess); if (misc & ATOM_VSYNC_POLARITY) lvds->native_mode.flags |= DRM_MODE_FLAG_NVSYNC; if (misc & ATOM_HSYNC_POLARITY) lvds->native_mode.flags |= DRM_MODE_FLAG_NHSYNC; if (misc & ATOM_COMPOSITESYNC) lvds->native_mode.flags |= DRM_MODE_FLAG_CSYNC; if (misc & ATOM_INTERLACE) lvds->native_mode.flags |= DRM_MODE_FLAG_INTERLACE; if (misc & ATOM_DOUBLE_CLOCK_MODE) lvds->native_mode.flags |= DRM_MODE_FLAG_DBLSCAN; /* set crtc values */ drm_mode_set_crtcinfo(&lvds->native_mode, CRTC_INTERLACE_HALVE_V); lvds->ss = radeon_atombios_get_ss_info(encoder, lvds_info->info.ucSS_Id); if (ASIC_IS_AVIVO(rdev)) { if (radeon_new_pll == 0) lvds->pll_algo = PLL_ALGO_LEGACY; else lvds->pll_algo = PLL_ALGO_NEW; } else { if (radeon_new_pll == 1) lvds->pll_algo = PLL_ALGO_NEW; else lvds->pll_algo = PLL_ALGO_LEGACY; } encoder->native_mode = lvds->native_mode; } return lvds; } struct radeon_encoder_primary_dac * radeon_atombios_get_primary_dac_info(struct radeon_encoder *encoder) { struct drm_device *dev = encoder->base.dev; struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, CompassionateData); uint16_t data_offset; struct _COMPASSIONATE_DATA *dac_info; uint8_t frev, crev; uint8_t bg, dac; struct radeon_encoder_primary_dac *p_dac = NULL; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { dac_info = (struct _COMPASSIONATE_DATA *) (mode_info->atom_context->bios + data_offset); p_dac = kzalloc(sizeof(struct radeon_encoder_primary_dac), GFP_KERNEL); if (!p_dac) return NULL; bg = dac_info->ucDAC1_BG_Adjustment; dac = dac_info->ucDAC1_DAC_Adjustment; p_dac->ps2_pdac_adj = (bg << 8) | (dac); } return p_dac; } bool radeon_atom_get_tv_timings(struct radeon_device *rdev, int index, struct drm_display_mode *mode) { struct radeon_mode_info *mode_info = &rdev->mode_info; ATOM_ANALOG_TV_INFO *tv_info; ATOM_ANALOG_TV_INFO_V1_2 *tv_info_v1_2; ATOM_DTD_FORMAT *dtd_timings; int data_index = GetIndexIntoMasterTable(DATA, AnalogTV_Info); u8 frev, crev; u16 data_offset, misc; if (!atom_parse_data_header(mode_info->atom_context, data_index, NULL, &frev, &crev, &data_offset)) return false; switch (crev) { case 1: tv_info = (ATOM_ANALOG_TV_INFO *)(mode_info->atom_context->bios + data_offset); if (index >= MAX_SUPPORTED_TV_TIMING) return false; mode->crtc_htotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Total); mode->crtc_hdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Disp); mode->crtc_hsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart); mode->crtc_hsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart) + le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncWidth); mode->crtc_vtotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Total); mode->crtc_vdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Disp); mode->crtc_vsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart); mode->crtc_vsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart) + le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncWidth); mode->flags = 0; misc = le16_to_cpu(tv_info->aModeTimings[index].susModeMiscInfo.usAccess); if (misc & ATOM_VSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NVSYNC; if (misc & ATOM_HSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NHSYNC; if (misc & ATOM_COMPOSITESYNC) mode->flags |= DRM_MODE_FLAG_CSYNC; if (misc & ATOM_INTERLACE) mode->flags |= DRM_MODE_FLAG_INTERLACE; if (misc & ATOM_DOUBLE_CLOCK_MODE) mode->flags |= DRM_MODE_FLAG_DBLSCAN; mode->clock = le16_to_cpu(tv_info->aModeTimings[index].usPixelClock) * 10; if (index == 1) { /* PAL timings appear to have wrong values for totals */ mode->crtc_htotal -= 1; mode->crtc_vtotal -= 1; } break; case 2: tv_info_v1_2 = (ATOM_ANALOG_TV_INFO_V1_2 *)(mode_info->atom_context->bios + data_offset); if (index >= MAX_SUPPORTED_TV_TIMING_V1_2) return false; dtd_timings = &tv_info_v1_2->aModeTimings[index]; mode->crtc_htotal = le16_to_cpu(dtd_timings->usHActive) + le16_to_cpu(dtd_timings->usHBlanking_Time); mode->crtc_hdisplay = le16_to_cpu(dtd_timings->usHActive); mode->crtc_hsync_start = le16_to_cpu(dtd_timings->usHActive) + le16_to_cpu(dtd_timings->usHSyncOffset); mode->crtc_hsync_end = mode->crtc_hsync_start + le16_to_cpu(dtd_timings->usHSyncWidth); mode->crtc_vtotal = le16_to_cpu(dtd_timings->usVActive) + le16_to_cpu(dtd_timings->usVBlanking_Time); mode->crtc_vdisplay = le16_to_cpu(dtd_timings->usVActive); mode->crtc_vsync_start = le16_to_cpu(dtd_timings->usVActive) + le16_to_cpu(dtd_timings->usVSyncOffset); mode->crtc_vsync_end = mode->crtc_vsync_start + le16_to_cpu(dtd_timings->usVSyncWidth); mode->flags = 0; misc = le16_to_cpu(dtd_timings->susModeMiscInfo.usAccess); if (misc & ATOM_VSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NVSYNC; if (misc & ATOM_HSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NHSYNC; if (misc & ATOM_COMPOSITESYNC) mode->flags |= DRM_MODE_FLAG_CSYNC; if (misc & ATOM_INTERLACE) mode->flags |= DRM_MODE_FLAG_INTERLACE; if (misc & ATOM_DOUBLE_CLOCK_MODE) mode->flags |= DRM_MODE_FLAG_DBLSCAN; mode->clock = le16_to_cpu(dtd_timings->usPixClk) * 10; break; } return true; } enum radeon_tv_std radeon_atombios_get_tv_info(struct radeon_device *rdev) { struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, AnalogTV_Info); uint16_t data_offset; uint8_t frev, crev; struct _ATOM_ANALOG_TV_INFO *tv_info; enum radeon_tv_std tv_std = TV_STD_NTSC; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { tv_info = (struct _ATOM_ANALOG_TV_INFO *) (mode_info->atom_context->bios + data_offset); switch (tv_info->ucTV_BootUpDefaultStandard) { case ATOM_TV_NTSC: tv_std = TV_STD_NTSC; DRM_INFO("Default TV standard: NTSC\n"); break; case ATOM_TV_NTSCJ: tv_std = TV_STD_NTSC_J; DRM_INFO("Default TV standard: NTSC-J\n"); break; case ATOM_TV_PAL: tv_std = TV_STD_PAL; DRM_INFO("Default TV standard: PAL\n"); break; case ATOM_TV_PALM: tv_std = TV_STD_PAL_M; DRM_INFO("Default TV standard: PAL-M\n"); break; case ATOM_TV_PALN: tv_std = TV_STD_PAL_N; DRM_INFO("Default TV standard: PAL-N\n"); break; case ATOM_TV_PALCN: tv_std = TV_STD_PAL_CN; DRM_INFO("Default TV standard: PAL-CN\n"); break; case ATOM_TV_PAL60: tv_std = TV_STD_PAL_60; DRM_INFO("Default TV standard: PAL-60\n"); break; case ATOM_TV_SECAM: tv_std = TV_STD_SECAM; DRM_INFO("Default TV standard: SECAM\n"); break; default: tv_std = TV_STD_NTSC; DRM_INFO("Unknown TV standard; defaulting to NTSC\n"); break; } } return tv_std; } struct radeon_encoder_tv_dac * radeon_atombios_get_tv_dac_info(struct radeon_encoder *encoder) { struct drm_device *dev = encoder->base.dev; struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, CompassionateData); uint16_t data_offset; struct _COMPASSIONATE_DATA *dac_info; uint8_t frev, crev; uint8_t bg, dac; struct radeon_encoder_tv_dac *tv_dac = NULL; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { dac_info = (struct _COMPASSIONATE_DATA *) (mode_info->atom_context->bios + data_offset); tv_dac = kzalloc(sizeof(struct radeon_encoder_tv_dac), GFP_KERNEL); if (!tv_dac) return NULL; bg = dac_info->ucDAC2_CRT2_BG_Adjustment; dac = dac_info->ucDAC2_CRT2_DAC_Adjustment; tv_dac->ps2_tvdac_adj = (bg << 16) | (dac << 20); bg = dac_info->ucDAC2_PAL_BG_Adjustment; dac = dac_info->ucDAC2_PAL_DAC_Adjustment; tv_dac->pal_tvdac_adj = (bg << 16) | (dac << 20); bg = dac_info->ucDAC2_NTSC_BG_Adjustment; dac = dac_info->ucDAC2_NTSC_DAC_Adjustment; tv_dac->ntsc_tvdac_adj = (bg << 16) | (dac << 20); tv_dac->tv_std = radeon_atombios_get_tv_info(rdev); } return tv_dac; } static const char *thermal_controller_names[] = { "NONE", "LM63", "ADM1032", "ADM1030", "MUA6649", "LM64", "F75375", "ASC7512", }; static const char *pp_lib_thermal_controller_names[] = { "NONE", "LM63", "ADM1032", "ADM1030", "MUA6649", "LM64", "F75375", "RV6xx", "RV770", "ADT7473", }; union power_info { struct _ATOM_POWERPLAY_INFO info; struct _ATOM_POWERPLAY_INFO_V2 info_2; struct _ATOM_POWERPLAY_INFO_V3 info_3; struct _ATOM_PPLIB_POWERPLAYTABLE info_4; }; void radeon_atombios_get_power_modes(struct radeon_device *rdev) { struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, PowerPlayInfo); u16 data_offset; u8 frev, crev; u32 misc, misc2 = 0, sclk, mclk; union power_info *power_info; struct _ATOM_PPLIB_NONCLOCK_INFO *non_clock_info; struct _ATOM_PPLIB_STATE *power_state; int num_modes = 0, i, j; int state_index = 0, mode_index = 0; struct radeon_i2c_bus_rec i2c_bus; rdev->pm.default_power_state = NULL; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { power_info = (union power_info *)(mode_info->atom_context->bios + data_offset); if (frev < 4) { /* add the i2c bus for thermal/fan chip */ if (power_info->info.ucOverdriveThermalController > 0) { DRM_INFO("Possible %s thermal controller at 0x%02x\n", thermal_controller_names[power_info->info.ucOverdriveThermalController], power_info->info.ucOverdriveControllerAddress >> 1); i2c_bus = radeon_lookup_i2c_gpio(rdev, power_info->info.ucOverdriveI2cLine); rdev->pm.i2c_bus = radeon_i2c_create(rdev->ddev, &i2c_bus, "Thermal"); } num_modes = power_info->info.ucNumOfPowerModeEntries; if (num_modes > ATOM_MAX_NUMBEROF_POWER_BLOCK) num_modes = ATOM_MAX_NUMBEROF_POWER_BLOCK; for (i = 0; i < num_modes; i++) { rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_NONE; switch (frev) { case 1: rdev->pm.power_state[state_index].num_clock_modes = 1; rdev->pm.power_state[state_index].clock_info[0].mclk = le16_to_cpu(power_info->info.asPowerPlayInfo[i].usMemoryClock); rdev->pm.power_state[state_index].clock_info[0].sclk = le16_to_cpu(power_info->info.asPowerPlayInfo[i].usEngineClock); /* skip invalid modes */ if ((rdev->pm.power_state[state_index].clock_info[0].mclk == 0) || (rdev->pm.power_state[state_index].clock_info[0].sclk == 0)) continue; /* skip overclock modes for now */ if ((rdev->pm.power_state[state_index].clock_info[0].mclk > rdev->clock.default_mclk + RADEON_MODE_OVERCLOCK_MARGIN) || (rdev->pm.power_state[state_index].clock_info[0].sclk > rdev->clock.default_sclk + RADEON_MODE_OVERCLOCK_MARGIN)) continue; rdev->pm.power_state[state_index].non_clock_info.pcie_lanes = power_info->info.asPowerPlayInfo[i].ucNumPciELanes; misc = le32_to_cpu(power_info->info.asPowerPlayInfo[i].ulMiscInfo); if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_SUPPORT) { rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_GPIO; rdev->pm.power_state[state_index].clock_info[0].voltage.gpio = radeon_lookup_gpio(rdev, power_info->info.asPowerPlayInfo[i].ucVoltageDropIndex); if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_ACTIVE_HIGH) rdev->pm.power_state[state_index].clock_info[0].voltage.active_high = true; else rdev->pm.power_state[state_index].clock_info[0].voltage.active_high = false; } else if (misc & ATOM_PM_MISCINFO_PROGRAM_VOLTAGE) { rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_VDDC; rdev->pm.power_state[state_index].clock_info[0].voltage.vddc_id = power_info->info.asPowerPlayInfo[i].ucVoltageDropIndex; } /* order matters! */ if (misc & ATOM_PM_MISCINFO_POWER_SAVING_MODE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_POWERSAVE; if (misc & ATOM_PM_MISCINFO_DEFAULT_DC_STATE_ENTRY_TRUE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BATTERY; if (misc & ATOM_PM_MISCINFO_DEFAULT_LOW_DC_STATE_ENTRY_TRUE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BATTERY; if (misc & ATOM_PM_MISCINFO_LOAD_BALANCE_EN) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BALANCED; if (misc & ATOM_PM_MISCINFO_3D_ACCELERATION_EN) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_PERFORMANCE; if (misc & ATOM_PM_MISCINFO_DRIVER_DEFAULT_MODE) { rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_DEFAULT; rdev->pm.default_power_state = &rdev->pm.power_state[state_index]; rdev->pm.power_state[state_index].default_clock_mode = &rdev->pm.power_state[state_index].clock_info[0]; } state_index++; break; case 2: rdev->pm.power_state[state_index].num_clock_modes = 1; rdev->pm.power_state[state_index].clock_info[0].mclk = le32_to_cpu(power_info->info_2.asPowerPlayInfo[i].ulMemoryClock); rdev->pm.power_state[state_index].clock_info[0].sclk = le32_to_cpu(power_info->info_2.asPowerPlayInfo[i].ulEngineClock); /* skip invalid modes */ if ((rdev->pm.power_state[state_index].clock_info[0].mclk == 0) || (rdev->pm.power_state[state_index].clock_info[0].sclk == 0)) continue; /* skip overclock modes for now */ if ((rdev->pm.power_state[state_index].clock_info[0].mclk > rdev->clock.default_mclk + RADEON_MODE_OVERCLOCK_MARGIN) || (rdev->pm.power_state[state_index].clock_info[0].sclk > rdev->clock.default_sclk + RADEON_MODE_OVERCLOCK_MARGIN)) continue; rdev->pm.power_state[state_index].non_clock_info.pcie_lanes = power_info->info_2.asPowerPlayInfo[i].ucNumPciELanes; misc = le32_to_cpu(power_info->info_2.asPowerPlayInfo[i].ulMiscInfo); misc2 = le32_to_cpu(power_info->info_2.asPowerPlayInfo[i].ulMiscInfo2); if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_SUPPORT) { rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_GPIO; rdev->pm.power_state[state_index].clock_info[0].voltage.gpio = radeon_lookup_gpio(rdev, power_info->info_2.asPowerPlayInfo[i].ucVoltageDropIndex); if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_ACTIVE_HIGH) rdev->pm.power_state[state_index].clock_info[0].voltage.active_high = true; else rdev->pm.power_state[state_index].clock_info[0].voltage.active_high = false; } else if (misc & ATOM_PM_MISCINFO_PROGRAM_VOLTAGE) { rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_VDDC; rdev->pm.power_state[state_index].clock_info[0].voltage.vddc_id = power_info->info_2.asPowerPlayInfo[i].ucVoltageDropIndex; } /* order matters! */ if (misc & ATOM_PM_MISCINFO_POWER_SAVING_MODE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_POWERSAVE; if (misc & ATOM_PM_MISCINFO_DEFAULT_DC_STATE_ENTRY_TRUE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BATTERY; if (misc & ATOM_PM_MISCINFO_DEFAULT_LOW_DC_STATE_ENTRY_TRUE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BATTERY; if (misc & ATOM_PM_MISCINFO_LOAD_BALANCE_EN) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BALANCED; if (misc & ATOM_PM_MISCINFO_3D_ACCELERATION_EN) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_PERFORMANCE; if (misc2 & ATOM_PM_MISCINFO2_SYSTEM_AC_LITE_MODE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BALANCED; if (misc & ATOM_PM_MISCINFO_DRIVER_DEFAULT_MODE) { rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_DEFAULT; rdev->pm.default_power_state = &rdev->pm.power_state[state_index]; rdev->pm.power_state[state_index].default_clock_mode = &rdev->pm.power_state[state_index].clock_info[0]; } state_index++; break; case 3: rdev->pm.power_state[state_index].num_clock_modes = 1; rdev->pm.power_state[state_index].clock_info[0].mclk = le32_to_cpu(power_info->info_3.asPowerPlayInfo[i].ulMemoryClock); rdev->pm.power_state[state_index].clock_info[0].sclk = le32_to_cpu(power_info->info_3.asPowerPlayInfo[i].ulEngineClock); /* skip invalid modes */ if ((rdev->pm.power_state[state_index].clock_info[0].mclk == 0) || (rdev->pm.power_state[state_index].clock_info[0].sclk == 0)) continue; /* skip overclock modes for now */ if ((rdev->pm.power_state[state_index].clock_info[0].mclk > rdev->clock.default_mclk + RADEON_MODE_OVERCLOCK_MARGIN) || (rdev->pm.power_state[state_index].clock_info[0].sclk > rdev->clock.default_sclk + RADEON_MODE_OVERCLOCK_MARGIN)) continue; rdev->pm.power_state[state_index].non_clock_info.pcie_lanes = power_info->info_3.asPowerPlayInfo[i].ucNumPciELanes; misc = le32_to_cpu(power_info->info_3.asPowerPlayInfo[i].ulMiscInfo); misc2 = le32_to_cpu(power_info->info_3.asPowerPlayInfo[i].ulMiscInfo2); if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_SUPPORT) { rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_GPIO; rdev->pm.power_state[state_index].clock_info[0].voltage.gpio = radeon_lookup_gpio(rdev, power_info->info_3.asPowerPlayInfo[i].ucVoltageDropIndex); if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_ACTIVE_HIGH) rdev->pm.power_state[state_index].clock_info[0].voltage.active_high = true; else rdev->pm.power_state[state_index].clock_info[0].voltage.active_high = false; } else if (misc & ATOM_PM_MISCINFO_PROGRAM_VOLTAGE) { rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_VDDC; rdev->pm.power_state[state_index].clock_info[0].voltage.vddc_id = power_info->info_3.asPowerPlayInfo[i].ucVoltageDropIndex; if (misc2 & ATOM_PM_MISCINFO2_VDDCI_DYNAMIC_VOLTAGE_EN) { rdev->pm.power_state[state_index].clock_info[0].voltage.vddci_enabled = true; rdev->pm.power_state[state_index].clock_info[0].voltage.vddci_id = power_info->info_3.asPowerPlayInfo[i].ucVDDCI_VoltageDropIndex; } } /* order matters! */ if (misc & ATOM_PM_MISCINFO_POWER_SAVING_MODE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_POWERSAVE; if (misc & ATOM_PM_MISCINFO_DEFAULT_DC_STATE_ENTRY_TRUE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BATTERY; if (misc & ATOM_PM_MISCINFO_DEFAULT_LOW_DC_STATE_ENTRY_TRUE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BATTERY; if (misc & ATOM_PM_MISCINFO_LOAD_BALANCE_EN) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BALANCED; if (misc & ATOM_PM_MISCINFO_3D_ACCELERATION_EN) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_PERFORMANCE; if (misc2 & ATOM_PM_MISCINFO2_SYSTEM_AC_LITE_MODE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BALANCED; if (misc & ATOM_PM_MISCINFO_DRIVER_DEFAULT_MODE) { rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_DEFAULT; rdev->pm.default_power_state = &rdev->pm.power_state[state_index]; rdev->pm.power_state[state_index].default_clock_mode = &rdev->pm.power_state[state_index].clock_info[0]; } state_index++; break; } } } else if (frev == 4) { /* add the i2c bus for thermal/fan chip */ /* no support for internal controller yet */ if (power_info->info_4.sThermalController.ucType > 0) { if ((power_info->info_4.sThermalController.ucType == ATOM_PP_THERMALCONTROLLER_RV6xx) || (power_info->info_4.sThermalController.ucType == ATOM_PP_THERMALCONTROLLER_RV770)) { DRM_INFO("Internal thermal controller %s fan control\n", (power_info->info_4.sThermalController.ucFanParameters & ATOM_PP_FANPARAMETERS_NOFAN) ? "without" : "with"); } else { DRM_INFO("Possible %s thermal controller at 0x%02x %s fan control\n", pp_lib_thermal_controller_names[power_info->info_4.sThermalController.ucType], power_info->info_4.sThermalController.ucI2cAddress >> 1, (power_info->info_4.sThermalController.ucFanParameters & ATOM_PP_FANPARAMETERS_NOFAN) ? "without" : "with"); i2c_bus = radeon_lookup_i2c_gpio(rdev, power_info->info_4.sThermalController.ucI2cLine); rdev->pm.i2c_bus = radeon_i2c_create(rdev->ddev, &i2c_bus, "Thermal"); } } for (i = 0; i < power_info->info_4.ucNumStates; i++) { mode_index = 0; power_state = (struct _ATOM_PPLIB_STATE *) (mode_info->atom_context->bios + data_offset + le16_to_cpu(power_info->info_4.usStateArrayOffset) + i * power_info->info_4.ucStateEntrySize); non_clock_info = (struct _ATOM_PPLIB_NONCLOCK_INFO *) (mode_info->atom_context->bios + data_offset + le16_to_cpu(power_info->info_4.usNonClockInfoArrayOffset) + (power_state->ucNonClockStateIndex * power_info->info_4.ucNonClockSize)); for (j = 0; j < (power_info->info_4.ucStateEntrySize - 1); j++) { if (rdev->flags & RADEON_IS_IGP) { struct _ATOM_PPLIB_RS780_CLOCK_INFO *clock_info = (struct _ATOM_PPLIB_RS780_CLOCK_INFO *) (mode_info->atom_context->bios + data_offset + le16_to_cpu(power_info->info_4.usClockInfoArrayOffset) + (power_state->ucClockStateIndices[j] * power_info->info_4.ucClockInfoSize)); sclk = le16_to_cpu(clock_info->usLowEngineClockLow); sclk |= clock_info->ucLowEngineClockHigh << 16; rdev->pm.power_state[state_index].clock_info[mode_index].sclk = sclk; /* skip invalid modes */ if (rdev->pm.power_state[state_index].clock_info[mode_index].sclk == 0) continue; /* skip overclock modes for now */ if (rdev->pm.power_state[state_index].clock_info[mode_index].sclk > rdev->clock.default_sclk + RADEON_MODE_OVERCLOCK_MARGIN) continue; rdev->pm.power_state[state_index].clock_info[mode_index].voltage.type = VOLTAGE_SW; rdev->pm.power_state[state_index].clock_info[mode_index].voltage.voltage = clock_info->usVDDC; mode_index++; } else { struct _ATOM_PPLIB_R600_CLOCK_INFO *clock_info = (struct _ATOM_PPLIB_R600_CLOCK_INFO *) (mode_info->atom_context->bios + data_offset + le16_to_cpu(power_info->info_4.usClockInfoArrayOffset) + (power_state->ucClockStateIndices[j] * power_info->info_4.ucClockInfoSize)); sclk = le16_to_cpu(clock_info->usEngineClockLow); sclk |= clock_info->ucEngineClockHigh << 16; mclk = le16_to_cpu(clock_info->usMemoryClockLow); mclk |= clock_info->ucMemoryClockHigh << 16; rdev->pm.power_state[state_index].clock_info[mode_index].mclk = mclk; rdev->pm.power_state[state_index].clock_info[mode_index].sclk = sclk; /* skip invalid modes */ if ((rdev->pm.power_state[state_index].clock_info[mode_index].mclk == 0) || (rdev->pm.power_state[state_index].clock_info[mode_index].sclk == 0)) continue; /* skip overclock modes for now */ if ((rdev->pm.power_state[state_index].clock_info[mode_index].mclk > rdev->clock.default_mclk + RADEON_MODE_OVERCLOCK_MARGIN) || (rdev->pm.power_state[state_index].clock_info[mode_index].sclk > rdev->clock.default_sclk + RADEON_MODE_OVERCLOCK_MARGIN)) continue; rdev->pm.power_state[state_index].clock_info[mode_index].voltage.type = VOLTAGE_SW; rdev->pm.power_state[state_index].clock_info[mode_index].voltage.voltage = clock_info->usVDDC; mode_index++; } } rdev->pm.power_state[state_index].num_clock_modes = mode_index; if (mode_index) { misc = le32_to_cpu(non_clock_info->ulCapsAndSettings); misc2 = le16_to_cpu(non_clock_info->usClassification); rdev->pm.power_state[state_index].non_clock_info.pcie_lanes = ((misc & ATOM_PPLIB_PCIE_LINK_WIDTH_MASK) >> ATOM_PPLIB_PCIE_LINK_WIDTH_SHIFT) + 1; switch (misc2 & ATOM_PPLIB_CLASSIFICATION_UI_MASK) { case ATOM_PPLIB_CLASSIFICATION_UI_BATTERY: rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BATTERY; break; case ATOM_PPLIB_CLASSIFICATION_UI_BALANCED: rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BALANCED; break; case ATOM_PPLIB_CLASSIFICATION_UI_PERFORMANCE: rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_PERFORMANCE; break; } if (misc2 & ATOM_PPLIB_CLASSIFICATION_BOOT) { rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_DEFAULT; rdev->pm.default_power_state = &rdev->pm.power_state[state_index]; rdev->pm.power_state[state_index].default_clock_mode = &rdev->pm.power_state[state_index].clock_info[mode_index - 1]; } state_index++; } } } } else { /* XXX figure out some good default low power mode for cards w/out power tables */ } if (rdev->pm.default_power_state == NULL) { /* add the default mode */ rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_DEFAULT; rdev->pm.power_state[state_index].num_clock_modes = 1; rdev->pm.power_state[state_index].clock_info[0].mclk = rdev->clock.default_mclk; rdev->pm.power_state[state_index].clock_info[0].sclk = rdev->clock.default_sclk; rdev->pm.power_state[state_index].default_clock_mode = &rdev->pm.power_state[state_index].clock_info[0]; rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_NONE; if (rdev->asic->get_pcie_lanes) rdev->pm.power_state[state_index].non_clock_info.pcie_lanes = radeon_get_pcie_lanes(rdev); else rdev->pm.power_state[state_index].non_clock_info.pcie_lanes = 16; rdev->pm.default_power_state = &rdev->pm.power_state[state_index]; state_index++; } rdev->pm.num_power_states = state_index; rdev->pm.current_power_state = rdev->pm.default_power_state; rdev->pm.current_clock_mode = rdev->pm.default_power_state->default_clock_mode; } void radeon_atom_set_clock_gating(struct radeon_device *rdev, int enable) { DYNAMIC_CLOCK_GATING_PS_ALLOCATION args; int index = GetIndexIntoMasterTable(COMMAND, DynamicClockGating); args.ucEnable = enable; atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args); } uint32_t radeon_atom_get_engine_clock(struct radeon_device *rdev) { GET_ENGINE_CLOCK_PS_ALLOCATION args; int index = GetIndexIntoMasterTable(COMMAND, GetEngineClock); atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args); return args.ulReturnEngineClock; } uint32_t radeon_atom_get_memory_clock(struct radeon_device *rdev) { GET_MEMORY_CLOCK_PS_ALLOCATION args; int index = GetIndexIntoMasterTable(COMMAND, GetMemoryClock); atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args); return args.ulReturnMemoryClock; } void radeon_atom_set_engine_clock(struct radeon_device *rdev, uint32_t eng_clock) { SET_ENGINE_CLOCK_PS_ALLOCATION args; int index = GetIndexIntoMasterTable(COMMAND, SetEngineClock); args.ulTargetEngineClock = eng_clock; /* 10 khz */ atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args); } void radeon_atom_set_memory_clock(struct radeon_device *rdev, uint32_t mem_clock) { SET_MEMORY_CLOCK_PS_ALLOCATION args; int index = GetIndexIntoMasterTable(COMMAND, SetMemoryClock); if (rdev->flags & RADEON_IS_IGP) return; args.ulTargetMemoryClock = mem_clock; /* 10 khz */ atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args); } void radeon_atom_initialize_bios_scratch_regs(struct drm_device *dev) { struct radeon_device *rdev = dev->dev_private; uint32_t bios_2_scratch, bios_6_scratch; if (rdev->family >= CHIP_R600) { bios_2_scratch = RREG32(R600_BIOS_2_SCRATCH); bios_6_scratch = RREG32(R600_BIOS_6_SCRATCH); } else { bios_2_scratch = RREG32(RADEON_BIOS_2_SCRATCH); bios_6_scratch = RREG32(RADEON_BIOS_6_SCRATCH); } /* let the bios control the backlight */ bios_2_scratch &= ~ATOM_S2_VRI_BRIGHT_ENABLE; /* tell the bios not to handle mode switching */ bios_6_scratch |= (ATOM_S6_ACC_BLOCK_DISPLAY_SWITCH | ATOM_S6_ACC_MODE); if (rdev->family >= CHIP_R600) { WREG32(R600_BIOS_2_SCRATCH, bios_2_scratch); WREG32(R600_BIOS_6_SCRATCH, bios_6_scratch); } else { WREG32(RADEON_BIOS_2_SCRATCH, bios_2_scratch); WREG32(RADEON_BIOS_6_SCRATCH, bios_6_scratch); } } void radeon_save_bios_scratch_regs(struct radeon_device *rdev) { uint32_t scratch_reg; int i; if (rdev->family >= CHIP_R600) scratch_reg = R600_BIOS_0_SCRATCH; else scratch_reg = RADEON_BIOS_0_SCRATCH; for (i = 0; i < RADEON_BIOS_NUM_SCRATCH; i++) rdev->bios_scratch[i] = RREG32(scratch_reg + (i * 4)); } void radeon_restore_bios_scratch_regs(struct radeon_device *rdev) { uint32_t scratch_reg; int i; if (rdev->family >= CHIP_R600) scratch_reg = R600_BIOS_0_SCRATCH; else scratch_reg = RADEON_BIOS_0_SCRATCH; for (i = 0; i < RADEON_BIOS_NUM_SCRATCH; i++) WREG32(scratch_reg + (i * 4), rdev->bios_scratch[i]); } void radeon_atom_output_lock(struct drm_encoder *encoder, bool lock) { struct drm_device *dev = encoder->dev; struct radeon_device *rdev = dev->dev_private; uint32_t bios_6_scratch; if (rdev->family >= CHIP_R600) bios_6_scratch = RREG32(R600_BIOS_6_SCRATCH); else bios_6_scratch = RREG32(RADEON_BIOS_6_SCRATCH); if (lock) bios_6_scratch |= ATOM_S6_CRITICAL_STATE; else bios_6_scratch &= ~ATOM_S6_CRITICAL_STATE; if (rdev->family >= CHIP_R600) WREG32(R600_BIOS_6_SCRATCH, bios_6_scratch); else WREG32(RADEON_BIOS_6_SCRATCH, bios_6_scratch); } /* at some point we may want to break this out into individual functions */ void radeon_atombios_connected_scratch_regs(struct drm_connector *connector, struct drm_encoder *encoder, bool connected) { struct drm_device *dev = connector->dev; struct radeon_device *rdev = dev->dev_private; struct radeon_connector *radeon_connector = to_radeon_connector(connector); struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder); uint32_t bios_0_scratch, bios_3_scratch, bios_6_scratch; if (rdev->family >= CHIP_R600) { bios_0_scratch = RREG32(R600_BIOS_0_SCRATCH); bios_3_scratch = RREG32(R600_BIOS_3_SCRATCH); bios_6_scratch = RREG32(R600_BIOS_6_SCRATCH); } else { bios_0_scratch = RREG32(RADEON_BIOS_0_SCRATCH); bios_3_scratch = RREG32(RADEON_BIOS_3_SCRATCH); bios_6_scratch = RREG32(RADEON_BIOS_6_SCRATCH); } if ((radeon_encoder->devices & ATOM_DEVICE_TV1_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_TV1_SUPPORT)) { if (connected) { DRM_DEBUG("TV1 connected\n"); bios_3_scratch |= ATOM_S3_TV1_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_TV1; } else { DRM_DEBUG("TV1 disconnected\n"); bios_0_scratch &= ~ATOM_S0_TV1_MASK; bios_3_scratch &= ~ATOM_S3_TV1_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_TV1; } } if ((radeon_encoder->devices & ATOM_DEVICE_CV_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_CV_SUPPORT)) { if (connected) { DRM_DEBUG("CV connected\n"); bios_3_scratch |= ATOM_S3_CV_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_CV; } else { DRM_DEBUG("CV disconnected\n"); bios_0_scratch &= ~ATOM_S0_CV_MASK; bios_3_scratch &= ~ATOM_S3_CV_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_CV; } } if ((radeon_encoder->devices & ATOM_DEVICE_LCD1_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_LCD1_SUPPORT)) { if (connected) { DRM_DEBUG("LCD1 connected\n"); bios_0_scratch |= ATOM_S0_LCD1; bios_3_scratch |= ATOM_S3_LCD1_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_LCD1; } else { DRM_DEBUG("LCD1 disconnected\n"); bios_0_scratch &= ~ATOM_S0_LCD1; bios_3_scratch &= ~ATOM_S3_LCD1_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_LCD1; } } if ((radeon_encoder->devices & ATOM_DEVICE_CRT1_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_CRT1_SUPPORT)) { if (connected) { DRM_DEBUG("CRT1 connected\n"); bios_0_scratch |= ATOM_S0_CRT1_COLOR; bios_3_scratch |= ATOM_S3_CRT1_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_CRT1; } else { DRM_DEBUG("CRT1 disconnected\n"); bios_0_scratch &= ~ATOM_S0_CRT1_MASK; bios_3_scratch &= ~ATOM_S3_CRT1_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_CRT1; } } if ((radeon_encoder->devices & ATOM_DEVICE_CRT2_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_CRT2_SUPPORT)) { if (connected) { DRM_DEBUG("CRT2 connected\n"); bios_0_scratch |= ATOM_S0_CRT2_COLOR; bios_3_scratch |= ATOM_S3_CRT2_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_CRT2; } else { DRM_DEBUG("CRT2 disconnected\n"); bios_0_scratch &= ~ATOM_S0_CRT2_MASK; bios_3_scratch &= ~ATOM_S3_CRT2_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_CRT2; } } if ((radeon_encoder->devices & ATOM_DEVICE_DFP1_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_DFP1_SUPPORT)) { if (connected) { DRM_DEBUG("DFP1 connected\n"); bios_0_scratch |= ATOM_S0_DFP1; bios_3_scratch |= ATOM_S3_DFP1_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_DFP1; } else { DRM_DEBUG("DFP1 disconnected\n"); bios_0_scratch &= ~ATOM_S0_DFP1; bios_3_scratch &= ~ATOM_S3_DFP1_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP1; } } if ((radeon_encoder->devices & ATOM_DEVICE_DFP2_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_DFP2_SUPPORT)) { if (connected) { DRM_DEBUG("DFP2 connected\n"); bios_0_scratch |= ATOM_S0_DFP2; bios_3_scratch |= ATOM_S3_DFP2_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_DFP2; } else { DRM_DEBUG("DFP2 disconnected\n"); bios_0_scratch &= ~ATOM_S0_DFP2; bios_3_scratch &= ~ATOM_S3_DFP2_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP2; } } if ((radeon_encoder->devices & ATOM_DEVICE_DFP3_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_DFP3_SUPPORT)) { if (connected) { DRM_DEBUG("DFP3 connected\n"); bios_0_scratch |= ATOM_S0_DFP3; bios_3_scratch |= ATOM_S3_DFP3_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_DFP3; } else { DRM_DEBUG("DFP3 disconnected\n"); bios_0_scratch &= ~ATOM_S0_DFP3; bios_3_scratch &= ~ATOM_S3_DFP3_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP3; } } if ((radeon_encoder->devices & ATOM_DEVICE_DFP4_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_DFP4_SUPPORT)) { if (connected) { DRM_DEBUG("DFP4 connected\n"); bios_0_scratch |= ATOM_S0_DFP4; bios_3_scratch |= ATOM_S3_DFP4_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_DFP4; } else { DRM_DEBUG("DFP4 disconnected\n"); bios_0_scratch &= ~ATOM_S0_DFP4; bios_3_scratch &= ~ATOM_S3_DFP4_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP4; } } if ((radeon_encoder->devices & ATOM_DEVICE_DFP5_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_DFP5_SUPPORT)) { if (connected) { DRM_DEBUG("DFP5 connected\n"); bios_0_scratch |= ATOM_S0_DFP5; bios_3_scratch |= ATOM_S3_DFP5_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_DFP5; } else { DRM_DEBUG("DFP5 disconnected\n"); bios_0_scratch &= ~ATOM_S0_DFP5; bios_3_scratch &= ~ATOM_S3_DFP5_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP5; } } if (rdev->family >= CHIP_R600) { WREG32(R600_BIOS_0_SCRATCH, bios_0_scratch); WREG32(R600_BIOS_3_SCRATCH, bios_3_scratch); WREG32(R600_BIOS_6_SCRATCH, bios_6_scratch); } else { WREG32(RADEON_BIOS_0_SCRATCH, bios_0_scratch); WREG32(RADEON_BIOS_3_SCRATCH, bios_3_scratch); WREG32(RADEON_BIOS_6_SCRATCH, bios_6_scratch); } } void radeon_atombios_encoder_crtc_scratch_regs(struct drm_encoder *encoder, int crtc) { struct drm_device *dev = encoder->dev; struct radeon_device *rdev = dev->dev_private; struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder); uint32_t bios_3_scratch; if (rdev->family >= CHIP_R600) bios_3_scratch = RREG32(R600_BIOS_3_SCRATCH); else bios_3_scratch = RREG32(RADEON_BIOS_3_SCRATCH); if (radeon_encoder->devices & ATOM_DEVICE_TV1_SUPPORT) { bios_3_scratch &= ~ATOM_S3_TV1_CRTC_ACTIVE; bios_3_scratch |= (crtc << 18); } if (radeon_encoder->devices & ATOM_DEVICE_CV_SUPPORT) { bios_3_scratch &= ~ATOM_S3_CV_CRTC_ACTIVE; bios_3_scratch |= (crtc << 24); } if (radeon_encoder->devices & ATOM_DEVICE_CRT1_SUPPORT) { bios_3_scratch &= ~ATOM_S3_CRT1_CRTC_ACTIVE; bios_3_scratch |= (crtc << 16); } if (radeon_encoder->devices & ATOM_DEVICE_CRT2_SUPPORT) { bios_3_scratch &= ~ATOM_S3_CRT2_CRTC_ACTIVE; bios_3_scratch |= (crtc << 20); } if (radeon_encoder->devices & ATOM_DEVICE_LCD1_SUPPORT) { bios_3_scratch &= ~ATOM_S3_LCD1_CRTC_ACTIVE; bios_3_scratch |= (crtc << 17); } if (radeon_encoder->devices & ATOM_DEVICE_DFP1_SUPPORT) { bios_3_scratch &= ~ATOM_S3_DFP1_CRTC_ACTIVE; bios_3_scratch |= (crtc << 19); } if (radeon_encoder->devices & ATOM_DEVICE_DFP2_SUPPORT) { bios_3_scratch &= ~ATOM_S3_DFP2_CRTC_ACTIVE; bios_3_scratch |= (crtc << 23); } if (radeon_encoder->devices & ATOM_DEVICE_DFP3_SUPPORT) { bios_3_scratch &= ~ATOM_S3_DFP3_CRTC_ACTIVE; bios_3_scratch |= (crtc << 25); } if (rdev->family >= CHIP_R600) WREG32(R600_BIOS_3_SCRATCH, bios_3_scratch); else WREG32(RADEON_BIOS_3_SCRATCH, bios_3_scratch); } void radeon_atombios_encoder_dpms_scratch_regs(struct drm_encoder *encoder, bool on) { struct drm_device *dev = encoder->dev; struct radeon_device *rdev = dev->dev_private; struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder); uint32_t bios_2_scratch; if (rdev->family >= CHIP_R600) bios_2_scratch = RREG32(R600_BIOS_2_SCRATCH); else bios_2_scratch = RREG32(RADEON_BIOS_2_SCRATCH); if (radeon_encoder->devices & ATOM_DEVICE_TV1_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_TV1_DPMS_STATE; else bios_2_scratch |= ATOM_S2_TV1_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_CV_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_CV_DPMS_STATE; else bios_2_scratch |= ATOM_S2_CV_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_CRT1_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_CRT1_DPMS_STATE; else bios_2_scratch |= ATOM_S2_CRT1_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_CRT2_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_CRT2_DPMS_STATE; else bios_2_scratch |= ATOM_S2_CRT2_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_LCD1_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_LCD1_DPMS_STATE; else bios_2_scratch |= ATOM_S2_LCD1_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_DFP1_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_DFP1_DPMS_STATE; else bios_2_scratch |= ATOM_S2_DFP1_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_DFP2_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_DFP2_DPMS_STATE; else bios_2_scratch |= ATOM_S2_DFP2_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_DFP3_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_DFP3_DPMS_STATE; else bios_2_scratch |= ATOM_S2_DFP3_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_DFP4_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_DFP4_DPMS_STATE; else bios_2_scratch |= ATOM_S2_DFP4_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_DFP5_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_DFP5_DPMS_STATE; else bios_2_scratch |= ATOM_S2_DFP5_DPMS_STATE; } if (rdev->family >= CHIP_R600) WREG32(R600_BIOS_2_SCRATCH, bios_2_scratch); else WREG32(RADEON_BIOS_2_SCRATCH, bios_2_scratch); }
./CrossVul/dataset_final_sorted/CWE-193/c/good_4732_1
crossvul-cpp_data_bad_4732_1
/* * Copyright 2007-8 Advanced Micro Devices, Inc. * Copyright 2008 Red Hat Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. * * Authors: Dave Airlie * Alex Deucher */ #include "drmP.h" #include "radeon_drm.h" #include "radeon.h" #include "atom.h" #include "atom-bits.h" /* from radeon_encoder.c */ extern uint32_t radeon_get_encoder_id(struct drm_device *dev, uint32_t supported_device, uint8_t dac); extern void radeon_link_encoder_connector(struct drm_device *dev); extern void radeon_add_atom_encoder(struct drm_device *dev, uint32_t encoder_id, uint32_t supported_device); /* from radeon_connector.c */ extern void radeon_add_atom_connector(struct drm_device *dev, uint32_t connector_id, uint32_t supported_device, int connector_type, struct radeon_i2c_bus_rec *i2c_bus, bool linkb, uint32_t igp_lane_info, uint16_t connector_object_id, struct radeon_hpd *hpd); /* from radeon_legacy_encoder.c */ extern void radeon_add_legacy_encoder(struct drm_device *dev, uint32_t encoder_id, uint32_t supported_device); union atom_supported_devices { struct _ATOM_SUPPORTED_DEVICES_INFO info; struct _ATOM_SUPPORTED_DEVICES_INFO_2 info_2; struct _ATOM_SUPPORTED_DEVICES_INFO_2d1 info_2d1; }; static inline struct radeon_i2c_bus_rec radeon_lookup_i2c_gpio(struct radeon_device *rdev, uint8_t id) { struct atom_context *ctx = rdev->mode_info.atom_context; ATOM_GPIO_I2C_ASSIGMENT *gpio; struct radeon_i2c_bus_rec i2c; int index = GetIndexIntoMasterTable(DATA, GPIO_I2C_Info); struct _ATOM_GPIO_I2C_INFO *i2c_info; uint16_t data_offset, size; int i, num_indices; memset(&i2c, 0, sizeof(struct radeon_i2c_bus_rec)); i2c.valid = false; if (atom_parse_data_header(ctx, index, &size, NULL, NULL, &data_offset)) { i2c_info = (struct _ATOM_GPIO_I2C_INFO *)(ctx->bios + data_offset); num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) / sizeof(ATOM_GPIO_I2C_ASSIGMENT); for (i = 0; i < num_indices; i++) { gpio = &i2c_info->asGPIO_Info[i]; if (gpio->sucI2cId.ucAccess == id) { i2c.mask_clk_reg = le16_to_cpu(gpio->usClkMaskRegisterIndex) * 4; i2c.mask_data_reg = le16_to_cpu(gpio->usDataMaskRegisterIndex) * 4; i2c.en_clk_reg = le16_to_cpu(gpio->usClkEnRegisterIndex) * 4; i2c.en_data_reg = le16_to_cpu(gpio->usDataEnRegisterIndex) * 4; i2c.y_clk_reg = le16_to_cpu(gpio->usClkY_RegisterIndex) * 4; i2c.y_data_reg = le16_to_cpu(gpio->usDataY_RegisterIndex) * 4; i2c.a_clk_reg = le16_to_cpu(gpio->usClkA_RegisterIndex) * 4; i2c.a_data_reg = le16_to_cpu(gpio->usDataA_RegisterIndex) * 4; i2c.mask_clk_mask = (1 << gpio->ucClkMaskShift); i2c.mask_data_mask = (1 << gpio->ucDataMaskShift); i2c.en_clk_mask = (1 << gpio->ucClkEnShift); i2c.en_data_mask = (1 << gpio->ucDataEnShift); i2c.y_clk_mask = (1 << gpio->ucClkY_Shift); i2c.y_data_mask = (1 << gpio->ucDataY_Shift); i2c.a_clk_mask = (1 << gpio->ucClkA_Shift); i2c.a_data_mask = (1 << gpio->ucDataA_Shift); if (gpio->sucI2cId.sbfAccess.bfHW_Capable) i2c.hw_capable = true; else i2c.hw_capable = false; if (gpio->sucI2cId.ucAccess == 0xa0) i2c.mm_i2c = true; else i2c.mm_i2c = false; i2c.i2c_id = gpio->sucI2cId.ucAccess; i2c.valid = true; break; } } } return i2c; } static inline struct radeon_gpio_rec radeon_lookup_gpio(struct radeon_device *rdev, u8 id) { struct atom_context *ctx = rdev->mode_info.atom_context; struct radeon_gpio_rec gpio; int index = GetIndexIntoMasterTable(DATA, GPIO_Pin_LUT); struct _ATOM_GPIO_PIN_LUT *gpio_info; ATOM_GPIO_PIN_ASSIGNMENT *pin; u16 data_offset, size; int i, num_indices; memset(&gpio, 0, sizeof(struct radeon_gpio_rec)); gpio.valid = false; if (atom_parse_data_header(ctx, index, &size, NULL, NULL, &data_offset)) { gpio_info = (struct _ATOM_GPIO_PIN_LUT *)(ctx->bios + data_offset); num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) / sizeof(ATOM_GPIO_PIN_ASSIGNMENT); for (i = 0; i < num_indices; i++) { pin = &gpio_info->asGPIO_Pin[i]; if (id == pin->ucGPIO_ID) { gpio.id = pin->ucGPIO_ID; gpio.reg = pin->usGpioPin_AIndex * 4; gpio.mask = (1 << pin->ucGpioPinBitShift); gpio.valid = true; break; } } } return gpio; } static struct radeon_hpd radeon_atom_get_hpd_info_from_gpio(struct radeon_device *rdev, struct radeon_gpio_rec *gpio) { struct radeon_hpd hpd; u32 reg; if (ASIC_IS_DCE4(rdev)) reg = EVERGREEN_DC_GPIO_HPD_A; else reg = AVIVO_DC_GPIO_HPD_A; hpd.gpio = *gpio; if (gpio->reg == reg) { switch(gpio->mask) { case (1 << 0): hpd.hpd = RADEON_HPD_1; break; case (1 << 8): hpd.hpd = RADEON_HPD_2; break; case (1 << 16): hpd.hpd = RADEON_HPD_3; break; case (1 << 24): hpd.hpd = RADEON_HPD_4; break; case (1 << 26): hpd.hpd = RADEON_HPD_5; break; case (1 << 28): hpd.hpd = RADEON_HPD_6; break; default: hpd.hpd = RADEON_HPD_NONE; break; } } else hpd.hpd = RADEON_HPD_NONE; return hpd; } static bool radeon_atom_apply_quirks(struct drm_device *dev, uint32_t supported_device, int *connector_type, struct radeon_i2c_bus_rec *i2c_bus, uint16_t *line_mux, struct radeon_hpd *hpd) { /* Asus M2A-VM HDMI board lists the DVI port as HDMI */ if ((dev->pdev->device == 0x791e) && (dev->pdev->subsystem_vendor == 0x1043) && (dev->pdev->subsystem_device == 0x826d)) { if ((*connector_type == DRM_MODE_CONNECTOR_HDMIA) && (supported_device == ATOM_DEVICE_DFP3_SUPPORT)) *connector_type = DRM_MODE_CONNECTOR_DVID; } /* Asrock RS600 board lists the DVI port as HDMI */ if ((dev->pdev->device == 0x7941) && (dev->pdev->subsystem_vendor == 0x1849) && (dev->pdev->subsystem_device == 0x7941)) { if ((*connector_type == DRM_MODE_CONNECTOR_HDMIA) && (supported_device == ATOM_DEVICE_DFP3_SUPPORT)) *connector_type = DRM_MODE_CONNECTOR_DVID; } /* a-bit f-i90hd - ciaranm on #radeonhd - this board has no DVI */ if ((dev->pdev->device == 0x7941) && (dev->pdev->subsystem_vendor == 0x147b) && (dev->pdev->subsystem_device == 0x2412)) { if (*connector_type == DRM_MODE_CONNECTOR_DVII) return false; } /* Falcon NW laptop lists vga ddc line for LVDS */ if ((dev->pdev->device == 0x5653) && (dev->pdev->subsystem_vendor == 0x1462) && (dev->pdev->subsystem_device == 0x0291)) { if (*connector_type == DRM_MODE_CONNECTOR_LVDS) { i2c_bus->valid = false; *line_mux = 53; } } /* HIS X1300 is DVI+VGA, not DVI+DVI */ if ((dev->pdev->device == 0x7146) && (dev->pdev->subsystem_vendor == 0x17af) && (dev->pdev->subsystem_device == 0x2058)) { if (supported_device == ATOM_DEVICE_DFP1_SUPPORT) return false; } /* Gigabyte X1300 is DVI+VGA, not DVI+DVI */ if ((dev->pdev->device == 0x7142) && (dev->pdev->subsystem_vendor == 0x1458) && (dev->pdev->subsystem_device == 0x2134)) { if (supported_device == ATOM_DEVICE_DFP1_SUPPORT) return false; } /* Funky macbooks */ if ((dev->pdev->device == 0x71C5) && (dev->pdev->subsystem_vendor == 0x106b) && (dev->pdev->subsystem_device == 0x0080)) { if ((supported_device == ATOM_DEVICE_CRT1_SUPPORT) || (supported_device == ATOM_DEVICE_DFP2_SUPPORT)) return false; if (supported_device == ATOM_DEVICE_CRT2_SUPPORT) *line_mux = 0x90; } /* ASUS HD 3600 XT board lists the DVI port as HDMI */ if ((dev->pdev->device == 0x9598) && (dev->pdev->subsystem_vendor == 0x1043) && (dev->pdev->subsystem_device == 0x01da)) { if (*connector_type == DRM_MODE_CONNECTOR_HDMIA) { *connector_type = DRM_MODE_CONNECTOR_DVII; } } /* ASUS HD 3450 board lists the DVI port as HDMI */ if ((dev->pdev->device == 0x95C5) && (dev->pdev->subsystem_vendor == 0x1043) && (dev->pdev->subsystem_device == 0x01e2)) { if (*connector_type == DRM_MODE_CONNECTOR_HDMIA) { *connector_type = DRM_MODE_CONNECTOR_DVII; } } /* some BIOSes seem to report DAC on HDMI - usually this is a board with * HDMI + VGA reporting as HDMI */ if (*connector_type == DRM_MODE_CONNECTOR_HDMIA) { if (supported_device & (ATOM_DEVICE_CRT_SUPPORT)) { *connector_type = DRM_MODE_CONNECTOR_VGA; *line_mux = 0; } } /* Acer laptop reports DVI-D as DVI-I */ if ((dev->pdev->device == 0x95c4) && (dev->pdev->subsystem_vendor == 0x1025) && (dev->pdev->subsystem_device == 0x013c)) { if ((*connector_type == DRM_MODE_CONNECTOR_DVII) && (supported_device == ATOM_DEVICE_DFP1_SUPPORT)) *connector_type = DRM_MODE_CONNECTOR_DVID; } /* XFX Pine Group device rv730 reports no VGA DDC lines * even though they are wired up to record 0x93 */ if ((dev->pdev->device == 0x9498) && (dev->pdev->subsystem_vendor == 0x1682) && (dev->pdev->subsystem_device == 0x2452)) { struct radeon_device *rdev = dev->dev_private; *i2c_bus = radeon_lookup_i2c_gpio(rdev, 0x93); } return true; } const int supported_devices_connector_convert[] = { DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_VGA, DRM_MODE_CONNECTOR_DVII, DRM_MODE_CONNECTOR_DVID, DRM_MODE_CONNECTOR_DVIA, DRM_MODE_CONNECTOR_SVIDEO, DRM_MODE_CONNECTOR_Composite, DRM_MODE_CONNECTOR_LVDS, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_HDMIA, DRM_MODE_CONNECTOR_HDMIB, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_9PinDIN, DRM_MODE_CONNECTOR_DisplayPort }; const uint16_t supported_devices_connector_object_id_convert[] = { CONNECTOR_OBJECT_ID_NONE, CONNECTOR_OBJECT_ID_VGA, CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_I, /* not all boards support DL */ CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_D, /* not all boards support DL */ CONNECTOR_OBJECT_ID_VGA, /* technically DVI-A */ CONNECTOR_OBJECT_ID_COMPOSITE, CONNECTOR_OBJECT_ID_SVIDEO, CONNECTOR_OBJECT_ID_LVDS, CONNECTOR_OBJECT_ID_9PIN_DIN, CONNECTOR_OBJECT_ID_9PIN_DIN, CONNECTOR_OBJECT_ID_DISPLAYPORT, CONNECTOR_OBJECT_ID_HDMI_TYPE_A, CONNECTOR_OBJECT_ID_HDMI_TYPE_B, CONNECTOR_OBJECT_ID_SVIDEO }; const int object_connector_convert[] = { DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_DVII, DRM_MODE_CONNECTOR_DVII, DRM_MODE_CONNECTOR_DVID, DRM_MODE_CONNECTOR_DVID, DRM_MODE_CONNECTOR_VGA, DRM_MODE_CONNECTOR_Composite, DRM_MODE_CONNECTOR_SVIDEO, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_9PinDIN, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_HDMIA, DRM_MODE_CONNECTOR_HDMIB, DRM_MODE_CONNECTOR_LVDS, DRM_MODE_CONNECTOR_9PinDIN, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_Unknown, DRM_MODE_CONNECTOR_DisplayPort, DRM_MODE_CONNECTOR_eDP, DRM_MODE_CONNECTOR_Unknown }; bool radeon_get_atom_connector_info_from_object_table(struct drm_device *dev) { struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; struct atom_context *ctx = mode_info->atom_context; int index = GetIndexIntoMasterTable(DATA, Object_Header); u16 size, data_offset; u8 frev, crev; ATOM_CONNECTOR_OBJECT_TABLE *con_obj; ATOM_DISPLAY_OBJECT_PATH_TABLE *path_obj; ATOM_OBJECT_HEADER *obj_header; int i, j, path_size, device_support; int connector_type; u16 igp_lane_info, conn_id, connector_object_id; bool linkb; struct radeon_i2c_bus_rec ddc_bus; struct radeon_gpio_rec gpio; struct radeon_hpd hpd; if (!atom_parse_data_header(ctx, index, &size, &frev, &crev, &data_offset)) return false; if (crev < 2) return false; obj_header = (ATOM_OBJECT_HEADER *) (ctx->bios + data_offset); path_obj = (ATOM_DISPLAY_OBJECT_PATH_TABLE *) (ctx->bios + data_offset + le16_to_cpu(obj_header->usDisplayPathTableOffset)); con_obj = (ATOM_CONNECTOR_OBJECT_TABLE *) (ctx->bios + data_offset + le16_to_cpu(obj_header->usConnectorObjectTableOffset)); device_support = le16_to_cpu(obj_header->usDeviceSupport); path_size = 0; for (i = 0; i < path_obj->ucNumOfDispPath; i++) { uint8_t *addr = (uint8_t *) path_obj->asDispPath; ATOM_DISPLAY_OBJECT_PATH *path; addr += path_size; path = (ATOM_DISPLAY_OBJECT_PATH *) addr; path_size += le16_to_cpu(path->usSize); linkb = false; if (device_support & le16_to_cpu(path->usDeviceTag)) { uint8_t con_obj_id, con_obj_num, con_obj_type; con_obj_id = (le16_to_cpu(path->usConnObjectId) & OBJECT_ID_MASK) >> OBJECT_ID_SHIFT; con_obj_num = (le16_to_cpu(path->usConnObjectId) & ENUM_ID_MASK) >> ENUM_ID_SHIFT; con_obj_type = (le16_to_cpu(path->usConnObjectId) & OBJECT_TYPE_MASK) >> OBJECT_TYPE_SHIFT; /* TODO CV support */ if (le16_to_cpu(path->usDeviceTag) == ATOM_DEVICE_CV_SUPPORT) continue; /* IGP chips */ if ((rdev->flags & RADEON_IS_IGP) && (con_obj_id == CONNECTOR_OBJECT_ID_PCIE_CONNECTOR)) { uint16_t igp_offset = 0; ATOM_INTEGRATED_SYSTEM_INFO_V2 *igp_obj; index = GetIndexIntoMasterTable(DATA, IntegratedSystemInfo); if (atom_parse_data_header(ctx, index, &size, &frev, &crev, &igp_offset)) { if (crev >= 2) { igp_obj = (ATOM_INTEGRATED_SYSTEM_INFO_V2 *) (ctx->bios + igp_offset); if (igp_obj) { uint32_t slot_config, ct; if (con_obj_num == 1) slot_config = igp_obj-> ulDDISlot1Config; else slot_config = igp_obj-> ulDDISlot2Config; ct = (slot_config >> 16) & 0xff; connector_type = object_connector_convert [ct]; connector_object_id = ct; igp_lane_info = slot_config & 0xffff; } else continue; } else continue; } else { igp_lane_info = 0; connector_type = object_connector_convert[con_obj_id]; connector_object_id = con_obj_id; } } else { igp_lane_info = 0; connector_type = object_connector_convert[con_obj_id]; connector_object_id = con_obj_id; } if (connector_type == DRM_MODE_CONNECTOR_Unknown) continue; for (j = 0; j < ((le16_to_cpu(path->usSize) - 8) / 2); j++) { uint8_t enc_obj_id, enc_obj_num, enc_obj_type; enc_obj_id = (le16_to_cpu(path->usGraphicObjIds[j]) & OBJECT_ID_MASK) >> OBJECT_ID_SHIFT; enc_obj_num = (le16_to_cpu(path->usGraphicObjIds[j]) & ENUM_ID_MASK) >> ENUM_ID_SHIFT; enc_obj_type = (le16_to_cpu(path->usGraphicObjIds[j]) & OBJECT_TYPE_MASK) >> OBJECT_TYPE_SHIFT; /* FIXME: add support for router objects */ if (enc_obj_type == GRAPH_OBJECT_TYPE_ENCODER) { if (enc_obj_num == 2) linkb = true; else linkb = false; radeon_add_atom_encoder(dev, enc_obj_id, le16_to_cpu (path-> usDeviceTag)); } } /* look up gpio for ddc, hpd */ if ((le16_to_cpu(path->usDeviceTag) & (ATOM_DEVICE_TV_SUPPORT | ATOM_DEVICE_CV_SUPPORT)) == 0) { for (j = 0; j < con_obj->ucNumberOfObjects; j++) { if (le16_to_cpu(path->usConnObjectId) == le16_to_cpu(con_obj->asObjects[j]. usObjectID)) { ATOM_COMMON_RECORD_HEADER *record = (ATOM_COMMON_RECORD_HEADER *) (ctx->bios + data_offset + le16_to_cpu(con_obj-> asObjects[j]. usRecordOffset)); ATOM_I2C_RECORD *i2c_record; ATOM_HPD_INT_RECORD *hpd_record; ATOM_I2C_ID_CONFIG_ACCESS *i2c_config; hpd.hpd = RADEON_HPD_NONE; while (record->ucRecordType > 0 && record-> ucRecordType <= ATOM_MAX_OBJECT_RECORD_NUMBER) { switch (record->ucRecordType) { case ATOM_I2C_RECORD_TYPE: i2c_record = (ATOM_I2C_RECORD *) record; i2c_config = (ATOM_I2C_ID_CONFIG_ACCESS *) &i2c_record->sucI2cId; ddc_bus = radeon_lookup_i2c_gpio(rdev, i2c_config-> ucAccess); break; case ATOM_HPD_INT_RECORD_TYPE: hpd_record = (ATOM_HPD_INT_RECORD *) record; gpio = radeon_lookup_gpio(rdev, hpd_record->ucHPDIntGPIOID); hpd = radeon_atom_get_hpd_info_from_gpio(rdev, &gpio); hpd.plugged_state = hpd_record->ucPlugged_PinState; break; } record = (ATOM_COMMON_RECORD_HEADER *) ((char *)record + record-> ucRecordSize); } break; } } } else { hpd.hpd = RADEON_HPD_NONE; ddc_bus.valid = false; } /* needed for aux chan transactions */ ddc_bus.hpd_id = hpd.hpd ? (hpd.hpd - 1) : 0; conn_id = le16_to_cpu(path->usConnObjectId); if (!radeon_atom_apply_quirks (dev, le16_to_cpu(path->usDeviceTag), &connector_type, &ddc_bus, &conn_id, &hpd)) continue; radeon_add_atom_connector(dev, conn_id, le16_to_cpu(path-> usDeviceTag), connector_type, &ddc_bus, linkb, igp_lane_info, connector_object_id, &hpd); } } radeon_link_encoder_connector(dev); return true; } static uint16_t atombios_get_connector_object_id(struct drm_device *dev, int connector_type, uint16_t devices) { struct radeon_device *rdev = dev->dev_private; if (rdev->flags & RADEON_IS_IGP) { return supported_devices_connector_object_id_convert [connector_type]; } else if (((connector_type == DRM_MODE_CONNECTOR_DVII) || (connector_type == DRM_MODE_CONNECTOR_DVID)) && (devices & ATOM_DEVICE_DFP2_SUPPORT)) { struct radeon_mode_info *mode_info = &rdev->mode_info; struct atom_context *ctx = mode_info->atom_context; int index = GetIndexIntoMasterTable(DATA, XTMDS_Info); uint16_t size, data_offset; uint8_t frev, crev; ATOM_XTMDS_INFO *xtmds; if (atom_parse_data_header(ctx, index, &size, &frev, &crev, &data_offset)) { xtmds = (ATOM_XTMDS_INFO *)(ctx->bios + data_offset); if (xtmds->ucSupportedLink & ATOM_XTMDS_SUPPORTED_DUALLINK) { if (connector_type == DRM_MODE_CONNECTOR_DVII) return CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_I; else return CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_D; } else { if (connector_type == DRM_MODE_CONNECTOR_DVII) return CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_I; else return CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_D; } } else return supported_devices_connector_object_id_convert [connector_type]; } else { return supported_devices_connector_object_id_convert [connector_type]; } } struct bios_connector { bool valid; uint16_t line_mux; uint16_t devices; int connector_type; struct radeon_i2c_bus_rec ddc_bus; struct radeon_hpd hpd; }; bool radeon_get_atom_connector_info_from_supported_devices_table(struct drm_device *dev) { struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; struct atom_context *ctx = mode_info->atom_context; int index = GetIndexIntoMasterTable(DATA, SupportedDevicesInfo); uint16_t size, data_offset; uint8_t frev, crev; uint16_t device_support; uint8_t dac; union atom_supported_devices *supported_devices; int i, j, max_device; struct bios_connector bios_connectors[ATOM_MAX_SUPPORTED_DEVICE]; if (!atom_parse_data_header(ctx, index, &size, &frev, &crev, &data_offset)) return false; supported_devices = (union atom_supported_devices *)(ctx->bios + data_offset); device_support = le16_to_cpu(supported_devices->info.usDeviceSupport); if (frev > 1) max_device = ATOM_MAX_SUPPORTED_DEVICE; else max_device = ATOM_MAX_SUPPORTED_DEVICE_INFO; for (i = 0; i < max_device; i++) { ATOM_CONNECTOR_INFO_I2C ci = supported_devices->info.asConnInfo[i]; bios_connectors[i].valid = false; if (!(device_support & (1 << i))) { continue; } if (i == ATOM_DEVICE_CV_INDEX) { DRM_DEBUG("Skipping Component Video\n"); continue; } bios_connectors[i].connector_type = supported_devices_connector_convert[ci.sucConnectorInfo. sbfAccess. bfConnectorType]; if (bios_connectors[i].connector_type == DRM_MODE_CONNECTOR_Unknown) continue; dac = ci.sucConnectorInfo.sbfAccess.bfAssociatedDAC; bios_connectors[i].line_mux = ci.sucI2cId.ucAccess; /* give tv unique connector ids */ if (i == ATOM_DEVICE_TV1_INDEX) { bios_connectors[i].ddc_bus.valid = false; bios_connectors[i].line_mux = 50; } else if (i == ATOM_DEVICE_TV2_INDEX) { bios_connectors[i].ddc_bus.valid = false; bios_connectors[i].line_mux = 51; } else if (i == ATOM_DEVICE_CV_INDEX) { bios_connectors[i].ddc_bus.valid = false; bios_connectors[i].line_mux = 52; } else bios_connectors[i].ddc_bus = radeon_lookup_i2c_gpio(rdev, bios_connectors[i].line_mux); if ((crev > 1) && (frev > 1)) { u8 isb = supported_devices->info_2d1.asIntSrcInfo[i].ucIntSrcBitmap; switch (isb) { case 0x4: bios_connectors[i].hpd.hpd = RADEON_HPD_1; break; case 0xa: bios_connectors[i].hpd.hpd = RADEON_HPD_2; break; default: bios_connectors[i].hpd.hpd = RADEON_HPD_NONE; break; } } else { if (i == ATOM_DEVICE_DFP1_INDEX) bios_connectors[i].hpd.hpd = RADEON_HPD_1; else if (i == ATOM_DEVICE_DFP2_INDEX) bios_connectors[i].hpd.hpd = RADEON_HPD_2; else bios_connectors[i].hpd.hpd = RADEON_HPD_NONE; } /* Always set the connector type to VGA for CRT1/CRT2. if they are * shared with a DVI port, we'll pick up the DVI connector when we * merge the outputs. Some bioses incorrectly list VGA ports as DVI. */ if (i == ATOM_DEVICE_CRT1_INDEX || i == ATOM_DEVICE_CRT2_INDEX) bios_connectors[i].connector_type = DRM_MODE_CONNECTOR_VGA; if (!radeon_atom_apply_quirks (dev, (1 << i), &bios_connectors[i].connector_type, &bios_connectors[i].ddc_bus, &bios_connectors[i].line_mux, &bios_connectors[i].hpd)) continue; bios_connectors[i].valid = true; bios_connectors[i].devices = (1 << i); if (ASIC_IS_AVIVO(rdev) || radeon_r4xx_atom) radeon_add_atom_encoder(dev, radeon_get_encoder_id(dev, (1 << i), dac), (1 << i)); else radeon_add_legacy_encoder(dev, radeon_get_encoder_id(dev, (1 << i), dac), (1 << i)); } /* combine shared connectors */ for (i = 0; i < max_device; i++) { if (bios_connectors[i].valid) { for (j = 0; j < max_device; j++) { if (bios_connectors[j].valid && (i != j)) { if (bios_connectors[i].line_mux == bios_connectors[j].line_mux) { /* make sure not to combine LVDS */ if (bios_connectors[i].devices & (ATOM_DEVICE_LCD_SUPPORT)) { bios_connectors[i].line_mux = 53; bios_connectors[i].ddc_bus.valid = false; continue; } if (bios_connectors[j].devices & (ATOM_DEVICE_LCD_SUPPORT)) { bios_connectors[j].line_mux = 53; bios_connectors[j].ddc_bus.valid = false; continue; } /* combine analog and digital for DVI-I */ if (((bios_connectors[i].devices & (ATOM_DEVICE_DFP_SUPPORT)) && (bios_connectors[j].devices & (ATOM_DEVICE_CRT_SUPPORT))) || ((bios_connectors[j].devices & (ATOM_DEVICE_DFP_SUPPORT)) && (bios_connectors[i].devices & (ATOM_DEVICE_CRT_SUPPORT)))) { bios_connectors[i].devices |= bios_connectors[j].devices; bios_connectors[i].connector_type = DRM_MODE_CONNECTOR_DVII; if (bios_connectors[j].devices & (ATOM_DEVICE_DFP_SUPPORT)) bios_connectors[i].hpd = bios_connectors[j].hpd; bios_connectors[j].valid = false; } } } } } } /* add the connectors */ for (i = 0; i < max_device; i++) { if (bios_connectors[i].valid) { uint16_t connector_object_id = atombios_get_connector_object_id(dev, bios_connectors[i].connector_type, bios_connectors[i].devices); radeon_add_atom_connector(dev, bios_connectors[i].line_mux, bios_connectors[i].devices, bios_connectors[i]. connector_type, &bios_connectors[i].ddc_bus, false, 0, connector_object_id, &bios_connectors[i].hpd); } } radeon_link_encoder_connector(dev); return true; } union firmware_info { ATOM_FIRMWARE_INFO info; ATOM_FIRMWARE_INFO_V1_2 info_12; ATOM_FIRMWARE_INFO_V1_3 info_13; ATOM_FIRMWARE_INFO_V1_4 info_14; ATOM_FIRMWARE_INFO_V2_1 info_21; }; bool radeon_atom_get_clock_info(struct drm_device *dev) { struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, FirmwareInfo); union firmware_info *firmware_info; uint8_t frev, crev; struct radeon_pll *p1pll = &rdev->clock.p1pll; struct radeon_pll *p2pll = &rdev->clock.p2pll; struct radeon_pll *dcpll = &rdev->clock.dcpll; struct radeon_pll *spll = &rdev->clock.spll; struct radeon_pll *mpll = &rdev->clock.mpll; uint16_t data_offset; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { firmware_info = (union firmware_info *)(mode_info->atom_context->bios + data_offset); /* pixel clocks */ p1pll->reference_freq = le16_to_cpu(firmware_info->info.usReferenceClock); p1pll->reference_div = 0; if (crev < 2) p1pll->pll_out_min = le16_to_cpu(firmware_info->info.usMinPixelClockPLL_Output); else p1pll->pll_out_min = le32_to_cpu(firmware_info->info_12.ulMinPixelClockPLL_Output); p1pll->pll_out_max = le32_to_cpu(firmware_info->info.ulMaxPixelClockPLL_Output); if (crev >= 4) { p1pll->lcd_pll_out_min = le16_to_cpu(firmware_info->info_14.usLcdMinPixelClockPLL_Output) * 100; if (p1pll->lcd_pll_out_min == 0) p1pll->lcd_pll_out_min = p1pll->pll_out_min; p1pll->lcd_pll_out_max = le16_to_cpu(firmware_info->info_14.usLcdMaxPixelClockPLL_Output) * 100; if (p1pll->lcd_pll_out_max == 0) p1pll->lcd_pll_out_max = p1pll->pll_out_max; } else { p1pll->lcd_pll_out_min = p1pll->pll_out_min; p1pll->lcd_pll_out_max = p1pll->pll_out_max; } if (p1pll->pll_out_min == 0) { if (ASIC_IS_AVIVO(rdev)) p1pll->pll_out_min = 64800; else p1pll->pll_out_min = 20000; } else if (p1pll->pll_out_min > 64800) { /* Limiting the pll output range is a good thing generally as * it limits the number of possible pll combinations for a given * frequency presumably to the ones that work best on each card. * However, certain duallink DVI monitors seem to like * pll combinations that would be limited by this at least on * pre-DCE 3.0 r6xx hardware. This might need to be adjusted per * family. */ if (!radeon_new_pll) p1pll->pll_out_min = 64800; } p1pll->pll_in_min = le16_to_cpu(firmware_info->info.usMinPixelClockPLL_Input); p1pll->pll_in_max = le16_to_cpu(firmware_info->info.usMaxPixelClockPLL_Input); *p2pll = *p1pll; /* system clock */ spll->reference_freq = le16_to_cpu(firmware_info->info.usReferenceClock); spll->reference_div = 0; spll->pll_out_min = le16_to_cpu(firmware_info->info.usMinEngineClockPLL_Output); spll->pll_out_max = le32_to_cpu(firmware_info->info.ulMaxEngineClockPLL_Output); /* ??? */ if (spll->pll_out_min == 0) { if (ASIC_IS_AVIVO(rdev)) spll->pll_out_min = 64800; else spll->pll_out_min = 20000; } spll->pll_in_min = le16_to_cpu(firmware_info->info.usMinEngineClockPLL_Input); spll->pll_in_max = le16_to_cpu(firmware_info->info.usMaxEngineClockPLL_Input); /* memory clock */ mpll->reference_freq = le16_to_cpu(firmware_info->info.usReferenceClock); mpll->reference_div = 0; mpll->pll_out_min = le16_to_cpu(firmware_info->info.usMinMemoryClockPLL_Output); mpll->pll_out_max = le32_to_cpu(firmware_info->info.ulMaxMemoryClockPLL_Output); /* ??? */ if (mpll->pll_out_min == 0) { if (ASIC_IS_AVIVO(rdev)) mpll->pll_out_min = 64800; else mpll->pll_out_min = 20000; } mpll->pll_in_min = le16_to_cpu(firmware_info->info.usMinMemoryClockPLL_Input); mpll->pll_in_max = le16_to_cpu(firmware_info->info.usMaxMemoryClockPLL_Input); rdev->clock.default_sclk = le32_to_cpu(firmware_info->info.ulDefaultEngineClock); rdev->clock.default_mclk = le32_to_cpu(firmware_info->info.ulDefaultMemoryClock); if (ASIC_IS_DCE4(rdev)) { rdev->clock.default_dispclk = le32_to_cpu(firmware_info->info_21.ulDefaultDispEngineClkFreq); if (rdev->clock.default_dispclk == 0) rdev->clock.default_dispclk = 60000; /* 600 Mhz */ rdev->clock.dp_extclk = le16_to_cpu(firmware_info->info_21.usUniphyDPModeExtClkFreq); } *dcpll = *p1pll; return true; } return false; } union igp_info { struct _ATOM_INTEGRATED_SYSTEM_INFO info; struct _ATOM_INTEGRATED_SYSTEM_INFO_V2 info_2; }; bool radeon_atombios_sideport_present(struct radeon_device *rdev) { struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, IntegratedSystemInfo); union igp_info *igp_info; u8 frev, crev; u16 data_offset; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { igp_info = (union igp_info *)(mode_info->atom_context->bios + data_offset); switch (crev) { case 1: if (igp_info->info.ucMemoryType & 0xf0) return true; break; case 2: if (igp_info->info_2.ucMemoryType & 0x0f) return true; break; default: DRM_ERROR("Unsupported IGP table: %d %d\n", frev, crev); break; } } return false; } bool radeon_atombios_get_tmds_info(struct radeon_encoder *encoder, struct radeon_encoder_int_tmds *tmds) { struct drm_device *dev = encoder->base.dev; struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, TMDS_Info); uint16_t data_offset; struct _ATOM_TMDS_INFO *tmds_info; uint8_t frev, crev; uint16_t maxfreq; int i; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { tmds_info = (struct _ATOM_TMDS_INFO *)(mode_info->atom_context->bios + data_offset); maxfreq = le16_to_cpu(tmds_info->usMaxFrequency); for (i = 0; i < 4; i++) { tmds->tmds_pll[i].freq = le16_to_cpu(tmds_info->asMiscInfo[i].usFrequency); tmds->tmds_pll[i].value = tmds_info->asMiscInfo[i].ucPLL_ChargePump & 0x3f; tmds->tmds_pll[i].value |= (tmds_info->asMiscInfo[i]. ucPLL_VCO_Gain & 0x3f) << 6; tmds->tmds_pll[i].value |= (tmds_info->asMiscInfo[i]. ucPLL_DutyCycle & 0xf) << 12; tmds->tmds_pll[i].value |= (tmds_info->asMiscInfo[i]. ucPLL_VoltageSwing & 0xf) << 16; DRM_DEBUG("TMDS PLL From ATOMBIOS %u %x\n", tmds->tmds_pll[i].freq, tmds->tmds_pll[i].value); if (maxfreq == tmds->tmds_pll[i].freq) { tmds->tmds_pll[i].freq = 0xffffffff; break; } } return true; } return false; } static struct radeon_atom_ss *radeon_atombios_get_ss_info(struct radeon_encoder *encoder, int id) { struct drm_device *dev = encoder->base.dev; struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, PPLL_SS_Info); uint16_t data_offset; struct _ATOM_SPREAD_SPECTRUM_INFO *ss_info; uint8_t frev, crev; struct radeon_atom_ss *ss = NULL; int i; if (id > ATOM_MAX_SS_ENTRY) return NULL; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { ss_info = (struct _ATOM_SPREAD_SPECTRUM_INFO *)(mode_info->atom_context->bios + data_offset); ss = kzalloc(sizeof(struct radeon_atom_ss), GFP_KERNEL); if (!ss) return NULL; for (i = 0; i < ATOM_MAX_SS_ENTRY; i++) { if (ss_info->asSS_Info[i].ucSS_Id == id) { ss->percentage = le16_to_cpu(ss_info->asSS_Info[i].usSpreadSpectrumPercentage); ss->type = ss_info->asSS_Info[i].ucSpreadSpectrumType; ss->step = ss_info->asSS_Info[i].ucSS_Step; ss->delay = ss_info->asSS_Info[i].ucSS_Delay; ss->range = ss_info->asSS_Info[i].ucSS_Range; ss->refdiv = ss_info->asSS_Info[i].ucRecommendedRef_Div; break; } } } return ss; } union lvds_info { struct _ATOM_LVDS_INFO info; struct _ATOM_LVDS_INFO_V12 info_12; }; struct radeon_encoder_atom_dig *radeon_atombios_get_lvds_info(struct radeon_encoder *encoder) { struct drm_device *dev = encoder->base.dev; struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, LVDS_Info); uint16_t data_offset, misc; union lvds_info *lvds_info; uint8_t frev, crev; struct radeon_encoder_atom_dig *lvds = NULL; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { lvds_info = (union lvds_info *)(mode_info->atom_context->bios + data_offset); lvds = kzalloc(sizeof(struct radeon_encoder_atom_dig), GFP_KERNEL); if (!lvds) return NULL; lvds->native_mode.clock = le16_to_cpu(lvds_info->info.sLCDTiming.usPixClk) * 10; lvds->native_mode.hdisplay = le16_to_cpu(lvds_info->info.sLCDTiming.usHActive); lvds->native_mode.vdisplay = le16_to_cpu(lvds_info->info.sLCDTiming.usVActive); lvds->native_mode.htotal = lvds->native_mode.hdisplay + le16_to_cpu(lvds_info->info.sLCDTiming.usHBlanking_Time); lvds->native_mode.hsync_start = lvds->native_mode.hdisplay + le16_to_cpu(lvds_info->info.sLCDTiming.usHSyncOffset); lvds->native_mode.hsync_end = lvds->native_mode.hsync_start + le16_to_cpu(lvds_info->info.sLCDTiming.usHSyncWidth); lvds->native_mode.vtotal = lvds->native_mode.vdisplay + le16_to_cpu(lvds_info->info.sLCDTiming.usVBlanking_Time); lvds->native_mode.vsync_start = lvds->native_mode.vdisplay + le16_to_cpu(lvds_info->info.sLCDTiming.usVSyncWidth); lvds->native_mode.vsync_end = lvds->native_mode.vsync_start + le16_to_cpu(lvds_info->info.sLCDTiming.usVSyncWidth); lvds->panel_pwr_delay = le16_to_cpu(lvds_info->info.usOffDelayInMs); lvds->lvds_misc = lvds_info->info.ucLVDS_Misc; misc = le16_to_cpu(lvds_info->info.sLCDTiming.susModeMiscInfo.usAccess); if (misc & ATOM_VSYNC_POLARITY) lvds->native_mode.flags |= DRM_MODE_FLAG_NVSYNC; if (misc & ATOM_HSYNC_POLARITY) lvds->native_mode.flags |= DRM_MODE_FLAG_NHSYNC; if (misc & ATOM_COMPOSITESYNC) lvds->native_mode.flags |= DRM_MODE_FLAG_CSYNC; if (misc & ATOM_INTERLACE) lvds->native_mode.flags |= DRM_MODE_FLAG_INTERLACE; if (misc & ATOM_DOUBLE_CLOCK_MODE) lvds->native_mode.flags |= DRM_MODE_FLAG_DBLSCAN; /* set crtc values */ drm_mode_set_crtcinfo(&lvds->native_mode, CRTC_INTERLACE_HALVE_V); lvds->ss = radeon_atombios_get_ss_info(encoder, lvds_info->info.ucSS_Id); if (ASIC_IS_AVIVO(rdev)) { if (radeon_new_pll == 0) lvds->pll_algo = PLL_ALGO_LEGACY; else lvds->pll_algo = PLL_ALGO_NEW; } else { if (radeon_new_pll == 1) lvds->pll_algo = PLL_ALGO_NEW; else lvds->pll_algo = PLL_ALGO_LEGACY; } encoder->native_mode = lvds->native_mode; } return lvds; } struct radeon_encoder_primary_dac * radeon_atombios_get_primary_dac_info(struct radeon_encoder *encoder) { struct drm_device *dev = encoder->base.dev; struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, CompassionateData); uint16_t data_offset; struct _COMPASSIONATE_DATA *dac_info; uint8_t frev, crev; uint8_t bg, dac; struct radeon_encoder_primary_dac *p_dac = NULL; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { dac_info = (struct _COMPASSIONATE_DATA *) (mode_info->atom_context->bios + data_offset); p_dac = kzalloc(sizeof(struct radeon_encoder_primary_dac), GFP_KERNEL); if (!p_dac) return NULL; bg = dac_info->ucDAC1_BG_Adjustment; dac = dac_info->ucDAC1_DAC_Adjustment; p_dac->ps2_pdac_adj = (bg << 8) | (dac); } return p_dac; } bool radeon_atom_get_tv_timings(struct radeon_device *rdev, int index, struct drm_display_mode *mode) { struct radeon_mode_info *mode_info = &rdev->mode_info; ATOM_ANALOG_TV_INFO *tv_info; ATOM_ANALOG_TV_INFO_V1_2 *tv_info_v1_2; ATOM_DTD_FORMAT *dtd_timings; int data_index = GetIndexIntoMasterTable(DATA, AnalogTV_Info); u8 frev, crev; u16 data_offset, misc; if (!atom_parse_data_header(mode_info->atom_context, data_index, NULL, &frev, &crev, &data_offset)) return false; switch (crev) { case 1: tv_info = (ATOM_ANALOG_TV_INFO *)(mode_info->atom_context->bios + data_offset); if (index > MAX_SUPPORTED_TV_TIMING) return false; mode->crtc_htotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Total); mode->crtc_hdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Disp); mode->crtc_hsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart); mode->crtc_hsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart) + le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncWidth); mode->crtc_vtotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Total); mode->crtc_vdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Disp); mode->crtc_vsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart); mode->crtc_vsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart) + le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncWidth); mode->flags = 0; misc = le16_to_cpu(tv_info->aModeTimings[index].susModeMiscInfo.usAccess); if (misc & ATOM_VSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NVSYNC; if (misc & ATOM_HSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NHSYNC; if (misc & ATOM_COMPOSITESYNC) mode->flags |= DRM_MODE_FLAG_CSYNC; if (misc & ATOM_INTERLACE) mode->flags |= DRM_MODE_FLAG_INTERLACE; if (misc & ATOM_DOUBLE_CLOCK_MODE) mode->flags |= DRM_MODE_FLAG_DBLSCAN; mode->clock = le16_to_cpu(tv_info->aModeTimings[index].usPixelClock) * 10; if (index == 1) { /* PAL timings appear to have wrong values for totals */ mode->crtc_htotal -= 1; mode->crtc_vtotal -= 1; } break; case 2: tv_info_v1_2 = (ATOM_ANALOG_TV_INFO_V1_2 *)(mode_info->atom_context->bios + data_offset); if (index > MAX_SUPPORTED_TV_TIMING_V1_2) return false; dtd_timings = &tv_info_v1_2->aModeTimings[index]; mode->crtc_htotal = le16_to_cpu(dtd_timings->usHActive) + le16_to_cpu(dtd_timings->usHBlanking_Time); mode->crtc_hdisplay = le16_to_cpu(dtd_timings->usHActive); mode->crtc_hsync_start = le16_to_cpu(dtd_timings->usHActive) + le16_to_cpu(dtd_timings->usHSyncOffset); mode->crtc_hsync_end = mode->crtc_hsync_start + le16_to_cpu(dtd_timings->usHSyncWidth); mode->crtc_vtotal = le16_to_cpu(dtd_timings->usVActive) + le16_to_cpu(dtd_timings->usVBlanking_Time); mode->crtc_vdisplay = le16_to_cpu(dtd_timings->usVActive); mode->crtc_vsync_start = le16_to_cpu(dtd_timings->usVActive) + le16_to_cpu(dtd_timings->usVSyncOffset); mode->crtc_vsync_end = mode->crtc_vsync_start + le16_to_cpu(dtd_timings->usVSyncWidth); mode->flags = 0; misc = le16_to_cpu(dtd_timings->susModeMiscInfo.usAccess); if (misc & ATOM_VSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NVSYNC; if (misc & ATOM_HSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NHSYNC; if (misc & ATOM_COMPOSITESYNC) mode->flags |= DRM_MODE_FLAG_CSYNC; if (misc & ATOM_INTERLACE) mode->flags |= DRM_MODE_FLAG_INTERLACE; if (misc & ATOM_DOUBLE_CLOCK_MODE) mode->flags |= DRM_MODE_FLAG_DBLSCAN; mode->clock = le16_to_cpu(dtd_timings->usPixClk) * 10; break; } return true; } enum radeon_tv_std radeon_atombios_get_tv_info(struct radeon_device *rdev) { struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, AnalogTV_Info); uint16_t data_offset; uint8_t frev, crev; struct _ATOM_ANALOG_TV_INFO *tv_info; enum radeon_tv_std tv_std = TV_STD_NTSC; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { tv_info = (struct _ATOM_ANALOG_TV_INFO *) (mode_info->atom_context->bios + data_offset); switch (tv_info->ucTV_BootUpDefaultStandard) { case ATOM_TV_NTSC: tv_std = TV_STD_NTSC; DRM_INFO("Default TV standard: NTSC\n"); break; case ATOM_TV_NTSCJ: tv_std = TV_STD_NTSC_J; DRM_INFO("Default TV standard: NTSC-J\n"); break; case ATOM_TV_PAL: tv_std = TV_STD_PAL; DRM_INFO("Default TV standard: PAL\n"); break; case ATOM_TV_PALM: tv_std = TV_STD_PAL_M; DRM_INFO("Default TV standard: PAL-M\n"); break; case ATOM_TV_PALN: tv_std = TV_STD_PAL_N; DRM_INFO("Default TV standard: PAL-N\n"); break; case ATOM_TV_PALCN: tv_std = TV_STD_PAL_CN; DRM_INFO("Default TV standard: PAL-CN\n"); break; case ATOM_TV_PAL60: tv_std = TV_STD_PAL_60; DRM_INFO("Default TV standard: PAL-60\n"); break; case ATOM_TV_SECAM: tv_std = TV_STD_SECAM; DRM_INFO("Default TV standard: SECAM\n"); break; default: tv_std = TV_STD_NTSC; DRM_INFO("Unknown TV standard; defaulting to NTSC\n"); break; } } return tv_std; } struct radeon_encoder_tv_dac * radeon_atombios_get_tv_dac_info(struct radeon_encoder *encoder) { struct drm_device *dev = encoder->base.dev; struct radeon_device *rdev = dev->dev_private; struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, CompassionateData); uint16_t data_offset; struct _COMPASSIONATE_DATA *dac_info; uint8_t frev, crev; uint8_t bg, dac; struct radeon_encoder_tv_dac *tv_dac = NULL; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { dac_info = (struct _COMPASSIONATE_DATA *) (mode_info->atom_context->bios + data_offset); tv_dac = kzalloc(sizeof(struct radeon_encoder_tv_dac), GFP_KERNEL); if (!tv_dac) return NULL; bg = dac_info->ucDAC2_CRT2_BG_Adjustment; dac = dac_info->ucDAC2_CRT2_DAC_Adjustment; tv_dac->ps2_tvdac_adj = (bg << 16) | (dac << 20); bg = dac_info->ucDAC2_PAL_BG_Adjustment; dac = dac_info->ucDAC2_PAL_DAC_Adjustment; tv_dac->pal_tvdac_adj = (bg << 16) | (dac << 20); bg = dac_info->ucDAC2_NTSC_BG_Adjustment; dac = dac_info->ucDAC2_NTSC_DAC_Adjustment; tv_dac->ntsc_tvdac_adj = (bg << 16) | (dac << 20); tv_dac->tv_std = radeon_atombios_get_tv_info(rdev); } return tv_dac; } static const char *thermal_controller_names[] = { "NONE", "LM63", "ADM1032", "ADM1030", "MUA6649", "LM64", "F75375", "ASC7512", }; static const char *pp_lib_thermal_controller_names[] = { "NONE", "LM63", "ADM1032", "ADM1030", "MUA6649", "LM64", "F75375", "RV6xx", "RV770", "ADT7473", }; union power_info { struct _ATOM_POWERPLAY_INFO info; struct _ATOM_POWERPLAY_INFO_V2 info_2; struct _ATOM_POWERPLAY_INFO_V3 info_3; struct _ATOM_PPLIB_POWERPLAYTABLE info_4; }; void radeon_atombios_get_power_modes(struct radeon_device *rdev) { struct radeon_mode_info *mode_info = &rdev->mode_info; int index = GetIndexIntoMasterTable(DATA, PowerPlayInfo); u16 data_offset; u8 frev, crev; u32 misc, misc2 = 0, sclk, mclk; union power_info *power_info; struct _ATOM_PPLIB_NONCLOCK_INFO *non_clock_info; struct _ATOM_PPLIB_STATE *power_state; int num_modes = 0, i, j; int state_index = 0, mode_index = 0; struct radeon_i2c_bus_rec i2c_bus; rdev->pm.default_power_state = NULL; if (atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) { power_info = (union power_info *)(mode_info->atom_context->bios + data_offset); if (frev < 4) { /* add the i2c bus for thermal/fan chip */ if (power_info->info.ucOverdriveThermalController > 0) { DRM_INFO("Possible %s thermal controller at 0x%02x\n", thermal_controller_names[power_info->info.ucOverdriveThermalController], power_info->info.ucOverdriveControllerAddress >> 1); i2c_bus = radeon_lookup_i2c_gpio(rdev, power_info->info.ucOverdriveI2cLine); rdev->pm.i2c_bus = radeon_i2c_create(rdev->ddev, &i2c_bus, "Thermal"); } num_modes = power_info->info.ucNumOfPowerModeEntries; if (num_modes > ATOM_MAX_NUMBEROF_POWER_BLOCK) num_modes = ATOM_MAX_NUMBEROF_POWER_BLOCK; for (i = 0; i < num_modes; i++) { rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_NONE; switch (frev) { case 1: rdev->pm.power_state[state_index].num_clock_modes = 1; rdev->pm.power_state[state_index].clock_info[0].mclk = le16_to_cpu(power_info->info.asPowerPlayInfo[i].usMemoryClock); rdev->pm.power_state[state_index].clock_info[0].sclk = le16_to_cpu(power_info->info.asPowerPlayInfo[i].usEngineClock); /* skip invalid modes */ if ((rdev->pm.power_state[state_index].clock_info[0].mclk == 0) || (rdev->pm.power_state[state_index].clock_info[0].sclk == 0)) continue; /* skip overclock modes for now */ if ((rdev->pm.power_state[state_index].clock_info[0].mclk > rdev->clock.default_mclk + RADEON_MODE_OVERCLOCK_MARGIN) || (rdev->pm.power_state[state_index].clock_info[0].sclk > rdev->clock.default_sclk + RADEON_MODE_OVERCLOCK_MARGIN)) continue; rdev->pm.power_state[state_index].non_clock_info.pcie_lanes = power_info->info.asPowerPlayInfo[i].ucNumPciELanes; misc = le32_to_cpu(power_info->info.asPowerPlayInfo[i].ulMiscInfo); if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_SUPPORT) { rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_GPIO; rdev->pm.power_state[state_index].clock_info[0].voltage.gpio = radeon_lookup_gpio(rdev, power_info->info.asPowerPlayInfo[i].ucVoltageDropIndex); if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_ACTIVE_HIGH) rdev->pm.power_state[state_index].clock_info[0].voltage.active_high = true; else rdev->pm.power_state[state_index].clock_info[0].voltage.active_high = false; } else if (misc & ATOM_PM_MISCINFO_PROGRAM_VOLTAGE) { rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_VDDC; rdev->pm.power_state[state_index].clock_info[0].voltage.vddc_id = power_info->info.asPowerPlayInfo[i].ucVoltageDropIndex; } /* order matters! */ if (misc & ATOM_PM_MISCINFO_POWER_SAVING_MODE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_POWERSAVE; if (misc & ATOM_PM_MISCINFO_DEFAULT_DC_STATE_ENTRY_TRUE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BATTERY; if (misc & ATOM_PM_MISCINFO_DEFAULT_LOW_DC_STATE_ENTRY_TRUE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BATTERY; if (misc & ATOM_PM_MISCINFO_LOAD_BALANCE_EN) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BALANCED; if (misc & ATOM_PM_MISCINFO_3D_ACCELERATION_EN) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_PERFORMANCE; if (misc & ATOM_PM_MISCINFO_DRIVER_DEFAULT_MODE) { rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_DEFAULT; rdev->pm.default_power_state = &rdev->pm.power_state[state_index]; rdev->pm.power_state[state_index].default_clock_mode = &rdev->pm.power_state[state_index].clock_info[0]; } state_index++; break; case 2: rdev->pm.power_state[state_index].num_clock_modes = 1; rdev->pm.power_state[state_index].clock_info[0].mclk = le32_to_cpu(power_info->info_2.asPowerPlayInfo[i].ulMemoryClock); rdev->pm.power_state[state_index].clock_info[0].sclk = le32_to_cpu(power_info->info_2.asPowerPlayInfo[i].ulEngineClock); /* skip invalid modes */ if ((rdev->pm.power_state[state_index].clock_info[0].mclk == 0) || (rdev->pm.power_state[state_index].clock_info[0].sclk == 0)) continue; /* skip overclock modes for now */ if ((rdev->pm.power_state[state_index].clock_info[0].mclk > rdev->clock.default_mclk + RADEON_MODE_OVERCLOCK_MARGIN) || (rdev->pm.power_state[state_index].clock_info[0].sclk > rdev->clock.default_sclk + RADEON_MODE_OVERCLOCK_MARGIN)) continue; rdev->pm.power_state[state_index].non_clock_info.pcie_lanes = power_info->info_2.asPowerPlayInfo[i].ucNumPciELanes; misc = le32_to_cpu(power_info->info_2.asPowerPlayInfo[i].ulMiscInfo); misc2 = le32_to_cpu(power_info->info_2.asPowerPlayInfo[i].ulMiscInfo2); if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_SUPPORT) { rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_GPIO; rdev->pm.power_state[state_index].clock_info[0].voltage.gpio = radeon_lookup_gpio(rdev, power_info->info_2.asPowerPlayInfo[i].ucVoltageDropIndex); if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_ACTIVE_HIGH) rdev->pm.power_state[state_index].clock_info[0].voltage.active_high = true; else rdev->pm.power_state[state_index].clock_info[0].voltage.active_high = false; } else if (misc & ATOM_PM_MISCINFO_PROGRAM_VOLTAGE) { rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_VDDC; rdev->pm.power_state[state_index].clock_info[0].voltage.vddc_id = power_info->info_2.asPowerPlayInfo[i].ucVoltageDropIndex; } /* order matters! */ if (misc & ATOM_PM_MISCINFO_POWER_SAVING_MODE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_POWERSAVE; if (misc & ATOM_PM_MISCINFO_DEFAULT_DC_STATE_ENTRY_TRUE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BATTERY; if (misc & ATOM_PM_MISCINFO_DEFAULT_LOW_DC_STATE_ENTRY_TRUE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BATTERY; if (misc & ATOM_PM_MISCINFO_LOAD_BALANCE_EN) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BALANCED; if (misc & ATOM_PM_MISCINFO_3D_ACCELERATION_EN) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_PERFORMANCE; if (misc2 & ATOM_PM_MISCINFO2_SYSTEM_AC_LITE_MODE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BALANCED; if (misc & ATOM_PM_MISCINFO_DRIVER_DEFAULT_MODE) { rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_DEFAULT; rdev->pm.default_power_state = &rdev->pm.power_state[state_index]; rdev->pm.power_state[state_index].default_clock_mode = &rdev->pm.power_state[state_index].clock_info[0]; } state_index++; break; case 3: rdev->pm.power_state[state_index].num_clock_modes = 1; rdev->pm.power_state[state_index].clock_info[0].mclk = le32_to_cpu(power_info->info_3.asPowerPlayInfo[i].ulMemoryClock); rdev->pm.power_state[state_index].clock_info[0].sclk = le32_to_cpu(power_info->info_3.asPowerPlayInfo[i].ulEngineClock); /* skip invalid modes */ if ((rdev->pm.power_state[state_index].clock_info[0].mclk == 0) || (rdev->pm.power_state[state_index].clock_info[0].sclk == 0)) continue; /* skip overclock modes for now */ if ((rdev->pm.power_state[state_index].clock_info[0].mclk > rdev->clock.default_mclk + RADEON_MODE_OVERCLOCK_MARGIN) || (rdev->pm.power_state[state_index].clock_info[0].sclk > rdev->clock.default_sclk + RADEON_MODE_OVERCLOCK_MARGIN)) continue; rdev->pm.power_state[state_index].non_clock_info.pcie_lanes = power_info->info_3.asPowerPlayInfo[i].ucNumPciELanes; misc = le32_to_cpu(power_info->info_3.asPowerPlayInfo[i].ulMiscInfo); misc2 = le32_to_cpu(power_info->info_3.asPowerPlayInfo[i].ulMiscInfo2); if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_SUPPORT) { rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_GPIO; rdev->pm.power_state[state_index].clock_info[0].voltage.gpio = radeon_lookup_gpio(rdev, power_info->info_3.asPowerPlayInfo[i].ucVoltageDropIndex); if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_ACTIVE_HIGH) rdev->pm.power_state[state_index].clock_info[0].voltage.active_high = true; else rdev->pm.power_state[state_index].clock_info[0].voltage.active_high = false; } else if (misc & ATOM_PM_MISCINFO_PROGRAM_VOLTAGE) { rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_VDDC; rdev->pm.power_state[state_index].clock_info[0].voltage.vddc_id = power_info->info_3.asPowerPlayInfo[i].ucVoltageDropIndex; if (misc2 & ATOM_PM_MISCINFO2_VDDCI_DYNAMIC_VOLTAGE_EN) { rdev->pm.power_state[state_index].clock_info[0].voltage.vddci_enabled = true; rdev->pm.power_state[state_index].clock_info[0].voltage.vddci_id = power_info->info_3.asPowerPlayInfo[i].ucVDDCI_VoltageDropIndex; } } /* order matters! */ if (misc & ATOM_PM_MISCINFO_POWER_SAVING_MODE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_POWERSAVE; if (misc & ATOM_PM_MISCINFO_DEFAULT_DC_STATE_ENTRY_TRUE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BATTERY; if (misc & ATOM_PM_MISCINFO_DEFAULT_LOW_DC_STATE_ENTRY_TRUE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BATTERY; if (misc & ATOM_PM_MISCINFO_LOAD_BALANCE_EN) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BALANCED; if (misc & ATOM_PM_MISCINFO_3D_ACCELERATION_EN) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_PERFORMANCE; if (misc2 & ATOM_PM_MISCINFO2_SYSTEM_AC_LITE_MODE) rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BALANCED; if (misc & ATOM_PM_MISCINFO_DRIVER_DEFAULT_MODE) { rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_DEFAULT; rdev->pm.default_power_state = &rdev->pm.power_state[state_index]; rdev->pm.power_state[state_index].default_clock_mode = &rdev->pm.power_state[state_index].clock_info[0]; } state_index++; break; } } } else if (frev == 4) { /* add the i2c bus for thermal/fan chip */ /* no support for internal controller yet */ if (power_info->info_4.sThermalController.ucType > 0) { if ((power_info->info_4.sThermalController.ucType == ATOM_PP_THERMALCONTROLLER_RV6xx) || (power_info->info_4.sThermalController.ucType == ATOM_PP_THERMALCONTROLLER_RV770)) { DRM_INFO("Internal thermal controller %s fan control\n", (power_info->info_4.sThermalController.ucFanParameters & ATOM_PP_FANPARAMETERS_NOFAN) ? "without" : "with"); } else { DRM_INFO("Possible %s thermal controller at 0x%02x %s fan control\n", pp_lib_thermal_controller_names[power_info->info_4.sThermalController.ucType], power_info->info_4.sThermalController.ucI2cAddress >> 1, (power_info->info_4.sThermalController.ucFanParameters & ATOM_PP_FANPARAMETERS_NOFAN) ? "without" : "with"); i2c_bus = radeon_lookup_i2c_gpio(rdev, power_info->info_4.sThermalController.ucI2cLine); rdev->pm.i2c_bus = radeon_i2c_create(rdev->ddev, &i2c_bus, "Thermal"); } } for (i = 0; i < power_info->info_4.ucNumStates; i++) { mode_index = 0; power_state = (struct _ATOM_PPLIB_STATE *) (mode_info->atom_context->bios + data_offset + le16_to_cpu(power_info->info_4.usStateArrayOffset) + i * power_info->info_4.ucStateEntrySize); non_clock_info = (struct _ATOM_PPLIB_NONCLOCK_INFO *) (mode_info->atom_context->bios + data_offset + le16_to_cpu(power_info->info_4.usNonClockInfoArrayOffset) + (power_state->ucNonClockStateIndex * power_info->info_4.ucNonClockSize)); for (j = 0; j < (power_info->info_4.ucStateEntrySize - 1); j++) { if (rdev->flags & RADEON_IS_IGP) { struct _ATOM_PPLIB_RS780_CLOCK_INFO *clock_info = (struct _ATOM_PPLIB_RS780_CLOCK_INFO *) (mode_info->atom_context->bios + data_offset + le16_to_cpu(power_info->info_4.usClockInfoArrayOffset) + (power_state->ucClockStateIndices[j] * power_info->info_4.ucClockInfoSize)); sclk = le16_to_cpu(clock_info->usLowEngineClockLow); sclk |= clock_info->ucLowEngineClockHigh << 16; rdev->pm.power_state[state_index].clock_info[mode_index].sclk = sclk; /* skip invalid modes */ if (rdev->pm.power_state[state_index].clock_info[mode_index].sclk == 0) continue; /* skip overclock modes for now */ if (rdev->pm.power_state[state_index].clock_info[mode_index].sclk > rdev->clock.default_sclk + RADEON_MODE_OVERCLOCK_MARGIN) continue; rdev->pm.power_state[state_index].clock_info[mode_index].voltage.type = VOLTAGE_SW; rdev->pm.power_state[state_index].clock_info[mode_index].voltage.voltage = clock_info->usVDDC; mode_index++; } else { struct _ATOM_PPLIB_R600_CLOCK_INFO *clock_info = (struct _ATOM_PPLIB_R600_CLOCK_INFO *) (mode_info->atom_context->bios + data_offset + le16_to_cpu(power_info->info_4.usClockInfoArrayOffset) + (power_state->ucClockStateIndices[j] * power_info->info_4.ucClockInfoSize)); sclk = le16_to_cpu(clock_info->usEngineClockLow); sclk |= clock_info->ucEngineClockHigh << 16; mclk = le16_to_cpu(clock_info->usMemoryClockLow); mclk |= clock_info->ucMemoryClockHigh << 16; rdev->pm.power_state[state_index].clock_info[mode_index].mclk = mclk; rdev->pm.power_state[state_index].clock_info[mode_index].sclk = sclk; /* skip invalid modes */ if ((rdev->pm.power_state[state_index].clock_info[mode_index].mclk == 0) || (rdev->pm.power_state[state_index].clock_info[mode_index].sclk == 0)) continue; /* skip overclock modes for now */ if ((rdev->pm.power_state[state_index].clock_info[mode_index].mclk > rdev->clock.default_mclk + RADEON_MODE_OVERCLOCK_MARGIN) || (rdev->pm.power_state[state_index].clock_info[mode_index].sclk > rdev->clock.default_sclk + RADEON_MODE_OVERCLOCK_MARGIN)) continue; rdev->pm.power_state[state_index].clock_info[mode_index].voltage.type = VOLTAGE_SW; rdev->pm.power_state[state_index].clock_info[mode_index].voltage.voltage = clock_info->usVDDC; mode_index++; } } rdev->pm.power_state[state_index].num_clock_modes = mode_index; if (mode_index) { misc = le32_to_cpu(non_clock_info->ulCapsAndSettings); misc2 = le16_to_cpu(non_clock_info->usClassification); rdev->pm.power_state[state_index].non_clock_info.pcie_lanes = ((misc & ATOM_PPLIB_PCIE_LINK_WIDTH_MASK) >> ATOM_PPLIB_PCIE_LINK_WIDTH_SHIFT) + 1; switch (misc2 & ATOM_PPLIB_CLASSIFICATION_UI_MASK) { case ATOM_PPLIB_CLASSIFICATION_UI_BATTERY: rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BATTERY; break; case ATOM_PPLIB_CLASSIFICATION_UI_BALANCED: rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_BALANCED; break; case ATOM_PPLIB_CLASSIFICATION_UI_PERFORMANCE: rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_PERFORMANCE; break; } if (misc2 & ATOM_PPLIB_CLASSIFICATION_BOOT) { rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_DEFAULT; rdev->pm.default_power_state = &rdev->pm.power_state[state_index]; rdev->pm.power_state[state_index].default_clock_mode = &rdev->pm.power_state[state_index].clock_info[mode_index - 1]; } state_index++; } } } } else { /* XXX figure out some good default low power mode for cards w/out power tables */ } if (rdev->pm.default_power_state == NULL) { /* add the default mode */ rdev->pm.power_state[state_index].type = POWER_STATE_TYPE_DEFAULT; rdev->pm.power_state[state_index].num_clock_modes = 1; rdev->pm.power_state[state_index].clock_info[0].mclk = rdev->clock.default_mclk; rdev->pm.power_state[state_index].clock_info[0].sclk = rdev->clock.default_sclk; rdev->pm.power_state[state_index].default_clock_mode = &rdev->pm.power_state[state_index].clock_info[0]; rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_NONE; if (rdev->asic->get_pcie_lanes) rdev->pm.power_state[state_index].non_clock_info.pcie_lanes = radeon_get_pcie_lanes(rdev); else rdev->pm.power_state[state_index].non_clock_info.pcie_lanes = 16; rdev->pm.default_power_state = &rdev->pm.power_state[state_index]; state_index++; } rdev->pm.num_power_states = state_index; rdev->pm.current_power_state = rdev->pm.default_power_state; rdev->pm.current_clock_mode = rdev->pm.default_power_state->default_clock_mode; } void radeon_atom_set_clock_gating(struct radeon_device *rdev, int enable) { DYNAMIC_CLOCK_GATING_PS_ALLOCATION args; int index = GetIndexIntoMasterTable(COMMAND, DynamicClockGating); args.ucEnable = enable; atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args); } uint32_t radeon_atom_get_engine_clock(struct radeon_device *rdev) { GET_ENGINE_CLOCK_PS_ALLOCATION args; int index = GetIndexIntoMasterTable(COMMAND, GetEngineClock); atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args); return args.ulReturnEngineClock; } uint32_t radeon_atom_get_memory_clock(struct radeon_device *rdev) { GET_MEMORY_CLOCK_PS_ALLOCATION args; int index = GetIndexIntoMasterTable(COMMAND, GetMemoryClock); atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args); return args.ulReturnMemoryClock; } void radeon_atom_set_engine_clock(struct radeon_device *rdev, uint32_t eng_clock) { SET_ENGINE_CLOCK_PS_ALLOCATION args; int index = GetIndexIntoMasterTable(COMMAND, SetEngineClock); args.ulTargetEngineClock = eng_clock; /* 10 khz */ atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args); } void radeon_atom_set_memory_clock(struct radeon_device *rdev, uint32_t mem_clock) { SET_MEMORY_CLOCK_PS_ALLOCATION args; int index = GetIndexIntoMasterTable(COMMAND, SetMemoryClock); if (rdev->flags & RADEON_IS_IGP) return; args.ulTargetMemoryClock = mem_clock; /* 10 khz */ atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args); } void radeon_atom_initialize_bios_scratch_regs(struct drm_device *dev) { struct radeon_device *rdev = dev->dev_private; uint32_t bios_2_scratch, bios_6_scratch; if (rdev->family >= CHIP_R600) { bios_2_scratch = RREG32(R600_BIOS_2_SCRATCH); bios_6_scratch = RREG32(R600_BIOS_6_SCRATCH); } else { bios_2_scratch = RREG32(RADEON_BIOS_2_SCRATCH); bios_6_scratch = RREG32(RADEON_BIOS_6_SCRATCH); } /* let the bios control the backlight */ bios_2_scratch &= ~ATOM_S2_VRI_BRIGHT_ENABLE; /* tell the bios not to handle mode switching */ bios_6_scratch |= (ATOM_S6_ACC_BLOCK_DISPLAY_SWITCH | ATOM_S6_ACC_MODE); if (rdev->family >= CHIP_R600) { WREG32(R600_BIOS_2_SCRATCH, bios_2_scratch); WREG32(R600_BIOS_6_SCRATCH, bios_6_scratch); } else { WREG32(RADEON_BIOS_2_SCRATCH, bios_2_scratch); WREG32(RADEON_BIOS_6_SCRATCH, bios_6_scratch); } } void radeon_save_bios_scratch_regs(struct radeon_device *rdev) { uint32_t scratch_reg; int i; if (rdev->family >= CHIP_R600) scratch_reg = R600_BIOS_0_SCRATCH; else scratch_reg = RADEON_BIOS_0_SCRATCH; for (i = 0; i < RADEON_BIOS_NUM_SCRATCH; i++) rdev->bios_scratch[i] = RREG32(scratch_reg + (i * 4)); } void radeon_restore_bios_scratch_regs(struct radeon_device *rdev) { uint32_t scratch_reg; int i; if (rdev->family >= CHIP_R600) scratch_reg = R600_BIOS_0_SCRATCH; else scratch_reg = RADEON_BIOS_0_SCRATCH; for (i = 0; i < RADEON_BIOS_NUM_SCRATCH; i++) WREG32(scratch_reg + (i * 4), rdev->bios_scratch[i]); } void radeon_atom_output_lock(struct drm_encoder *encoder, bool lock) { struct drm_device *dev = encoder->dev; struct radeon_device *rdev = dev->dev_private; uint32_t bios_6_scratch; if (rdev->family >= CHIP_R600) bios_6_scratch = RREG32(R600_BIOS_6_SCRATCH); else bios_6_scratch = RREG32(RADEON_BIOS_6_SCRATCH); if (lock) bios_6_scratch |= ATOM_S6_CRITICAL_STATE; else bios_6_scratch &= ~ATOM_S6_CRITICAL_STATE; if (rdev->family >= CHIP_R600) WREG32(R600_BIOS_6_SCRATCH, bios_6_scratch); else WREG32(RADEON_BIOS_6_SCRATCH, bios_6_scratch); } /* at some point we may want to break this out into individual functions */ void radeon_atombios_connected_scratch_regs(struct drm_connector *connector, struct drm_encoder *encoder, bool connected) { struct drm_device *dev = connector->dev; struct radeon_device *rdev = dev->dev_private; struct radeon_connector *radeon_connector = to_radeon_connector(connector); struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder); uint32_t bios_0_scratch, bios_3_scratch, bios_6_scratch; if (rdev->family >= CHIP_R600) { bios_0_scratch = RREG32(R600_BIOS_0_SCRATCH); bios_3_scratch = RREG32(R600_BIOS_3_SCRATCH); bios_6_scratch = RREG32(R600_BIOS_6_SCRATCH); } else { bios_0_scratch = RREG32(RADEON_BIOS_0_SCRATCH); bios_3_scratch = RREG32(RADEON_BIOS_3_SCRATCH); bios_6_scratch = RREG32(RADEON_BIOS_6_SCRATCH); } if ((radeon_encoder->devices & ATOM_DEVICE_TV1_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_TV1_SUPPORT)) { if (connected) { DRM_DEBUG("TV1 connected\n"); bios_3_scratch |= ATOM_S3_TV1_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_TV1; } else { DRM_DEBUG("TV1 disconnected\n"); bios_0_scratch &= ~ATOM_S0_TV1_MASK; bios_3_scratch &= ~ATOM_S3_TV1_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_TV1; } } if ((radeon_encoder->devices & ATOM_DEVICE_CV_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_CV_SUPPORT)) { if (connected) { DRM_DEBUG("CV connected\n"); bios_3_scratch |= ATOM_S3_CV_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_CV; } else { DRM_DEBUG("CV disconnected\n"); bios_0_scratch &= ~ATOM_S0_CV_MASK; bios_3_scratch &= ~ATOM_S3_CV_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_CV; } } if ((radeon_encoder->devices & ATOM_DEVICE_LCD1_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_LCD1_SUPPORT)) { if (connected) { DRM_DEBUG("LCD1 connected\n"); bios_0_scratch |= ATOM_S0_LCD1; bios_3_scratch |= ATOM_S3_LCD1_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_LCD1; } else { DRM_DEBUG("LCD1 disconnected\n"); bios_0_scratch &= ~ATOM_S0_LCD1; bios_3_scratch &= ~ATOM_S3_LCD1_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_LCD1; } } if ((radeon_encoder->devices & ATOM_DEVICE_CRT1_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_CRT1_SUPPORT)) { if (connected) { DRM_DEBUG("CRT1 connected\n"); bios_0_scratch |= ATOM_S0_CRT1_COLOR; bios_3_scratch |= ATOM_S3_CRT1_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_CRT1; } else { DRM_DEBUG("CRT1 disconnected\n"); bios_0_scratch &= ~ATOM_S0_CRT1_MASK; bios_3_scratch &= ~ATOM_S3_CRT1_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_CRT1; } } if ((radeon_encoder->devices & ATOM_DEVICE_CRT2_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_CRT2_SUPPORT)) { if (connected) { DRM_DEBUG("CRT2 connected\n"); bios_0_scratch |= ATOM_S0_CRT2_COLOR; bios_3_scratch |= ATOM_S3_CRT2_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_CRT2; } else { DRM_DEBUG("CRT2 disconnected\n"); bios_0_scratch &= ~ATOM_S0_CRT2_MASK; bios_3_scratch &= ~ATOM_S3_CRT2_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_CRT2; } } if ((radeon_encoder->devices & ATOM_DEVICE_DFP1_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_DFP1_SUPPORT)) { if (connected) { DRM_DEBUG("DFP1 connected\n"); bios_0_scratch |= ATOM_S0_DFP1; bios_3_scratch |= ATOM_S3_DFP1_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_DFP1; } else { DRM_DEBUG("DFP1 disconnected\n"); bios_0_scratch &= ~ATOM_S0_DFP1; bios_3_scratch &= ~ATOM_S3_DFP1_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP1; } } if ((radeon_encoder->devices & ATOM_DEVICE_DFP2_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_DFP2_SUPPORT)) { if (connected) { DRM_DEBUG("DFP2 connected\n"); bios_0_scratch |= ATOM_S0_DFP2; bios_3_scratch |= ATOM_S3_DFP2_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_DFP2; } else { DRM_DEBUG("DFP2 disconnected\n"); bios_0_scratch &= ~ATOM_S0_DFP2; bios_3_scratch &= ~ATOM_S3_DFP2_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP2; } } if ((radeon_encoder->devices & ATOM_DEVICE_DFP3_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_DFP3_SUPPORT)) { if (connected) { DRM_DEBUG("DFP3 connected\n"); bios_0_scratch |= ATOM_S0_DFP3; bios_3_scratch |= ATOM_S3_DFP3_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_DFP3; } else { DRM_DEBUG("DFP3 disconnected\n"); bios_0_scratch &= ~ATOM_S0_DFP3; bios_3_scratch &= ~ATOM_S3_DFP3_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP3; } } if ((radeon_encoder->devices & ATOM_DEVICE_DFP4_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_DFP4_SUPPORT)) { if (connected) { DRM_DEBUG("DFP4 connected\n"); bios_0_scratch |= ATOM_S0_DFP4; bios_3_scratch |= ATOM_S3_DFP4_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_DFP4; } else { DRM_DEBUG("DFP4 disconnected\n"); bios_0_scratch &= ~ATOM_S0_DFP4; bios_3_scratch &= ~ATOM_S3_DFP4_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP4; } } if ((radeon_encoder->devices & ATOM_DEVICE_DFP5_SUPPORT) && (radeon_connector->devices & ATOM_DEVICE_DFP5_SUPPORT)) { if (connected) { DRM_DEBUG("DFP5 connected\n"); bios_0_scratch |= ATOM_S0_DFP5; bios_3_scratch |= ATOM_S3_DFP5_ACTIVE; bios_6_scratch |= ATOM_S6_ACC_REQ_DFP5; } else { DRM_DEBUG("DFP5 disconnected\n"); bios_0_scratch &= ~ATOM_S0_DFP5; bios_3_scratch &= ~ATOM_S3_DFP5_ACTIVE; bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP5; } } if (rdev->family >= CHIP_R600) { WREG32(R600_BIOS_0_SCRATCH, bios_0_scratch); WREG32(R600_BIOS_3_SCRATCH, bios_3_scratch); WREG32(R600_BIOS_6_SCRATCH, bios_6_scratch); } else { WREG32(RADEON_BIOS_0_SCRATCH, bios_0_scratch); WREG32(RADEON_BIOS_3_SCRATCH, bios_3_scratch); WREG32(RADEON_BIOS_6_SCRATCH, bios_6_scratch); } } void radeon_atombios_encoder_crtc_scratch_regs(struct drm_encoder *encoder, int crtc) { struct drm_device *dev = encoder->dev; struct radeon_device *rdev = dev->dev_private; struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder); uint32_t bios_3_scratch; if (rdev->family >= CHIP_R600) bios_3_scratch = RREG32(R600_BIOS_3_SCRATCH); else bios_3_scratch = RREG32(RADEON_BIOS_3_SCRATCH); if (radeon_encoder->devices & ATOM_DEVICE_TV1_SUPPORT) { bios_3_scratch &= ~ATOM_S3_TV1_CRTC_ACTIVE; bios_3_scratch |= (crtc << 18); } if (radeon_encoder->devices & ATOM_DEVICE_CV_SUPPORT) { bios_3_scratch &= ~ATOM_S3_CV_CRTC_ACTIVE; bios_3_scratch |= (crtc << 24); } if (radeon_encoder->devices & ATOM_DEVICE_CRT1_SUPPORT) { bios_3_scratch &= ~ATOM_S3_CRT1_CRTC_ACTIVE; bios_3_scratch |= (crtc << 16); } if (radeon_encoder->devices & ATOM_DEVICE_CRT2_SUPPORT) { bios_3_scratch &= ~ATOM_S3_CRT2_CRTC_ACTIVE; bios_3_scratch |= (crtc << 20); } if (radeon_encoder->devices & ATOM_DEVICE_LCD1_SUPPORT) { bios_3_scratch &= ~ATOM_S3_LCD1_CRTC_ACTIVE; bios_3_scratch |= (crtc << 17); } if (radeon_encoder->devices & ATOM_DEVICE_DFP1_SUPPORT) { bios_3_scratch &= ~ATOM_S3_DFP1_CRTC_ACTIVE; bios_3_scratch |= (crtc << 19); } if (radeon_encoder->devices & ATOM_DEVICE_DFP2_SUPPORT) { bios_3_scratch &= ~ATOM_S3_DFP2_CRTC_ACTIVE; bios_3_scratch |= (crtc << 23); } if (radeon_encoder->devices & ATOM_DEVICE_DFP3_SUPPORT) { bios_3_scratch &= ~ATOM_S3_DFP3_CRTC_ACTIVE; bios_3_scratch |= (crtc << 25); } if (rdev->family >= CHIP_R600) WREG32(R600_BIOS_3_SCRATCH, bios_3_scratch); else WREG32(RADEON_BIOS_3_SCRATCH, bios_3_scratch); } void radeon_atombios_encoder_dpms_scratch_regs(struct drm_encoder *encoder, bool on) { struct drm_device *dev = encoder->dev; struct radeon_device *rdev = dev->dev_private; struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder); uint32_t bios_2_scratch; if (rdev->family >= CHIP_R600) bios_2_scratch = RREG32(R600_BIOS_2_SCRATCH); else bios_2_scratch = RREG32(RADEON_BIOS_2_SCRATCH); if (radeon_encoder->devices & ATOM_DEVICE_TV1_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_TV1_DPMS_STATE; else bios_2_scratch |= ATOM_S2_TV1_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_CV_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_CV_DPMS_STATE; else bios_2_scratch |= ATOM_S2_CV_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_CRT1_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_CRT1_DPMS_STATE; else bios_2_scratch |= ATOM_S2_CRT1_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_CRT2_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_CRT2_DPMS_STATE; else bios_2_scratch |= ATOM_S2_CRT2_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_LCD1_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_LCD1_DPMS_STATE; else bios_2_scratch |= ATOM_S2_LCD1_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_DFP1_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_DFP1_DPMS_STATE; else bios_2_scratch |= ATOM_S2_DFP1_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_DFP2_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_DFP2_DPMS_STATE; else bios_2_scratch |= ATOM_S2_DFP2_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_DFP3_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_DFP3_DPMS_STATE; else bios_2_scratch |= ATOM_S2_DFP3_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_DFP4_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_DFP4_DPMS_STATE; else bios_2_scratch |= ATOM_S2_DFP4_DPMS_STATE; } if (radeon_encoder->devices & ATOM_DEVICE_DFP5_SUPPORT) { if (on) bios_2_scratch &= ~ATOM_S2_DFP5_DPMS_STATE; else bios_2_scratch |= ATOM_S2_DFP5_DPMS_STATE; } if (rdev->family >= CHIP_R600) WREG32(R600_BIOS_2_SCRATCH, bios_2_scratch); else WREG32(RADEON_BIOS_2_SCRATCH, bios_2_scratch); }
./CrossVul/dataset_final_sorted/CWE-193/c/bad_4732_1
crossvul-cpp_data_bad_2801_0
/*- * Copyright (c) 2003-2007 Tim Kientzle * Copyright (c) 2011 Andres Mejia * 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(S) ``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(S) 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 "archive_platform.h" #ifdef HAVE_ERRNO_H #include <errno.h> #endif #include <time.h> #include <limits.h> #ifdef HAVE_ZLIB_H #include <zlib.h> /* crc32 */ #endif #include "archive.h" #ifndef HAVE_ZLIB_H #include "archive_crc32.h" #endif #include "archive_endian.h" #include "archive_entry.h" #include "archive_entry_locale.h" #include "archive_ppmd7_private.h" #include "archive_private.h" #include "archive_read_private.h" /* RAR signature, also known as the mark header */ #define RAR_SIGNATURE "\x52\x61\x72\x21\x1A\x07\x00" /* Header types */ #define MARK_HEAD 0x72 #define MAIN_HEAD 0x73 #define FILE_HEAD 0x74 #define COMM_HEAD 0x75 #define AV_HEAD 0x76 #define SUB_HEAD 0x77 #define PROTECT_HEAD 0x78 #define SIGN_HEAD 0x79 #define NEWSUB_HEAD 0x7a #define ENDARC_HEAD 0x7b /* Main Header Flags */ #define MHD_VOLUME 0x0001 #define MHD_COMMENT 0x0002 #define MHD_LOCK 0x0004 #define MHD_SOLID 0x0008 #define MHD_NEWNUMBERING 0x0010 #define MHD_AV 0x0020 #define MHD_PROTECT 0x0040 #define MHD_PASSWORD 0x0080 #define MHD_FIRSTVOLUME 0x0100 #define MHD_ENCRYPTVER 0x0200 /* Flags common to all headers */ #define HD_MARKDELETION 0x4000 #define HD_ADD_SIZE_PRESENT 0x8000 /* File Header Flags */ #define FHD_SPLIT_BEFORE 0x0001 #define FHD_SPLIT_AFTER 0x0002 #define FHD_PASSWORD 0x0004 #define FHD_COMMENT 0x0008 #define FHD_SOLID 0x0010 #define FHD_LARGE 0x0100 #define FHD_UNICODE 0x0200 #define FHD_SALT 0x0400 #define FHD_VERSION 0x0800 #define FHD_EXTTIME 0x1000 #define FHD_EXTFLAGS 0x2000 /* File dictionary sizes */ #define DICTIONARY_SIZE_64 0x00 #define DICTIONARY_SIZE_128 0x20 #define DICTIONARY_SIZE_256 0x40 #define DICTIONARY_SIZE_512 0x60 #define DICTIONARY_SIZE_1024 0x80 #define DICTIONARY_SIZE_2048 0xA0 #define DICTIONARY_SIZE_4096 0xC0 #define FILE_IS_DIRECTORY 0xE0 #define DICTIONARY_MASK FILE_IS_DIRECTORY /* OS Flags */ #define OS_MSDOS 0 #define OS_OS2 1 #define OS_WIN32 2 #define OS_UNIX 3 #define OS_MAC_OS 4 #define OS_BEOS 5 /* Compression Methods */ #define COMPRESS_METHOD_STORE 0x30 /* LZSS */ #define COMPRESS_METHOD_FASTEST 0x31 #define COMPRESS_METHOD_FAST 0x32 #define COMPRESS_METHOD_NORMAL 0x33 /* PPMd Variant H */ #define COMPRESS_METHOD_GOOD 0x34 #define COMPRESS_METHOD_BEST 0x35 #define CRC_POLYNOMIAL 0xEDB88320 #define NS_UNIT 10000000 #define DICTIONARY_MAX_SIZE 0x400000 #define MAINCODE_SIZE 299 #define OFFSETCODE_SIZE 60 #define LOWOFFSETCODE_SIZE 17 #define LENGTHCODE_SIZE 28 #define HUFFMAN_TABLE_SIZE \ MAINCODE_SIZE + OFFSETCODE_SIZE + LOWOFFSETCODE_SIZE + LENGTHCODE_SIZE #define MAX_SYMBOL_LENGTH 0xF #define MAX_SYMBOLS 20 /* * Considering L1,L2 cache miss and a calling of write system-call, * the best size of the output buffer(uncompressed buffer) is 128K. * If the structure of extracting process is changed, this value * might be researched again. */ #define UNP_BUFFER_SIZE (128 * 1024) /* Define this here for non-Windows platforms */ #if !((defined(__WIN32__) || defined(_WIN32) || defined(__WIN32)) && !defined(__CYGWIN__)) #define FILE_ATTRIBUTE_DIRECTORY 0x10 #endif /* Fields common to all headers */ struct rar_header { char crc[2]; char type; char flags[2]; char size[2]; }; /* Fields common to all file headers */ struct rar_file_header { char pack_size[4]; char unp_size[4]; char host_os; char file_crc[4]; char file_time[4]; char unp_ver; char method; char name_size[2]; char file_attr[4]; }; struct huffman_tree_node { int branches[2]; }; struct huffman_table_entry { unsigned int length; int value; }; struct huffman_code { struct huffman_tree_node *tree; int numentries; int numallocatedentries; int minlength; int maxlength; int tablesize; struct huffman_table_entry *table; }; struct lzss { unsigned char *window; int mask; int64_t position; }; struct data_block_offsets { int64_t header_size; int64_t start_offset; int64_t end_offset; }; struct rar { /* Entries from main RAR header */ unsigned main_flags; unsigned long file_crc; char reserved1[2]; char reserved2[4]; char encryptver; /* File header entries */ char compression_method; unsigned file_flags; int64_t packed_size; int64_t unp_size; time_t mtime; long mnsec; mode_t mode; char *filename; char *filename_save; size_t filename_save_size; size_t filename_allocated; /* File header optional entries */ char salt[8]; time_t atime; long ansec; time_t ctime; long cnsec; time_t arctime; long arcnsec; /* Fields to help with tracking decompression of files. */ int64_t bytes_unconsumed; int64_t bytes_remaining; int64_t bytes_uncopied; int64_t offset; int64_t offset_outgoing; int64_t offset_seek; char valid; unsigned int unp_offset; unsigned int unp_buffer_size; unsigned char *unp_buffer; unsigned int dictionary_size; char start_new_block; char entry_eof; unsigned long crc_calculated; int found_first_header; char has_endarc_header; struct data_block_offsets *dbo; unsigned int cursor; unsigned int nodes; /* LZSS members */ struct huffman_code maincode; struct huffman_code offsetcode; struct huffman_code lowoffsetcode; struct huffman_code lengthcode; unsigned char lengthtable[HUFFMAN_TABLE_SIZE]; struct lzss lzss; char output_last_match; unsigned int lastlength; unsigned int lastoffset; unsigned int oldoffset[4]; unsigned int lastlowoffset; unsigned int numlowoffsetrepeats; int64_t filterstart; char start_new_table; /* PPMd Variant H members */ char ppmd_valid; char ppmd_eod; char is_ppmd_block; int ppmd_escape; CPpmd7 ppmd7_context; CPpmd7z_RangeDec range_dec; IByteIn bytein; /* * String conversion object. */ int init_default_conversion; struct archive_string_conv *sconv_default; struct archive_string_conv *opt_sconv; struct archive_string_conv *sconv_utf8; struct archive_string_conv *sconv_utf16be; /* * Bit stream reader. */ struct rar_br { #define CACHE_TYPE uint64_t #define CACHE_BITS (8 * sizeof(CACHE_TYPE)) /* Cache buffer. */ CACHE_TYPE cache_buffer; /* Indicates how many bits avail in cache_buffer. */ int cache_avail; ssize_t avail_in; const unsigned char *next_in; } br; /* * Custom field to denote that this archive contains encrypted entries */ int has_encrypted_entries; }; static int archive_read_support_format_rar_capabilities(struct archive_read *); static int archive_read_format_rar_has_encrypted_entries(struct archive_read *); static int archive_read_format_rar_bid(struct archive_read *, int); static int archive_read_format_rar_options(struct archive_read *, const char *, const char *); static int archive_read_format_rar_read_header(struct archive_read *, struct archive_entry *); static int archive_read_format_rar_read_data(struct archive_read *, const void **, size_t *, int64_t *); static int archive_read_format_rar_read_data_skip(struct archive_read *a); static int64_t archive_read_format_rar_seek_data(struct archive_read *, int64_t, int); static int archive_read_format_rar_cleanup(struct archive_read *); /* Support functions */ static int read_header(struct archive_read *, struct archive_entry *, char); static time_t get_time(int); static int read_exttime(const char *, struct rar *, const char *); static int read_symlink_stored(struct archive_read *, struct archive_entry *, struct archive_string_conv *); static int read_data_stored(struct archive_read *, const void **, size_t *, int64_t *); static int read_data_compressed(struct archive_read *, const void **, size_t *, int64_t *); static int rar_br_preparation(struct archive_read *, struct rar_br *); static int parse_codes(struct archive_read *); static void free_codes(struct archive_read *); static int read_next_symbol(struct archive_read *, struct huffman_code *); static int create_code(struct archive_read *, struct huffman_code *, unsigned char *, int, char); static int add_value(struct archive_read *, struct huffman_code *, int, int, int); static int new_node(struct huffman_code *); static int make_table(struct archive_read *, struct huffman_code *); static int make_table_recurse(struct archive_read *, struct huffman_code *, int, struct huffman_table_entry *, int, int); static int64_t expand(struct archive_read *, int64_t); static int copy_from_lzss_window(struct archive_read *, const void **, int64_t, int); static const void *rar_read_ahead(struct archive_read *, size_t, ssize_t *); /* * Bit stream reader. */ /* Check that the cache buffer has enough bits. */ #define rar_br_has(br, n) ((br)->cache_avail >= n) /* Get compressed data by bit. */ #define rar_br_bits(br, n) \ (((uint32_t)((br)->cache_buffer >> \ ((br)->cache_avail - (n)))) & cache_masks[n]) #define rar_br_bits_forced(br, n) \ (((uint32_t)((br)->cache_buffer << \ ((n) - (br)->cache_avail))) & cache_masks[n]) /* Read ahead to make sure the cache buffer has enough compressed data we * will use. * True : completed, there is enough data in the cache buffer. * False : there is no data in the stream. */ #define rar_br_read_ahead(a, br, n) \ ((rar_br_has(br, (n)) || rar_br_fillup(a, br)) || rar_br_has(br, (n))) /* Notify how many bits we consumed. */ #define rar_br_consume(br, n) ((br)->cache_avail -= (n)) #define rar_br_consume_unalined_bits(br) ((br)->cache_avail &= ~7) static const uint32_t cache_masks[] = { 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF, 0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF, 0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }; /* * Shift away used bits in the cache data and fill it up with following bits. * Call this when cache buffer does not have enough bits you need. * * Returns 1 if the cache buffer is full. * Returns 0 if the cache buffer is not full; input buffer is empty. */ static int rar_br_fillup(struct archive_read *a, struct rar_br *br) { struct rar *rar = (struct rar *)(a->format->data); int n = CACHE_BITS - br->cache_avail; for (;;) { switch (n >> 3) { case 8: if (br->avail_in >= 8) { br->cache_buffer = ((uint64_t)br->next_in[0]) << 56 | ((uint64_t)br->next_in[1]) << 48 | ((uint64_t)br->next_in[2]) << 40 | ((uint64_t)br->next_in[3]) << 32 | ((uint32_t)br->next_in[4]) << 24 | ((uint32_t)br->next_in[5]) << 16 | ((uint32_t)br->next_in[6]) << 8 | (uint32_t)br->next_in[7]; br->next_in += 8; br->avail_in -= 8; br->cache_avail += 8 * 8; rar->bytes_unconsumed += 8; rar->bytes_remaining -= 8; return (1); } break; case 7: if (br->avail_in >= 7) { br->cache_buffer = (br->cache_buffer << 56) | ((uint64_t)br->next_in[0]) << 48 | ((uint64_t)br->next_in[1]) << 40 | ((uint64_t)br->next_in[2]) << 32 | ((uint32_t)br->next_in[3]) << 24 | ((uint32_t)br->next_in[4]) << 16 | ((uint32_t)br->next_in[5]) << 8 | (uint32_t)br->next_in[6]; br->next_in += 7; br->avail_in -= 7; br->cache_avail += 7 * 8; rar->bytes_unconsumed += 7; rar->bytes_remaining -= 7; return (1); } break; case 6: if (br->avail_in >= 6) { br->cache_buffer = (br->cache_buffer << 48) | ((uint64_t)br->next_in[0]) << 40 | ((uint64_t)br->next_in[1]) << 32 | ((uint32_t)br->next_in[2]) << 24 | ((uint32_t)br->next_in[3]) << 16 | ((uint32_t)br->next_in[4]) << 8 | (uint32_t)br->next_in[5]; br->next_in += 6; br->avail_in -= 6; br->cache_avail += 6 * 8; rar->bytes_unconsumed += 6; rar->bytes_remaining -= 6; return (1); } break; case 0: /* We have enough compressed data in * the cache buffer.*/ return (1); default: break; } if (br->avail_in <= 0) { if (rar->bytes_unconsumed > 0) { /* Consume as much as the decompressor * actually used. */ __archive_read_consume(a, rar->bytes_unconsumed); rar->bytes_unconsumed = 0; } br->next_in = rar_read_ahead(a, 1, &(br->avail_in)); if (br->next_in == NULL) return (0); if (br->avail_in == 0) return (0); } br->cache_buffer = (br->cache_buffer << 8) | *br->next_in++; br->avail_in--; br->cache_avail += 8; n -= 8; rar->bytes_unconsumed++; rar->bytes_remaining--; } } static int rar_br_preparation(struct archive_read *a, struct rar_br *br) { struct rar *rar = (struct rar *)(a->format->data); if (rar->bytes_remaining > 0) { br->next_in = rar_read_ahead(a, 1, &(br->avail_in)); if (br->next_in == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); return (ARCHIVE_FATAL); } if (br->cache_avail == 0) (void)rar_br_fillup(a, br); } return (ARCHIVE_OK); } /* Find last bit set */ static inline int rar_fls(unsigned int word) { word |= (word >> 1); word |= (word >> 2); word |= (word >> 4); word |= (word >> 8); word |= (word >> 16); return word - (word >> 1); } /* LZSS functions */ static inline int64_t lzss_position(struct lzss *lzss) { return lzss->position; } static inline int lzss_mask(struct lzss *lzss) { return lzss->mask; } static inline int lzss_size(struct lzss *lzss) { return lzss->mask + 1; } static inline int lzss_offset_for_position(struct lzss *lzss, int64_t pos) { return (int)(pos & lzss->mask); } static inline unsigned char * lzss_pointer_for_position(struct lzss *lzss, int64_t pos) { return &lzss->window[lzss_offset_for_position(lzss, pos)]; } static inline int lzss_current_offset(struct lzss *lzss) { return lzss_offset_for_position(lzss, lzss->position); } static inline uint8_t * lzss_current_pointer(struct lzss *lzss) { return lzss_pointer_for_position(lzss, lzss->position); } static inline void lzss_emit_literal(struct rar *rar, uint8_t literal) { *lzss_current_pointer(&rar->lzss) = literal; rar->lzss.position++; } static inline void lzss_emit_match(struct rar *rar, int offset, int length) { int dstoffs = lzss_current_offset(&rar->lzss); int srcoffs = (dstoffs - offset) & lzss_mask(&rar->lzss); int l, li, remaining; unsigned char *d, *s; remaining = length; while (remaining > 0) { l = remaining; if (dstoffs > srcoffs) { if (l > lzss_size(&rar->lzss) - dstoffs) l = lzss_size(&rar->lzss) - dstoffs; } else { if (l > lzss_size(&rar->lzss) - srcoffs) l = lzss_size(&rar->lzss) - srcoffs; } d = &(rar->lzss.window[dstoffs]); s = &(rar->lzss.window[srcoffs]); if ((dstoffs + l < srcoffs) || (srcoffs + l < dstoffs)) memcpy(d, s, l); else { for (li = 0; li < l; li++) d[li] = s[li]; } remaining -= l; dstoffs = (dstoffs + l) & lzss_mask(&(rar->lzss)); srcoffs = (srcoffs + l) & lzss_mask(&(rar->lzss)); } rar->lzss.position += length; } static void * ppmd_alloc(void *p, size_t size) { (void)p; return malloc(size); } static void ppmd_free(void *p, void *address) { (void)p; free(address); } static ISzAlloc g_szalloc = { ppmd_alloc, ppmd_free }; static Byte ppmd_read(void *p) { struct archive_read *a = ((IByteIn*)p)->a; struct rar *rar = (struct rar *)(a->format->data); struct rar_br *br = &(rar->br); Byte b; if (!rar_br_read_ahead(a, br, 8)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return 0; } b = rar_br_bits(br, 8); rar_br_consume(br, 8); return b; } int archive_read_support_format_rar(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; struct rar *rar; int r; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_support_format_rar"); rar = (struct rar *)calloc(sizeof(*rar), 1); if (rar == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate rar data"); return (ARCHIVE_FATAL); } /* * Until enough data has been read, we cannot tell about * any encrypted entries yet. */ rar->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; r = __archive_read_register_format(a, rar, "rar", archive_read_format_rar_bid, archive_read_format_rar_options, archive_read_format_rar_read_header, archive_read_format_rar_read_data, archive_read_format_rar_read_data_skip, archive_read_format_rar_seek_data, archive_read_format_rar_cleanup, archive_read_support_format_rar_capabilities, archive_read_format_rar_has_encrypted_entries); if (r != ARCHIVE_OK) free(rar); return (r); } static int archive_read_support_format_rar_capabilities(struct archive_read * a) { (void)a; /* UNUSED */ return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA | ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA); } static int archive_read_format_rar_has_encrypted_entries(struct archive_read *_a) { if (_a && _a->format) { struct rar * rar = (struct rar *)_a->format->data; if (rar) { return rar->has_encrypted_entries; } } return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; } static int archive_read_format_rar_bid(struct archive_read *a, int best_bid) { const char *p; /* If there's already a bid > 30, we'll never win. */ if (best_bid > 30) return (-1); if ((p = __archive_read_ahead(a, 7, NULL)) == NULL) return (-1); if (memcmp(p, RAR_SIGNATURE, 7) == 0) return (30); if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) { /* This is a PE file */ ssize_t offset = 0x10000; ssize_t window = 4096; ssize_t bytes_avail; while (offset + window <= (1024 * 128)) { const char *buff = __archive_read_ahead(a, offset + window, &bytes_avail); if (buff == NULL) { /* Remaining bytes are less than window. */ window >>= 1; if (window < 0x40) return (0); continue; } p = buff + offset; while (p + 7 < buff + bytes_avail) { if (memcmp(p, RAR_SIGNATURE, 7) == 0) return (30); p += 0x10; } offset = p - buff; } } return (0); } static int skip_sfx(struct archive_read *a) { const void *h; const char *p, *q; size_t skip, total; ssize_t bytes, window; total = 0; window = 4096; while (total + window <= (1024 * 128)) { h = __archive_read_ahead(a, window, &bytes); if (h == NULL) { /* Remaining bytes are less than window. */ window >>= 1; if (window < 0x40) goto fatal; continue; } if (bytes < 0x40) goto fatal; p = h; q = p + bytes; /* * Scan ahead until we find something that looks * like the RAR header. */ while (p + 7 < q) { if (memcmp(p, RAR_SIGNATURE, 7) == 0) { skip = p - (const char *)h; __archive_read_consume(a, skip); return (ARCHIVE_OK); } p += 0x10; } skip = p - (const char *)h; __archive_read_consume(a, skip); total += skip; } fatal: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Couldn't find out RAR header"); return (ARCHIVE_FATAL); } static int archive_read_format_rar_options(struct archive_read *a, const char *key, const char *val) { struct rar *rar; int ret = ARCHIVE_FAILED; rar = (struct rar *)(a->format->data); if (strcmp(key, "hdrcharset") == 0) { if (val == NULL || val[0] == 0) archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "rar: hdrcharset option needs a character-set name"); else { rar->opt_sconv = archive_string_conversion_from_charset( &a->archive, val, 0); if (rar->opt_sconv != NULL) ret = ARCHIVE_OK; else ret = ARCHIVE_FATAL; } return (ret); } /* Note: The "warn" return is just to inform the options * supervisor that we didn't handle it. It will generate * a suitable error if no one used this option. */ return (ARCHIVE_WARN); } static int archive_read_format_rar_read_header(struct archive_read *a, struct archive_entry *entry) { const void *h; const char *p; struct rar *rar; size_t skip; char head_type; int ret; unsigned flags; unsigned long crc32_expected; a->archive.archive_format = ARCHIVE_FORMAT_RAR; if (a->archive.archive_format_name == NULL) a->archive.archive_format_name = "RAR"; rar = (struct rar *)(a->format->data); /* * It should be sufficient to call archive_read_next_header() for * a reader to determine if an entry is encrypted or not. If the * encryption of an entry is only detectable when calling * archive_read_data(), so be it. We'll do the same check there * as well. */ if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { rar->has_encrypted_entries = 0; } /* RAR files can be generated without EOF headers, so return ARCHIVE_EOF if * this fails. */ if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_EOF); p = h; if (rar->found_first_header == 0 && ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0)) { /* This is an executable ? Must be self-extracting... */ ret = skip_sfx(a); if (ret < ARCHIVE_WARN) return (ret); } rar->found_first_header = 1; while (1) { unsigned long crc32_val; if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; head_type = p[2]; switch(head_type) { case MARK_HEAD: if (memcmp(p, RAR_SIGNATURE, 7) != 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid marker header"); return (ARCHIVE_FATAL); } __archive_read_consume(a, 7); break; case MAIN_HEAD: rar->main_flags = archive_le16dec(p + 3); skip = archive_le16dec(p + 5); if (skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, skip, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; memcpy(rar->reserved1, p + 7, sizeof(rar->reserved1)); memcpy(rar->reserved2, p + 7 + sizeof(rar->reserved1), sizeof(rar->reserved2)); if (rar->main_flags & MHD_ENCRYPTVER) { if (skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)+1) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } rar->encryptver = *(p + 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)); } /* Main header is password encrypted, so we cannot read any file names or any other info about files from the header. */ if (rar->main_flags & MHD_PASSWORD) { archive_entry_set_is_metadata_encrypted(entry, 1); archive_entry_set_is_data_encrypted(entry, 1); rar->has_encrypted_entries = 1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR encryption support unavailable."); return (ARCHIVE_FATAL); } crc32_val = crc32(0, (const unsigned char *)p + 2, (unsigned)skip - 2); if ((crc32_val & 0xffff) != archive_le16dec(p)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } __archive_read_consume(a, skip); break; case FILE_HEAD: return read_header(a, entry, head_type); case COMM_HEAD: case AV_HEAD: case SUB_HEAD: case PROTECT_HEAD: case SIGN_HEAD: case ENDARC_HEAD: flags = archive_le16dec(p + 3); skip = archive_le16dec(p + 5); if (skip < 7) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size too small"); return (ARCHIVE_FATAL); } if (flags & HD_ADD_SIZE_PRESENT) { if (skip < 7 + 4) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size too small"); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, skip, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; skip += archive_le32dec(p + 7); } /* Skip over the 2-byte CRC at the beginning of the header. */ crc32_expected = archive_le16dec(p); __archive_read_consume(a, 2); skip -= 2; /* Skim the entire header and compute the CRC. */ crc32_val = 0; while (skip > 0) { size_t to_read = skip; ssize_t did_read; if (to_read > 32 * 1024) { to_read = 32 * 1024; } if ((h = __archive_read_ahead(a, to_read, &did_read)) == NULL) { return (ARCHIVE_FATAL); } p = h; crc32_val = crc32(crc32_val, (const unsigned char *)p, (unsigned)did_read); __archive_read_consume(a, did_read); skip -= did_read; } if ((crc32_val & 0xffff) != crc32_expected) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } if (head_type == ENDARC_HEAD) return (ARCHIVE_EOF); break; case NEWSUB_HEAD: if ((ret = read_header(a, entry, head_type)) < ARCHIVE_WARN) return ret; break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file"); return (ARCHIVE_FATAL); } } } static int archive_read_format_rar_read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct rar *rar = (struct rar *)(a->format->data); int ret; if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { rar->has_encrypted_entries = 0; } if (rar->bytes_unconsumed > 0) { /* Consume as much as the decompressor actually used. */ __archive_read_consume(a, rar->bytes_unconsumed); rar->bytes_unconsumed = 0; } *buff = NULL; if (rar->entry_eof || rar->offset_seek >= rar->unp_size) { *size = 0; *offset = rar->offset; if (*offset < rar->unp_size) *offset = rar->unp_size; return (ARCHIVE_EOF); } switch (rar->compression_method) { case COMPRESS_METHOD_STORE: ret = read_data_stored(a, buff, size, offset); break; case COMPRESS_METHOD_FASTEST: case COMPRESS_METHOD_FAST: case COMPRESS_METHOD_NORMAL: case COMPRESS_METHOD_GOOD: case COMPRESS_METHOD_BEST: ret = read_data_compressed(a, buff, size, offset); if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN) __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unsupported compression method for RAR file."); ret = ARCHIVE_FATAL; break; } return (ret); } static int archive_read_format_rar_read_data_skip(struct archive_read *a) { struct rar *rar; int64_t bytes_skipped; int ret; rar = (struct rar *)(a->format->data); if (rar->bytes_unconsumed > 0) { /* Consume as much as the decompressor actually used. */ __archive_read_consume(a, rar->bytes_unconsumed); rar->bytes_unconsumed = 0; } if (rar->bytes_remaining > 0) { bytes_skipped = __archive_read_consume(a, rar->bytes_remaining); if (bytes_skipped < 0) return (ARCHIVE_FATAL); } /* Compressed data to skip must be read from each header in a multivolume * archive. */ if (rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER) { ret = archive_read_format_rar_read_header(a, a->entry); if (ret == (ARCHIVE_EOF)) ret = archive_read_format_rar_read_header(a, a->entry); if (ret != (ARCHIVE_OK)) return ret; return archive_read_format_rar_read_data_skip(a); } return (ARCHIVE_OK); } static int64_t archive_read_format_rar_seek_data(struct archive_read *a, int64_t offset, int whence) { int64_t client_offset, ret; unsigned int i; struct rar *rar = (struct rar *)(a->format->data); if (rar->compression_method == COMPRESS_METHOD_STORE) { /* Modify the offset for use with SEEK_SET */ switch (whence) { case SEEK_CUR: client_offset = rar->offset_seek; break; case SEEK_END: client_offset = rar->unp_size; break; case SEEK_SET: default: client_offset = 0; } client_offset += offset; if (client_offset < 0) { /* Can't seek past beginning of data block */ return -1; } else if (client_offset > rar->unp_size) { /* * Set the returned offset but only seek to the end of * the data block. */ rar->offset_seek = client_offset; client_offset = rar->unp_size; } client_offset += rar->dbo[0].start_offset; i = 0; while (i < rar->cursor) { i++; client_offset += rar->dbo[i].start_offset - rar->dbo[i-1].end_offset; } if (rar->main_flags & MHD_VOLUME) { /* Find the appropriate offset among the multivolume archive */ while (1) { if (client_offset < rar->dbo[rar->cursor].start_offset && rar->file_flags & FHD_SPLIT_BEFORE) { /* Search backwards for the correct data block */ if (rar->cursor == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Attempt to seek past beginning of RAR data block"); return (ARCHIVE_FAILED); } rar->cursor--; client_offset -= rar->dbo[rar->cursor+1].start_offset - rar->dbo[rar->cursor].end_offset; if (client_offset < rar->dbo[rar->cursor].start_offset) continue; ret = __archive_read_seek(a, rar->dbo[rar->cursor].start_offset - rar->dbo[rar->cursor].header_size, SEEK_SET); if (ret < (ARCHIVE_OK)) return ret; ret = archive_read_format_rar_read_header(a, a->entry); if (ret != (ARCHIVE_OK)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Error during seek of RAR file"); return (ARCHIVE_FAILED); } rar->cursor--; break; } else if (client_offset > rar->dbo[rar->cursor].end_offset && rar->file_flags & FHD_SPLIT_AFTER) { /* Search forward for the correct data block */ rar->cursor++; if (rar->cursor < rar->nodes && client_offset > rar->dbo[rar->cursor].end_offset) { client_offset += rar->dbo[rar->cursor].start_offset - rar->dbo[rar->cursor-1].end_offset; continue; } rar->cursor--; ret = __archive_read_seek(a, rar->dbo[rar->cursor].end_offset, SEEK_SET); if (ret < (ARCHIVE_OK)) return ret; ret = archive_read_format_rar_read_header(a, a->entry); if (ret == (ARCHIVE_EOF)) { rar->has_endarc_header = 1; ret = archive_read_format_rar_read_header(a, a->entry); } if (ret != (ARCHIVE_OK)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Error during seek of RAR file"); return (ARCHIVE_FAILED); } client_offset += rar->dbo[rar->cursor].start_offset - rar->dbo[rar->cursor-1].end_offset; continue; } break; } } ret = __archive_read_seek(a, client_offset, SEEK_SET); if (ret < (ARCHIVE_OK)) return ret; rar->bytes_remaining = rar->dbo[rar->cursor].end_offset - ret; i = rar->cursor; while (i > 0) { i--; ret -= rar->dbo[i+1].start_offset - rar->dbo[i].end_offset; } ret -= rar->dbo[0].start_offset; /* Always restart reading the file after a seek */ __archive_reset_read_data(&a->archive); rar->bytes_unconsumed = 0; rar->offset = 0; /* * If a seek past the end of file was requested, return the requested * offset. */ if (ret == rar->unp_size && rar->offset_seek > rar->unp_size) return rar->offset_seek; /* Return the new offset */ rar->offset_seek = ret; return rar->offset_seek; } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Seeking of compressed RAR files is unsupported"); } return (ARCHIVE_FAILED); } static int archive_read_format_rar_cleanup(struct archive_read *a) { struct rar *rar; rar = (struct rar *)(a->format->data); free_codes(a); free(rar->filename); free(rar->filename_save); free(rar->dbo); free(rar->unp_buffer); free(rar->lzss.window); __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); free(rar); (a->format->data) = NULL; return (ARCHIVE_OK); } static int read_header(struct archive_read *a, struct archive_entry *entry, char head_type) { const void *h; const char *p, *endp; struct rar *rar; struct rar_header rar_header; struct rar_file_header file_header; int64_t header_size; unsigned filename_size, end; char *filename; char *strp; char packed_size[8]; char unp_size[8]; int ttime; struct archive_string_conv *sconv, *fn_sconv; unsigned long crc32_val; int ret = (ARCHIVE_OK), ret2; rar = (struct rar *)(a->format->data); /* Setup a string conversion object for non-rar-unicode filenames. */ sconv = rar->opt_sconv; if (sconv == NULL) { if (!rar->init_default_conversion) { rar->sconv_default = archive_string_default_conversion_for_read( &(a->archive)); rar->init_default_conversion = 1; } sconv = rar->sconv_default; } if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; memcpy(&rar_header, p, sizeof(rar_header)); rar->file_flags = archive_le16dec(rar_header.flags); header_size = archive_le16dec(rar_header.size); if (header_size < (int64_t)sizeof(file_header) + 7) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2); __archive_read_consume(a, 7); if (!(rar->file_flags & FHD_SOLID)) { rar->compression_method = 0; rar->packed_size = 0; rar->unp_size = 0; rar->mtime = 0; rar->ctime = 0; rar->atime = 0; rar->arctime = 0; rar->mode = 0; memset(&rar->salt, 0, sizeof(rar->salt)); rar->atime = 0; rar->ansec = 0; rar->ctime = 0; rar->cnsec = 0; rar->mtime = 0; rar->mnsec = 0; rar->arctime = 0; rar->arcnsec = 0; } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR solid archive support unavailable."); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); /* File Header CRC check. */ crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7)); if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } /* If no CRC error, Go on parsing File Header. */ p = h; endp = p + header_size - 7; memcpy(&file_header, p, sizeof(file_header)); p += sizeof(file_header); rar->compression_method = file_header.method; ttime = archive_le32dec(file_header.file_time); rar->mtime = get_time(ttime); rar->file_crc = archive_le32dec(file_header.file_crc); if (rar->file_flags & FHD_PASSWORD) { archive_entry_set_is_data_encrypted(entry, 1); rar->has_encrypted_entries = 1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR encryption support unavailable."); /* Since it is only the data part itself that is encrypted we can at least extract information about the currently processed entry and don't need to return ARCHIVE_FATAL here. */ /*return (ARCHIVE_FATAL);*/ } if (rar->file_flags & FHD_LARGE) { memcpy(packed_size, file_header.pack_size, 4); memcpy(packed_size + 4, p, 4); /* High pack size */ p += 4; memcpy(unp_size, file_header.unp_size, 4); memcpy(unp_size + 4, p, 4); /* High unpack size */ p += 4; rar->packed_size = archive_le64dec(&packed_size); rar->unp_size = archive_le64dec(&unp_size); } else { rar->packed_size = archive_le32dec(file_header.pack_size); rar->unp_size = archive_le32dec(file_header.unp_size); } if (rar->packed_size < 0 || rar->unp_size < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid sizes specified."); return (ARCHIVE_FATAL); } rar->bytes_remaining = rar->packed_size; /* TODO: RARv3 subblocks contain comments. For now the complete block is * consumed at the end. */ if (head_type == NEWSUB_HEAD) { size_t distance = p - (const char *)h; header_size += rar->packed_size; /* Make sure we have the extended data. */ if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; endp = p + header_size - 7; p += distance; } filename_size = archive_le16dec(file_header.name_size); if (p + filename_size > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename size"); return (ARCHIVE_FATAL); } if (rar->filename_allocated < filename_size * 2 + 2) { char *newptr; size_t newsize = filename_size * 2 + 2; newptr = realloc(rar->filename, newsize); if (newptr == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->filename = newptr; rar->filename_allocated = newsize; } filename = rar->filename; memcpy(filename, p, filename_size); filename[filename_size] = '\0'; if (rar->file_flags & FHD_UNICODE) { if (filename_size != strlen(filename)) { unsigned char highbyte, flagbits, flagbyte; unsigned fn_end, offset; end = filename_size; fn_end = filename_size * 2; filename_size = 0; offset = (unsigned)strlen(filename) + 1; highbyte = *(p + offset++); flagbits = 0; flagbyte = 0; while (offset < end && filename_size < fn_end) { if (!flagbits) { flagbyte = *(p + offset++); flagbits = 8; } flagbits -= 2; switch((flagbyte >> flagbits) & 3) { case 0: filename[filename_size++] = '\0'; filename[filename_size++] = *(p + offset++); break; case 1: filename[filename_size++] = highbyte; filename[filename_size++] = *(p + offset++); break; case 2: filename[filename_size++] = *(p + offset + 1); filename[filename_size++] = *(p + offset); offset += 2; break; case 3: { char extra, high; uint8_t length = *(p + offset++); if (length & 0x80) { extra = *(p + offset++); high = (char)highbyte; } else extra = high = 0; length = (length & 0x7f) + 2; while (length && filename_size < fn_end) { unsigned cp = filename_size >> 1; filename[filename_size++] = high; filename[filename_size++] = p[cp] + extra; length--; } } break; } } if (filename_size > fn_end) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename"); return (ARCHIVE_FATAL); } filename[filename_size++] = '\0'; filename[filename_size++] = '\0'; /* Decoded unicode form is UTF-16BE, so we have to update a string * conversion object for it. */ if (rar->sconv_utf16be == NULL) { rar->sconv_utf16be = archive_string_conversion_from_charset( &a->archive, "UTF-16BE", 1); if (rar->sconv_utf16be == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf16be; strp = filename; while (memcmp(strp, "\x00\x00", 2)) { if (!memcmp(strp, "\x00\\", 2)) *(strp + 1) = '/'; strp += 2; } p += offset; } else { /* * If FHD_UNICODE is set but no unicode data, this file name form * is UTF-8, so we have to update a string conversion object for * it accordingly. */ if (rar->sconv_utf8 == NULL) { rar->sconv_utf8 = archive_string_conversion_from_charset( &a->archive, "UTF-8", 1); if (rar->sconv_utf8 == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf8; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } } else { fn_sconv = sconv; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } /* Split file in multivolume RAR. No more need to process header. */ if (rar->filename_save && filename_size == rar->filename_save_size && !memcmp(rar->filename, rar->filename_save, filename_size + 1)) { __archive_read_consume(a, header_size - 7); rar->cursor++; if (rar->cursor >= rar->nodes) { rar->nodes++; if ((rar->dbo = realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[rar->cursor].header_size = header_size; rar->dbo[rar->cursor].start_offset = -1; rar->dbo[rar->cursor].end_offset = -1; } if (rar->dbo[rar->cursor].start_offset < 0) { rar->dbo[rar->cursor].start_offset = a->filter->position; rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset + rar->packed_size; } return ret; } rar->filename_save = (char*)realloc(rar->filename_save, filename_size + 1); memcpy(rar->filename_save, rar->filename, filename_size + 1); rar->filename_save_size = filename_size; /* Set info for seeking */ free(rar->dbo); if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[0].header_size = header_size; rar->dbo[0].start_offset = -1; rar->dbo[0].end_offset = -1; rar->cursor = 0; rar->nodes = 1; if (rar->file_flags & FHD_SALT) { if (p + 8 > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } memcpy(rar->salt, p, 8); p += 8; } if (rar->file_flags & FHD_EXTTIME) { if (read_exttime(p, rar, endp) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } } __archive_read_consume(a, header_size - 7); rar->dbo[0].start_offset = a->filter->position; rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size; switch(file_header.host_os) { case OS_MSDOS: case OS_OS2: case OS_WIN32: rar->mode = archive_le32dec(file_header.file_attr); if (rar->mode & FILE_ATTRIBUTE_DIRECTORY) rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH; else rar->mode = AE_IFREG; rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; break; case OS_UNIX: case OS_MAC_OS: case OS_BEOS: rar->mode = archive_le32dec(file_header.file_attr); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unknown file attributes from RAR file's host OS"); return (ARCHIVE_FATAL); } rar->bytes_uncopied = rar->bytes_unconsumed = 0; rar->lzss.position = rar->offset = 0; rar->offset_seek = 0; rar->dictionary_size = 0; rar->offset_outgoing = 0; rar->br.cache_avail = 0; rar->br.avail_in = 0; rar->crc_calculated = 0; rar->entry_eof = 0; rar->valid = 1; rar->is_ppmd_block = 0; rar->start_new_table = 1; free(rar->unp_buffer); rar->unp_buffer = NULL; rar->unp_offset = 0; rar->unp_buffer_size = UNP_BUFFER_SIZE; memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); rar->ppmd_valid = rar->ppmd_eod = 0; /* Don't set any archive entries for non-file header types */ if (head_type == NEWSUB_HEAD) return ret; archive_entry_set_mtime(entry, rar->mtime, rar->mnsec); archive_entry_set_ctime(entry, rar->ctime, rar->cnsec); archive_entry_set_atime(entry, rar->atime, rar->ansec); archive_entry_set_size(entry, rar->unp_size); archive_entry_set_mode(entry, rar->mode); if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv)) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(fn_sconv)); ret = (ARCHIVE_WARN); } if (((rar->mode) & AE_IFMT) == AE_IFLNK) { /* Make sure a symbolic-link file does not have its body. */ rar->bytes_remaining = 0; archive_entry_set_size(entry, 0); /* Read a symbolic-link name. */ if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN)) return ret2; if (ret > ret2) ret = ret2; } if (rar->bytes_remaining == 0) rar->entry_eof = 1; return ret; } static time_t get_time(int ttime) { struct tm tm; tm.tm_sec = 2 * (ttime & 0x1f); tm.tm_min = (ttime >> 5) & 0x3f; tm.tm_hour = (ttime >> 11) & 0x1f; tm.tm_mday = (ttime >> 16) & 0x1f; tm.tm_mon = ((ttime >> 21) & 0x0f) - 1; tm.tm_year = ((ttime >> 25) & 0x7f) + 80; tm.tm_isdst = -1; return mktime(&tm); } static int read_exttime(const char *p, struct rar *rar, const char *endp) { unsigned rmode, flags, rem, j, count; int ttime, i; struct tm *tm; time_t t; long nsec; if (p + 2 > endp) return (-1); flags = archive_le16dec(p); p += 2; for (i = 3; i >= 0; i--) { t = 0; if (i == 3) t = rar->mtime; rmode = flags >> i * 4; if (rmode & 8) { if (!t) { if (p + 4 > endp) return (-1); ttime = archive_le32dec(p); t = get_time(ttime); p += 4; } rem = 0; count = rmode & 3; if (p + count > endp) return (-1); for (j = 0; j < count; j++) { rem = (((unsigned)(unsigned char)*p) << 16) | (rem >> 8); p++; } tm = localtime(&t); nsec = tm->tm_sec + rem / NS_UNIT; if (rmode & 4) { tm->tm_sec++; t = mktime(tm); } if (i == 3) { rar->mtime = t; rar->mnsec = nsec; } else if (i == 2) { rar->ctime = t; rar->cnsec = nsec; } else if (i == 1) { rar->atime = t; rar->ansec = nsec; } else { rar->arctime = t; rar->arcnsec = nsec; } } } return (0); } static int read_symlink_stored(struct archive_read *a, struct archive_entry *entry, struct archive_string_conv *sconv) { const void *h; const char *p; struct rar *rar; int ret = (ARCHIVE_OK); rar = (struct rar *)(a->format->data); if ((h = rar_read_ahead(a, (size_t)rar->packed_size, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; if (archive_entry_copy_symlink_l(entry, p, (size_t)rar->packed_size, sconv)) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for link"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "link cannot be converted from %s to current locale.", archive_string_conversion_charset_name(sconv)); ret = (ARCHIVE_WARN); } __archive_read_consume(a, rar->packed_size); return ret; } static int read_data_stored(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct rar *rar; ssize_t bytes_avail; rar = (struct rar *)(a->format->data); if (rar->bytes_remaining == 0 && !(rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER)) { *buff = NULL; *size = 0; *offset = rar->offset; if (rar->file_crc != rar->crc_calculated) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "File CRC error"); return (ARCHIVE_FATAL); } rar->entry_eof = 1; return (ARCHIVE_EOF); } *buff = rar_read_ahead(a, 1, &bytes_avail); if (bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); return (ARCHIVE_FATAL); } *size = bytes_avail; *offset = rar->offset; rar->offset += bytes_avail; rar->offset_seek += bytes_avail; rar->bytes_remaining -= bytes_avail; rar->bytes_unconsumed = bytes_avail; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)bytes_avail); return (ARCHIVE_OK); } static int read_data_compressed(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct rar *rar; int64_t start, end, actualend; size_t bs; int ret = (ARCHIVE_OK), sym, code, lzss_offset, length, i; rar = (struct rar *)(a->format->data); do { if (!rar->valid) return (ARCHIVE_FATAL); if (rar->ppmd_eod || (rar->dictionary_size && rar->offset >= rar->unp_size)) { if (rar->unp_offset > 0) { /* * We have unprocessed extracted data. write it out. */ *buff = rar->unp_buffer; *size = rar->unp_offset; *offset = rar->offset_outgoing; rar->offset_outgoing += *size; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size); rar->unp_offset = 0; return (ARCHIVE_OK); } *buff = NULL; *size = 0; *offset = rar->offset; if (rar->file_crc != rar->crc_calculated) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "File CRC error"); return (ARCHIVE_FATAL); } rar->entry_eof = 1; return (ARCHIVE_EOF); } if (!rar->is_ppmd_block && rar->dictionary_size && rar->bytes_uncopied > 0) { if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset)) bs = rar->unp_buffer_size - rar->unp_offset; else bs = (size_t)rar->bytes_uncopied; ret = copy_from_lzss_window(a, buff, rar->offset, (int)bs); if (ret != ARCHIVE_OK) return (ret); rar->offset += bs; rar->bytes_uncopied -= bs; if (*buff != NULL) { rar->unp_offset = 0; *size = rar->unp_buffer_size; *offset = rar->offset_outgoing; rar->offset_outgoing += *size; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size); return (ret); } continue; } if (!rar->br.next_in && (ret = rar_br_preparation(a, &(rar->br))) < ARCHIVE_WARN) return (ret); if (rar->start_new_table && ((ret = parse_codes(a)) < (ARCHIVE_WARN))) return (ret); if (rar->is_ppmd_block) { if ((sym = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } if(sym != rar->ppmd_escape) { lzss_emit_literal(rar, sym); rar->bytes_uncopied++; } else { if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } switch(code) { case 0: rar->start_new_table = 1; return read_data_compressed(a, buff, size, offset); case 2: rar->ppmd_eod = 1;/* End Of ppmd Data. */ continue; case 3: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Parsing filters is unsupported."); return (ARCHIVE_FAILED); case 4: lzss_offset = 0; for (i = 2; i >= 0; i--) { if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } lzss_offset |= code << (i * 8); } if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } lzss_emit_match(rar, lzss_offset + 2, length + 32); rar->bytes_uncopied += length + 32; break; case 5: if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } lzss_emit_match(rar, 1, length + 4); rar->bytes_uncopied += length + 4; break; default: lzss_emit_literal(rar, sym); rar->bytes_uncopied++; } } } else { start = rar->offset; end = start + rar->dictionary_size; rar->filterstart = INT64_MAX; if ((actualend = expand(a, end)) < 0) return ((int)actualend); rar->bytes_uncopied = actualend - start; if (rar->bytes_uncopied == 0) { /* Broken RAR files cause this case. * NOTE: If this case were possible on a normal RAR file * we would find out where it was actually bad and * what we would do to solve it. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Internal error extracting RAR file"); return (ARCHIVE_FATAL); } } if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset)) bs = rar->unp_buffer_size - rar->unp_offset; else bs = (size_t)rar->bytes_uncopied; ret = copy_from_lzss_window(a, buff, rar->offset, (int)bs); if (ret != ARCHIVE_OK) return (ret); rar->offset += bs; rar->bytes_uncopied -= bs; /* * If *buff is NULL, it means unp_buffer is not full. * So we have to continue extracting a RAR file. */ } while (*buff == NULL); rar->unp_offset = 0; *size = rar->unp_buffer_size; *offset = rar->offset_outgoing; rar->offset_outgoing += *size; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size); return ret; } static int parse_codes(struct archive_read *a) { int i, j, val, n, r; unsigned char bitlengths[MAX_SYMBOLS], zerocount, ppmd_flags; unsigned int maxorder; struct huffman_code precode; struct rar *rar = (struct rar *)(a->format->data); struct rar_br *br = &(rar->br); free_codes(a); /* Skip to the next byte */ rar_br_consume_unalined_bits(br); /* PPMd block flag */ if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; if ((rar->is_ppmd_block = rar_br_bits(br, 1)) != 0) { rar_br_consume(br, 1); if (!rar_br_read_ahead(a, br, 7)) goto truncated_data; ppmd_flags = rar_br_bits(br, 7); rar_br_consume(br, 7); /* Memory is allocated in MB */ if (ppmd_flags & 0x20) { if (!rar_br_read_ahead(a, br, 8)) goto truncated_data; rar->dictionary_size = (rar_br_bits(br, 8) + 1) << 20; rar_br_consume(br, 8); } if (ppmd_flags & 0x40) { if (!rar_br_read_ahead(a, br, 8)) goto truncated_data; rar->ppmd_escape = rar->ppmd7_context.InitEsc = rar_br_bits(br, 8); rar_br_consume(br, 8); } else rar->ppmd_escape = 2; if (ppmd_flags & 0x20) { maxorder = (ppmd_flags & 0x1F) + 1; if(maxorder > 16) maxorder = 16 + (maxorder - 16) * 3; if (maxorder == 1) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); return (ARCHIVE_FATAL); } /* Make sure ppmd7_contest is freed before Ppmd7_Construct * because reading a broken file cause this abnormal sequence. */ __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); rar->bytein.a = a; rar->bytein.Read = &ppmd_read; __archive_ppmd7_functions.PpmdRAR_RangeDec_CreateVTable(&rar->range_dec); rar->range_dec.Stream = &rar->bytein; __archive_ppmd7_functions.Ppmd7_Construct(&rar->ppmd7_context); if (rar->dictionary_size == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid zero dictionary size"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.Ppmd7_Alloc(&rar->ppmd7_context, rar->dictionary_size, &g_szalloc)) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unable to initialize PPMd range decoder"); return (ARCHIVE_FATAL); } __archive_ppmd7_functions.Ppmd7_Init(&rar->ppmd7_context, maxorder); rar->ppmd_valid = 1; } else { if (!rar->ppmd_valid) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid PPMd sequence"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unable to initialize PPMd range decoder"); return (ARCHIVE_FATAL); } } } else { rar_br_consume(br, 1); /* Keep existing table flag */ if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; if (!rar_br_bits(br, 1)) memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); rar_br_consume(br, 1); memset(&bitlengths, 0, sizeof(bitlengths)); for (i = 0; i < MAX_SYMBOLS;) { if (!rar_br_read_ahead(a, br, 4)) goto truncated_data; bitlengths[i++] = rar_br_bits(br, 4); rar_br_consume(br, 4); if (bitlengths[i-1] == 0xF) { if (!rar_br_read_ahead(a, br, 4)) goto truncated_data; zerocount = rar_br_bits(br, 4); rar_br_consume(br, 4); if (zerocount) { i--; for (j = 0; j < zerocount + 2 && i < MAX_SYMBOLS; j++) bitlengths[i++] = 0; } } } memset(&precode, 0, sizeof(precode)); r = create_code(a, &precode, bitlengths, MAX_SYMBOLS, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) { free(precode.tree); free(precode.table); return (r); } for (i = 0; i < HUFFMAN_TABLE_SIZE;) { if ((val = read_next_symbol(a, &precode)) < 0) { free(precode.tree); free(precode.table); return (ARCHIVE_FATAL); } if (val < 16) { rar->lengthtable[i] = (rar->lengthtable[i] + val) & 0xF; i++; } else if (val < 18) { if (i == 0) { free(precode.tree); free(precode.table); archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Internal error extracting RAR file."); return (ARCHIVE_FATAL); } if(val == 16) { if (!rar_br_read_ahead(a, br, 3)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 3) + 3; rar_br_consume(br, 3); } else { if (!rar_br_read_ahead(a, br, 7)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 7) + 11; rar_br_consume(br, 7); } for (j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++) { rar->lengthtable[i] = rar->lengthtable[i-1]; i++; } } else { if(val == 18) { if (!rar_br_read_ahead(a, br, 3)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 3) + 3; rar_br_consume(br, 3); } else { if (!rar_br_read_ahead(a, br, 7)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 7) + 11; rar_br_consume(br, 7); } for(j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++) rar->lengthtable[i++] = 0; } } free(precode.tree); free(precode.table); r = create_code(a, &rar->maincode, &rar->lengthtable[0], MAINCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->offsetcode, &rar->lengthtable[MAINCODE_SIZE], OFFSETCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->lowoffsetcode, &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE], LOWOFFSETCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->lengthcode, &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE + LOWOFFSETCODE_SIZE], LENGTHCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); } if (!rar->dictionary_size || !rar->lzss.window) { /* Seems as though dictionary sizes are not used. Even so, minimize * memory usage as much as possible. */ void *new_window; unsigned int new_size; if (rar->unp_size >= DICTIONARY_MAX_SIZE) new_size = DICTIONARY_MAX_SIZE; else new_size = rar_fls((unsigned int)rar->unp_size) << 1; new_window = realloc(rar->lzss.window, new_size); if (new_window == NULL) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for uncompressed data."); return (ARCHIVE_FATAL); } rar->lzss.window = (unsigned char *)new_window; rar->dictionary_size = new_size; memset(rar->lzss.window, 0, rar->dictionary_size); rar->lzss.mask = rar->dictionary_size - 1; } rar->start_new_table = 0; return (ARCHIVE_OK); truncated_data: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return (ARCHIVE_FATAL); } static void free_codes(struct archive_read *a) { struct rar *rar = (struct rar *)(a->format->data); free(rar->maincode.tree); free(rar->offsetcode.tree); free(rar->lowoffsetcode.tree); free(rar->lengthcode.tree); free(rar->maincode.table); free(rar->offsetcode.table); free(rar->lowoffsetcode.table); free(rar->lengthcode.table); memset(&rar->maincode, 0, sizeof(rar->maincode)); memset(&rar->offsetcode, 0, sizeof(rar->offsetcode)); memset(&rar->lowoffsetcode, 0, sizeof(rar->lowoffsetcode)); memset(&rar->lengthcode, 0, sizeof(rar->lengthcode)); } static int read_next_symbol(struct archive_read *a, struct huffman_code *code) { unsigned char bit; unsigned int bits; int length, value, node; struct rar *rar; struct rar_br *br; if (!code->table) { if (make_table(a, code) != (ARCHIVE_OK)) return -1; } rar = (struct rar *)(a->format->data); br = &(rar->br); /* Look ahead (peek) at bits */ if (!rar_br_read_ahead(a, br, code->tablesize)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return -1; } bits = rar_br_bits(br, code->tablesize); length = code->table[bits].length; value = code->table[bits].value; if (length < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid prefix code in bitstream"); return -1; } if (length <= code->tablesize) { /* Skip length bits */ rar_br_consume(br, length); return value; } /* Skip tablesize bits */ rar_br_consume(br, code->tablesize); node = value; while (!(code->tree[node].branches[0] == code->tree[node].branches[1])) { if (!rar_br_read_ahead(a, br, 1)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return -1; } bit = rar_br_bits(br, 1); rar_br_consume(br, 1); if (code->tree[node].branches[bit] < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid prefix code in bitstream"); return -1; } node = code->tree[node].branches[bit]; } return code->tree[node].branches[0]; } static int create_code(struct archive_read *a, struct huffman_code *code, unsigned char *lengths, int numsymbols, char maxlength) { int i, j, codebits = 0, symbolsleft = numsymbols; code->numentries = 0; code->numallocatedentries = 0; if (new_node(code) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } code->numentries = 1; code->minlength = INT_MAX; code->maxlength = INT_MIN; codebits = 0; for(i = 1; i <= maxlength; i++) { for(j = 0; j < numsymbols; j++) { if (lengths[j] != i) continue; if (add_value(a, code, j, codebits, i) != ARCHIVE_OK) return (ARCHIVE_FATAL); codebits++; if (--symbolsleft <= 0) { break; break; } } codebits <<= 1; } return (ARCHIVE_OK); } static int add_value(struct archive_read *a, struct huffman_code *code, int value, int codebits, int length) { int repeatpos, lastnode, bitpos, bit, repeatnode, nextnode; free(code->table); code->table = NULL; if(length > code->maxlength) code->maxlength = length; if(length < code->minlength) code->minlength = length; repeatpos = -1; if (repeatpos == 0 || (repeatpos >= 0 && (((codebits >> (repeatpos - 1)) & 3) == 0 || ((codebits >> (repeatpos - 1)) & 3) == 3))) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid repeat position"); return (ARCHIVE_FATAL); } lastnode = 0; for (bitpos = length - 1; bitpos >= 0; bitpos--) { bit = (codebits >> bitpos) & 1; /* Leaf node check */ if (code->tree[lastnode].branches[0] == code->tree[lastnode].branches[1]) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Prefix found"); return (ARCHIVE_FATAL); } if (bitpos == repeatpos) { /* Open branch check */ if (!(code->tree[lastnode].branches[bit] < 0)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid repeating code"); return (ARCHIVE_FATAL); } if ((repeatnode = new_node(code)) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } if ((nextnode = new_node(code)) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } /* Set branches */ code->tree[lastnode].branches[bit] = repeatnode; code->tree[repeatnode].branches[bit] = repeatnode; code->tree[repeatnode].branches[bit^1] = nextnode; lastnode = nextnode; bitpos++; /* terminating bit already handled, skip it */ } else { /* Open branch check */ if (code->tree[lastnode].branches[bit] < 0) { if (new_node(code) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } code->tree[lastnode].branches[bit] = code->numentries++; } /* set to branch */ lastnode = code->tree[lastnode].branches[bit]; } } if (!(code->tree[lastnode].branches[0] == -1 && code->tree[lastnode].branches[1] == -2)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Prefix found"); return (ARCHIVE_FATAL); } /* Set leaf value */ code->tree[lastnode].branches[0] = value; code->tree[lastnode].branches[1] = value; return (ARCHIVE_OK); } static int new_node(struct huffman_code *code) { void *new_tree; if (code->numallocatedentries == code->numentries) { int new_num_entries = 256; if (code->numentries > 0) { new_num_entries = code->numentries * 2; } new_tree = realloc(code->tree, new_num_entries * sizeof(*code->tree)); if (new_tree == NULL) return (-1); code->tree = (struct huffman_tree_node *)new_tree; code->numallocatedentries = new_num_entries; } code->tree[code->numentries].branches[0] = -1; code->tree[code->numentries].branches[1] = -2; return 1; } static int make_table(struct archive_read *a, struct huffman_code *code) { if (code->maxlength < code->minlength || code->maxlength > 10) code->tablesize = 10; else code->tablesize = code->maxlength; code->table = (struct huffman_table_entry *)calloc(1, sizeof(*code->table) * ((size_t)1 << code->tablesize)); return make_table_recurse(a, code, 0, code->table, 0, code->tablesize); } static int make_table_recurse(struct archive_read *a, struct huffman_code *code, int node, struct huffman_table_entry *table, int depth, int maxdepth) { int currtablesize, i, ret = (ARCHIVE_OK); if (!code->tree) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Huffman tree was not created."); return (ARCHIVE_FATAL); } if (node < 0 || node >= code->numentries) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid location to Huffman tree specified."); return (ARCHIVE_FATAL); } currtablesize = 1 << (maxdepth - depth); if (code->tree[node].branches[0] == code->tree[node].branches[1]) { for(i = 0; i < currtablesize; i++) { table[i].length = depth; table[i].value = code->tree[node].branches[0]; } } else if (node < 0) { for(i = 0; i < currtablesize; i++) table[i].length = -1; } else { if(depth == maxdepth) { table[0].length = maxdepth + 1; table[0].value = node; } else { ret |= make_table_recurse(a, code, code->tree[node].branches[0], table, depth + 1, maxdepth); ret |= make_table_recurse(a, code, code->tree[node].branches[1], table + currtablesize / 2, depth + 1, maxdepth); } } return ret; } static int64_t expand(struct archive_read *a, int64_t end) { static const unsigned char lengthbases[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224 }; static const unsigned char lengthbits[] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 }; static const unsigned int offsetbases[] = { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576, 32768, 49152, 65536, 98304, 131072, 196608, 262144, 327680, 393216, 458752, 524288, 589824, 655360, 720896, 786432, 851968, 917504, 983040, 1048576, 1310720, 1572864, 1835008, 2097152, 2359296, 2621440, 2883584, 3145728, 3407872, 3670016, 3932160 }; static const unsigned char offsetbits[] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18 }; static const unsigned char shortbases[] = { 0, 4, 8, 16, 32, 64, 128, 192 }; static const unsigned char shortbits[] = { 2, 2, 3, 4, 5, 6, 6, 6 }; int symbol, offs, len, offsindex, lensymbol, i, offssymbol, lowoffsetsymbol; unsigned char newfile; struct rar *rar = (struct rar *)(a->format->data); struct rar_br *br = &(rar->br); if (rar->filterstart < end) end = rar->filterstart; while (1) { if (rar->output_last_match && lzss_position(&rar->lzss) + rar->lastlength <= end) { lzss_emit_match(rar, rar->lastoffset, rar->lastlength); rar->output_last_match = 0; } if(rar->is_ppmd_block || rar->output_last_match || lzss_position(&rar->lzss) >= end) return lzss_position(&rar->lzss); if ((symbol = read_next_symbol(a, &rar->maincode)) < 0) return (ARCHIVE_FATAL); rar->output_last_match = 0; if (symbol < 256) { lzss_emit_literal(rar, symbol); continue; } else if (symbol == 256) { if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; newfile = !rar_br_bits(br, 1); rar_br_consume(br, 1); if(newfile) { rar->start_new_block = 1; if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; rar->start_new_table = rar_br_bits(br, 1); rar_br_consume(br, 1); return lzss_position(&rar->lzss); } else { if (parse_codes(a) != ARCHIVE_OK) return (ARCHIVE_FATAL); continue; } } else if(symbol==257) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Parsing filters is unsupported."); return (ARCHIVE_FAILED); } else if(symbol==258) { if(rar->lastlength == 0) continue; offs = rar->lastoffset; len = rar->lastlength; } else if (symbol <= 262) { offsindex = symbol - 259; offs = rar->oldoffset[offsindex]; if ((lensymbol = read_next_symbol(a, &rar->lengthcode)) < 0) goto bad_data; if (lensymbol > (int)(sizeof(lengthbases)/sizeof(lengthbases[0]))) goto bad_data; if (lensymbol > (int)(sizeof(lengthbits)/sizeof(lengthbits[0]))) goto bad_data; len = lengthbases[lensymbol] + 2; if (lengthbits[lensymbol] > 0) { if (!rar_br_read_ahead(a, br, lengthbits[lensymbol])) goto truncated_data; len += rar_br_bits(br, lengthbits[lensymbol]); rar_br_consume(br, lengthbits[lensymbol]); } for (i = offsindex; i > 0; i--) rar->oldoffset[i] = rar->oldoffset[i-1]; rar->oldoffset[0] = offs; } else if(symbol<=270) { offs = shortbases[symbol-263] + 1; if(shortbits[symbol-263] > 0) { if (!rar_br_read_ahead(a, br, shortbits[symbol-263])) goto truncated_data; offs += rar_br_bits(br, shortbits[symbol-263]); rar_br_consume(br, shortbits[symbol-263]); } len = 2; for(i = 3; i > 0; i--) rar->oldoffset[i] = rar->oldoffset[i-1]; rar->oldoffset[0] = offs; } else { if (symbol-271 > (int)(sizeof(lengthbases)/sizeof(lengthbases[0]))) goto bad_data; if (symbol-271 > (int)(sizeof(lengthbits)/sizeof(lengthbits[0]))) goto bad_data; len = lengthbases[symbol-271]+3; if(lengthbits[symbol-271] > 0) { if (!rar_br_read_ahead(a, br, lengthbits[symbol-271])) goto truncated_data; len += rar_br_bits(br, lengthbits[symbol-271]); rar_br_consume(br, lengthbits[symbol-271]); } if ((offssymbol = read_next_symbol(a, &rar->offsetcode)) < 0) goto bad_data; if (offssymbol > (int)(sizeof(offsetbases)/sizeof(offsetbases[0]))) goto bad_data; if (offssymbol > (int)(sizeof(offsetbits)/sizeof(offsetbits[0]))) goto bad_data; offs = offsetbases[offssymbol]+1; if(offsetbits[offssymbol] > 0) { if(offssymbol > 9) { if(offsetbits[offssymbol] > 4) { if (!rar_br_read_ahead(a, br, offsetbits[offssymbol] - 4)) goto truncated_data; offs += rar_br_bits(br, offsetbits[offssymbol] - 4) << 4; rar_br_consume(br, offsetbits[offssymbol] - 4); } if(rar->numlowoffsetrepeats > 0) { rar->numlowoffsetrepeats--; offs += rar->lastlowoffset; } else { if ((lowoffsetsymbol = read_next_symbol(a, &rar->lowoffsetcode)) < 0) return (ARCHIVE_FATAL); if(lowoffsetsymbol == 16) { rar->numlowoffsetrepeats = 15; offs += rar->lastlowoffset; } else { offs += lowoffsetsymbol; rar->lastlowoffset = lowoffsetsymbol; } } } else { if (!rar_br_read_ahead(a, br, offsetbits[offssymbol])) goto truncated_data; offs += rar_br_bits(br, offsetbits[offssymbol]); rar_br_consume(br, offsetbits[offssymbol]); } } if (offs >= 0x40000) len++; if (offs >= 0x2000) len++; for(i = 3; i > 0; i--) rar->oldoffset[i] = rar->oldoffset[i-1]; rar->oldoffset[0] = offs; } rar->lastoffset = offs; rar->lastlength = len; rar->output_last_match = 1; } truncated_data: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return (ARCHIVE_FATAL); bad_data: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file data"); return (ARCHIVE_FATAL); } static int copy_from_lzss_window(struct archive_read *a, const void **buffer, int64_t startpos, int length) { int windowoffs, firstpart; struct rar *rar = (struct rar *)(a->format->data); if (!rar->unp_buffer) { if ((rar->unp_buffer = malloc(rar->unp_buffer_size)) == NULL) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for uncompressed data."); return (ARCHIVE_FATAL); } } windowoffs = lzss_offset_for_position(&rar->lzss, startpos); if(windowoffs + length <= lzss_size(&rar->lzss)) { memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs], length); } else if (length <= lzss_size(&rar->lzss)) { firstpart = lzss_size(&rar->lzss) - windowoffs; if (firstpart < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file data"); return (ARCHIVE_FATAL); } if (firstpart < length) { memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs], firstpart); memcpy(&rar->unp_buffer[rar->unp_offset + firstpart], &rar->lzss.window[0], length - firstpart); } else { memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs], length); } } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file data"); return (ARCHIVE_FATAL); } rar->unp_offset += length; if (rar->unp_offset >= rar->unp_buffer_size) *buffer = rar->unp_buffer; else *buffer = NULL; return (ARCHIVE_OK); } static const void * rar_read_ahead(struct archive_read *a, size_t min, ssize_t *avail) { struct rar *rar = (struct rar *)(a->format->data); const void *h = __archive_read_ahead(a, min, avail); int ret; if (avail) { if (a->archive.read_data_is_posix_read && *avail > (ssize_t)a->archive.read_data_requested) *avail = a->archive.read_data_requested; if (*avail > rar->bytes_remaining) *avail = (ssize_t)rar->bytes_remaining; if (*avail < 0) return NULL; else if (*avail == 0 && rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER) { ret = archive_read_format_rar_read_header(a, a->entry); if (ret == (ARCHIVE_EOF)) { rar->has_endarc_header = 1; ret = archive_read_format_rar_read_header(a, a->entry); } if (ret != (ARCHIVE_OK)) return NULL; return rar_read_ahead(a, min, avail); } } return h; }
./CrossVul/dataset_final_sorted/CWE-193/c/bad_2801_0
crossvul-cpp_data_good_3860_0
/* * Copyright (c) 2018 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ /** @file mqtt_decoder.c * * @brief Decoder functions needed for decoding packets received from the * broker. */ #include <logging/log.h> LOG_MODULE_REGISTER(net_mqtt_dec, CONFIG_MQTT_LOG_LEVEL); #include "mqtt_internal.h" #include "mqtt_os.h" /** * @brief Unpacks unsigned 8 bit value from the buffer from the offset * requested. * * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] val Memory where the value is to be unpacked. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the buffer would be exceeded during the read */ static int unpack_uint8(struct buf_ctx *buf, u8_t *val) { MQTT_TRC(">> cur:%p, end:%p", buf->cur, buf->end); if ((buf->end - buf->cur) < sizeof(u8_t)) { return -EINVAL; } *val = *(buf->cur++); MQTT_TRC("<< val:%02x", *val); return 0; } /** * @brief Unpacks unsigned 16 bit value from the buffer from the offset * requested. * * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] val Memory where the value is to be unpacked. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the buffer would be exceeded during the read */ static int unpack_uint16(struct buf_ctx *buf, u16_t *val) { MQTT_TRC(">> cur:%p, end:%p", buf->cur, buf->end); if ((buf->end - buf->cur) < sizeof(u16_t)) { return -EINVAL; } *val = *(buf->cur++) << 8; /* MSB */ *val |= *(buf->cur++); /* LSB */ MQTT_TRC("<< val:%04x", *val); return 0; } /** * @brief Unpacks utf8 string from the buffer from the offset requested. * * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] str Pointer to a string that will hold the string location * in the buffer. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the buffer would be exceeded during the read */ static int unpack_utf8_str(struct buf_ctx *buf, struct mqtt_utf8 *str) { u16_t utf8_strlen; int err_code; MQTT_TRC(">> cur:%p, end:%p", buf->cur, buf->end); err_code = unpack_uint16(buf, &utf8_strlen); if (err_code != 0) { return err_code; } if ((buf->end - buf->cur) < utf8_strlen) { return -EINVAL; } str->size = utf8_strlen; /* Zero length UTF8 strings permitted. */ if (utf8_strlen) { /* Point to right location in buffer. */ str->utf8 = buf->cur; buf->cur += utf8_strlen; } else { str->utf8 = NULL; } MQTT_TRC("<< str_size:%08x", (u32_t)GET_UT8STR_BUFFER_SIZE(str)); return 0; } /** * @brief Unpacks binary string from the buffer from the offset requested. * * @param[in] length Binary string length. * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] str Pointer to a binary string that will hold the binary string * location in the buffer. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the buffer would be exceeded during the read */ static int unpack_data(u32_t length, struct buf_ctx *buf, struct mqtt_binstr *str) { MQTT_TRC(">> cur:%p, end:%p", buf->cur, buf->end); if ((buf->end - buf->cur) < length) { return -EINVAL; } str->len = length; /* Zero length binary strings are permitted. */ if (length > 0) { str->data = buf->cur; buf->cur += length; } else { str->data = NULL; } MQTT_TRC("<< bin len:%08x", GET_BINSTR_BUFFER_SIZE(str)); return 0; } /**@brief Decode MQTT Packet Length in the MQTT fixed header. * * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] length Length of variable header and payload in the * MQTT message. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the length decoding would use more that 4 bytes. * @retval -EAGAIN if the buffer would be exceeded during the read. */ static int packet_length_decode(struct buf_ctx *buf, u32_t *length) { u8_t shift = 0U; u8_t bytes = 0U; *length = 0U; do { if (bytes >= MQTT_MAX_LENGTH_BYTES) { return -EINVAL; } if (buf->cur >= buf->end) { return -EAGAIN; } *length += ((u32_t)*(buf->cur) & MQTT_LENGTH_VALUE_MASK) << shift; shift += MQTT_LENGTH_SHIFT; bytes++; } while ((*(buf->cur++) & MQTT_LENGTH_CONTINUATION_BIT) != 0U); if (*length > MQTT_MAX_PAYLOAD_SIZE) { return -EINVAL; } MQTT_TRC("length:0x%08x", *length); return 0; } int fixed_header_decode(struct buf_ctx *buf, u8_t *type_and_flags, u32_t *length) { int err_code; err_code = unpack_uint8(buf, type_and_flags); if (err_code != 0) { return err_code; } return packet_length_decode(buf, length); } int connect_ack_decode(const struct mqtt_client *client, struct buf_ctx *buf, struct mqtt_connack_param *param) { int err_code; u8_t flags, ret_code; err_code = unpack_uint8(buf, &flags); if (err_code != 0) { return err_code; } err_code = unpack_uint8(buf, &ret_code); if (err_code != 0) { return err_code; } if (client->protocol_version == MQTT_VERSION_3_1_1) { param->session_present_flag = flags & MQTT_CONNACK_FLAG_SESSION_PRESENT; MQTT_TRC("[CID %p]: session_present_flag: %d", client, param->session_present_flag); } param->return_code = (enum mqtt_conn_return_code)ret_code; return 0; } int publish_decode(u8_t flags, u32_t var_length, struct buf_ctx *buf, struct mqtt_publish_param *param) { int err_code; u32_t var_header_length; param->dup_flag = flags & MQTT_HEADER_DUP_MASK; param->retain_flag = flags & MQTT_HEADER_RETAIN_MASK; param->message.topic.qos = ((flags & MQTT_HEADER_QOS_MASK) >> 1); err_code = unpack_utf8_str(buf, &param->message.topic.topic); if (err_code != 0) { return err_code; } var_header_length = param->message.topic.topic.size + sizeof(u16_t); if (param->message.topic.qos > MQTT_QOS_0_AT_MOST_ONCE) { err_code = unpack_uint16(buf, &param->message_id); if (err_code != 0) { return err_code; } var_header_length += sizeof(u16_t); } param->message.payload.data = NULL; param->message.payload.len = var_length - var_header_length; return 0; } int publish_ack_decode(struct buf_ctx *buf, struct mqtt_puback_param *param) { return unpack_uint16(buf, &param->message_id); } int publish_receive_decode(struct buf_ctx *buf, struct mqtt_pubrec_param *param) { return unpack_uint16(buf, &param->message_id); } int publish_release_decode(struct buf_ctx *buf, struct mqtt_pubrel_param *param) { return unpack_uint16(buf, &param->message_id); } int publish_complete_decode(struct buf_ctx *buf, struct mqtt_pubcomp_param *param) { return unpack_uint16(buf, &param->message_id); } int subscribe_ack_decode(struct buf_ctx *buf, struct mqtt_suback_param *param) { int err_code; err_code = unpack_uint16(buf, &param->message_id); if (err_code != 0) { return err_code; } return unpack_data(buf->end - buf->cur, buf, &param->return_codes); } int unsubscribe_ack_decode(struct buf_ctx *buf, struct mqtt_unsuback_param *param) { return unpack_uint16(buf, &param->message_id); }
./CrossVul/dataset_final_sorted/CWE-193/c/good_3860_0
crossvul-cpp_data_good_4375_2
/* * Copyright (C) 2011, 2012, 2013 Citrix Systems * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ns_turn_server.h" #include "ns_turn_utils.h" #include "ns_turn_allocation.h" #include "ns_turn_msg_addr.h" #include "ns_turn_ioalib.h" #include "../apps/relay/ns_ioalib_impl.h" /////////////////////////////////////////// #define FUNCSTART if(server && eve(server->verbose)) TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"%s:%d:start\n",__FUNCTION__,__LINE__) #define FUNCEND if(server && eve(server->verbose)) TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"%s:%d:end\n",__FUNCTION__,__LINE__) //////////////////////////////////////////////// static inline int get_family(int stun_family, ioa_engine_handle e, ioa_socket_handle client_socket) { switch(stun_family) { case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4: return AF_INET; break; case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6: return AF_INET6; break; case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_DEFAULT: if(e->default_relays && get_ioa_socket_address_family(client_socket) == AF_INET6) return AF_INET6; else return AF_INET; default: return AF_INET; }; } //////////////////////////////////////////////// const char * get_version(turn_turnserver *server) { if(server && !*server->no_software_attribute) { return (const char *) TURN_SOFTWARE; } else { return (const char *) "None"; } } #define MAX_NUMBER_OF_UNKNOWN_ATTRS (128) int TURN_MAX_ALLOCATE_TIMEOUT = 60; int TURN_MAX_ALLOCATE_TIMEOUT_STUN_ONLY = 3; static inline void log_method(ts_ur_super_session* ss, const char *method, int err_code, const uint8_t *reason) { if(ss) { if(!method) method = "unknown"; if(!err_code) { if(ss->origin[0]) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: origin <%s> realm <%s> user <%s>: incoming packet %s processed, success\n", (unsigned long long)(ss->id), (const char*)(ss->origin),(const char*)(ss->realm_options.name),(const char*)(ss->username),method); } else { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: realm <%s> user <%s>: incoming packet %s processed, success\n", (unsigned long long)(ss->id), (const char*)(ss->realm_options.name),(const char*)(ss->username),method); } } else { if(!reason) reason=get_default_reason(err_code); if(ss->origin[0]) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: origin <%s> realm <%s> user <%s>: incoming packet %s processed, error %d: %s\n", (unsigned long long)(ss->id), (const char*)(ss->origin),(const char*)(ss->realm_options.name),(const char*)(ss->username), method, err_code, reason); } else { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: realm <%s> user <%s>: incoming packet %s processed, error %d: %s\n", (unsigned long long)(ss->id), (const char*)(ss->realm_options.name),(const char*)(ss->username), method, err_code, reason); } } } } /////////////////////////////////////////// static int attach_socket_to_session(turn_turnserver* server, ioa_socket_handle s, ts_ur_super_session* ss); static int check_stun_auth(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh, uint16_t method, int *message_integrity, int *postpone_reply, int can_resume); static int create_relay_connection(turn_turnserver* server, ts_ur_super_session *ss, uint32_t lifetime, int address_family, uint8_t transport, int even_port, uint64_t in_reservation_token, uint64_t *out_reservation_token, int *err_code, const uint8_t **reason, accept_cb acb); static int refresh_relay_connection(turn_turnserver* server, ts_ur_super_session *ss, uint32_t lifetime, int even_port, uint64_t in_reservation_token, uint64_t *out_reservation_token, int *err_code, int family); static int write_client_connection(turn_turnserver *server, ts_ur_super_session* ss, ioa_network_buffer_handle nbh, int ttl, int tos); static void tcp_peer_accept_connection(ioa_socket_handle s, void *arg); static int read_client_connection(turn_turnserver *server, ts_ur_super_session *ss, ioa_net_data *in_buffer, int can_resume, int count_usage); static int need_stun_authentication(turn_turnserver *server, ts_ur_super_session *ss); /////////////////// timer ////////////////////////// static void timer_timeout_handler(ioa_engine_handle e, void *arg) { UNUSED_ARG(e); if(arg) { turn_turnserver *server=(turn_turnserver*)arg; server->ctime = turn_time(); } } turn_time_t get_turn_server_time(turn_turnserver *server) { if(server) { return server->ctime; } return turn_time(); } /////////////////// quota ////////////////////// static int inc_quota(ts_ur_super_session* ss, uint8_t *username) { if(ss && !(ss->quota_used) && ss->server && ((turn_turnserver*)ss->server)->chquotacb && username) { if(((turn_turnserver*)ss->server)->ct == TURN_CREDENTIALS_LONG_TERM) { if(!(ss->origin_set)) { return -1; } } if((((turn_turnserver*)ss->server)->chquotacb)(username, ss->oauth, (uint8_t*)ss->realm_options.name)<0) { return -1; } else { STRCPY(ss->username,username); ss->quota_used = 1; } } return 0; } static void dec_quota(ts_ur_super_session* ss) { if(ss && ss->quota_used && ss->server && ((turn_turnserver*)ss->server)->raqcb) { ss->quota_used = 0; (((turn_turnserver*)ss->server)->raqcb)(ss->username, ss->oauth, (uint8_t*)ss->realm_options.name); } } static void dec_bps(ts_ur_super_session* ss) { if(ss && ss->server) { if(ss->bps) { if(((turn_turnserver*)ss->server)->allocate_bps_func) { ((turn_turnserver*)ss->server)->allocate_bps_func(ss->bps,0); } ss->bps = 0; } } } /////////////////// server lists /////////////////// void init_turn_server_addrs_list(turn_server_addrs_list_t *l) { if(l) { l->addrs = NULL; l->size = 0; turn_mutex_init(&(l->m)); } } /////////////////// RFC 5780 /////////////////////// void set_rfc5780(turn_turnserver *server, get_alt_addr_cb cb, send_message_cb smcb) { if(server) { if(!cb || !smcb) { server->rfc5780 = 0; server->alt_addr_cb = NULL; server->sm_cb = NULL; } else { server->rfc5780 = 1; server->alt_addr_cb = cb; server->sm_cb = smcb; } } } static int is_rfc5780(turn_turnserver *server) { if(!server) return 0; return ((server->rfc5780) && (server->alt_addr_cb)); } static int get_other_address(turn_turnserver *server, ts_ur_super_session *ss, ioa_addr *alt_addr) { if(is_rfc5780(server) && ss && ss->client_socket) { int ret = server->alt_addr_cb(get_local_addr_from_ioa_socket(ss->client_socket), alt_addr); return ret; } return -1; } static int send_turn_message_to(turn_turnserver *server, ioa_network_buffer_handle nbh, ioa_addr *response_origin, ioa_addr *response_destination) { if(is_rfc5780(server) && nbh && response_origin && response_destination) { return server->sm_cb(server->e, nbh, response_origin, response_destination); } return -1; } /////////////////// Peer addr check ///////////////////////////// static int good_peer_addr(turn_turnserver *server, const char* realm, ioa_addr *peer_addr) { #define CHECK_REALM(r) if((r)[0] && realm && realm[0] && strcmp((r),realm)) continue if(server && peer_addr) { if(*(server->no_multicast_peers) && ioa_addr_is_multicast(peer_addr)) return 0; if( !*(server->allow_loopback_peers) && ioa_addr_is_loopback(peer_addr)) return 0; if (ioa_addr_is_zero(peer_addr)) return 0; { int i; if(server->ip_whitelist) { // White listing of addr ranges for (i = server->ip_whitelist->ranges_number - 1; i >= 0; --i) { CHECK_REALM(server->ip_whitelist->rs[i].realm); if (ioa_addr_in_range(&(server->ip_whitelist->rs[i].enc), peer_addr)) return 1; } } { ioa_lock_whitelist(server->e); const ip_range_list_t* wl = ioa_get_whitelist(server->e); if(wl) { // White listing of addr ranges for (i = wl->ranges_number - 1; i >= 0; --i) { CHECK_REALM(wl->rs[i].realm); if (ioa_addr_in_range(&(wl->rs[i].enc), peer_addr)) { ioa_unlock_whitelist(server->e); return 1; } } } ioa_unlock_whitelist(server->e); } if(server->ip_blacklist) { // Black listing of addr ranges for (i = server->ip_blacklist->ranges_number - 1; i >= 0; --i) { CHECK_REALM(server->ip_blacklist->rs[i].realm); if (ioa_addr_in_range(&(server->ip_blacklist->rs[i].enc), peer_addr)) { char saddr[129]; addr_to_string_no_port(peer_addr,(uint8_t*)saddr); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "A peer IP %s denied in the range: %s\n",saddr,server->ip_blacklist->rs[i].str); return 0; } } } { ioa_lock_blacklist(server->e); const ip_range_list_t* bl = ioa_get_blacklist(server->e); if(bl) { // Black listing of addr ranges for (i = bl->ranges_number - 1; i >= 0; --i) { CHECK_REALM(bl->rs[i].realm); if (ioa_addr_in_range(&(bl->rs[i].enc), peer_addr)) { ioa_unlock_blacklist(server->e); char saddr[129]; addr_to_string_no_port(peer_addr,(uint8_t*)saddr); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "A peer IP %s denied in the range: %s\n",saddr,bl->rs[i].str); return 0; } } } ioa_unlock_blacklist(server->e); } } } #undef CHECK_REALM return 1; } /////////////////// Allocation ////////////////////////////////// allocation* get_allocation_ss(ts_ur_super_session *ss) { return &(ss->alloc); } static inline relay_endpoint_session *get_relay_session_ss(ts_ur_super_session *ss, int family) { return get_relay_session(&(ss->alloc),family); } static inline ioa_socket_handle get_relay_socket_ss(ts_ur_super_session *ss, int family) { return get_relay_socket(&(ss->alloc),family); } /////////// Session info /////// void turn_session_info_init(struct turn_session_info* tsi) { if(tsi) { bzero(tsi,sizeof(struct turn_session_info)); } } void turn_session_info_clean(struct turn_session_info* tsi) { if(tsi) { if(tsi->extra_peers_data) { free(tsi->extra_peers_data); } turn_session_info_init(tsi); } } void turn_session_info_add_peer(struct turn_session_info* tsi, ioa_addr *peer) { if(tsi && peer) { { size_t i; for(i=0;i<tsi->main_peers_size;++i) { if(addr_eq(peer, &(tsi->main_peers_data[i].addr))) { return; } } if(tsi->main_peers_size < TURN_MAIN_PEERS_ARRAY_SIZE) { addr_cpy(&(tsi->main_peers_data[tsi->main_peers_size].addr),peer); addr_to_string(&(tsi->main_peers_data[tsi->main_peers_size].addr), (uint8_t*)tsi->main_peers_data[tsi->main_peers_size].saddr); tsi->main_peers_size += 1; return; } } if(tsi->extra_peers_data) { size_t sz; for(sz=0;sz<tsi->extra_peers_size;++sz) { if(addr_eq(peer, &(tsi->extra_peers_data[sz].addr))) { return; } } } tsi->extra_peers_data = (addr_data*)realloc(tsi->extra_peers_data,(tsi->extra_peers_size+1)*sizeof(addr_data)); addr_cpy(&(tsi->extra_peers_data[tsi->extra_peers_size].addr),peer); addr_to_string(&(tsi->extra_peers_data[tsi->extra_peers_size].addr), (uint8_t*)tsi->extra_peers_data[tsi->extra_peers_size].saddr); tsi->extra_peers_size += 1; } } struct tsi_arg { struct turn_session_info* tsi; ioa_addr *addr; }; static int turn_session_info_foreachcb(ur_map_key_type key, ur_map_value_type value, void *arg) { UNUSED_ARG(value); int port = (int)key; struct tsi_arg *ta = (struct tsi_arg *)arg; if(port && ta && ta->tsi && ta->addr) { ioa_addr a; addr_cpy(&a,ta->addr); addr_set_port(&a,port); turn_session_info_add_peer(ta->tsi,&a); } return 0; } int turn_session_info_copy_from(struct turn_session_info* tsi, ts_ur_super_session *ss) { int ret = -1; if(tsi && ss) { tsi->id = ss->id; tsi->bps = ss->bps; tsi->start_time = ss->start_time; tsi->valid = is_allocation_valid(&(ss->alloc)) && !(ss->to_be_closed) && (ss->quota_used); if(tsi->valid) { if(ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].s) { tsi->expiration_time = ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].expiration_time; if(ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].s) { if(turn_time_before(tsi->expiration_time,ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].expiration_time)) { tsi->expiration_time = ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].expiration_time; } } } else if(ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].s) { tsi->expiration_time = ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].expiration_time; } if(ss->client_socket) { tsi->client_protocol = get_ioa_socket_type(ss->client_socket); addr_cpy(&(tsi->local_addr_data.addr),get_local_addr_from_ioa_socket(ss->client_socket)); addr_to_string(&(tsi->local_addr_data.addr),(uint8_t*)tsi->local_addr_data.saddr); addr_cpy(&(tsi->remote_addr_data.addr),get_remote_addr_from_ioa_socket(ss->client_socket)); addr_to_string(&(tsi->remote_addr_data.addr),(uint8_t*)tsi->remote_addr_data.saddr); } { if(ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].s) { tsi->peer_protocol = get_ioa_socket_type(ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].s); if(ss->alloc.is_valid) { addr_cpy(&(tsi->relay_addr_data_ipv4.addr),get_local_addr_from_ioa_socket(ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].s)); addr_to_string(&(tsi->relay_addr_data_ipv4.addr),(uint8_t*)tsi->relay_addr_data_ipv4.saddr); } } if(ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].s) { tsi->peer_protocol = get_ioa_socket_type(ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].s); if(ss->alloc.is_valid) { addr_cpy(&(tsi->relay_addr_data_ipv6.addr),get_local_addr_from_ioa_socket(ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].s)); addr_to_string(&(tsi->relay_addr_data_ipv6.addr),(uint8_t*)tsi->relay_addr_data_ipv6.saddr); } } } STRCPY(tsi->username,ss->username); tsi->enforce_fingerprints = ss->enforce_fingerprints; STRCPY(tsi->tls_method, get_ioa_socket_tls_method(ss->client_socket)); STRCPY(tsi->tls_cipher, get_ioa_socket_tls_cipher(ss->client_socket)); STRCPY(tsi->realm, ss->realm_options.name); STRCPY(tsi->origin, ss->origin); if(ss->t_received_packets > ss->received_packets) tsi->received_packets = ss->t_received_packets; else tsi->received_packets = ss->received_packets; if(ss->t_sent_packets > ss->sent_packets) tsi->sent_packets = ss->t_sent_packets; else tsi->sent_packets = ss->sent_packets; if(ss->t_received_bytes > ss->received_bytes) tsi->received_bytes = ss->t_received_bytes; else tsi->received_bytes = ss->received_bytes; if(ss->t_sent_bytes > ss->sent_bytes) tsi->sent_bytes = ss->t_sent_bytes; else tsi->sent_bytes = ss->sent_bytes; if (ss->t_peer_received_packets > ss->peer_received_packets) tsi->peer_received_packets = ss->t_peer_received_packets; else tsi->peer_received_packets = ss->peer_received_packets; if (ss->t_peer_sent_packets > ss->peer_sent_packets) tsi->peer_sent_packets = ss->t_peer_sent_packets; else tsi->peer_sent_packets = ss->peer_sent_packets; if (ss->t_peer_received_bytes > ss->peer_received_bytes) tsi->peer_received_bytes = ss->t_peer_received_bytes; else tsi->peer_received_bytes = ss->peer_received_bytes; if (ss->t_peer_sent_bytes > ss->peer_sent_bytes) tsi->peer_sent_bytes = ss->t_peer_sent_bytes; else tsi->peer_sent_bytes = ss->peer_sent_bytes; { tsi->received_rate = ss->received_rate; tsi->sent_rate = ss->sent_rate; tsi->total_rate = tsi->received_rate + tsi->sent_rate; tsi->peer_received_rate = ss->peer_received_rate; tsi->peer_sent_rate = ss->peer_sent_rate; tsi->peer_total_rate = tsi->peer_received_rate + tsi->peer_sent_rate; } tsi->is_mobile = ss->is_mobile; { size_t i; for(i=0;i<TURN_PERMISSION_HASHTABLE_SIZE;++i) { turn_permission_array *parray = &(ss->alloc.addr_to_perm.table[i]); { size_t j; for(j=0;j<TURN_PERMISSION_ARRAY_SIZE;++j) { turn_permission_slot* slot = &(parray->main_slots[j]); if(slot->info.allocated) { turn_session_info_add_peer(tsi,&(slot->info.addr)); struct tsi_arg arg = { tsi, &(slot->info.addr) }; lm_map_foreach_arg(&(slot->info.chns), turn_session_info_foreachcb, &arg); } } } { turn_permission_slot **slots = parray->extra_slots; if(slots) { size_t sz = parray->extra_sz; size_t j; for(j=0;j<sz;++j) { turn_permission_slot* slot = slots[j]; if(slot && slot->info.allocated) { turn_session_info_add_peer(tsi,&(slot->info.addr)); struct tsi_arg arg = { tsi, &(slot->info.addr) }; lm_map_foreach_arg(&(slot->info.chns), turn_session_info_foreachcb, &arg); } } } } } } { tcp_connection_list *tcl = &(ss->alloc.tcs); if(tcl->elems) { size_t i; size_t sz = tcl->sz; for(i=0;i<sz;++i) { if(tcl->elems[i]) { tcp_connection *tc = tcl->elems[i]; if(tc) { turn_session_info_add_peer(tsi,&(tc->peer_addr)); } } } } } } ret = 0; } return ret; } int report_turn_session_info(turn_turnserver *server, ts_ur_super_session *ss, int force_invalid) { if(server && ss && server->send_turn_session_info) { struct turn_session_info tsi; turn_session_info_init(&tsi); if(turn_session_info_copy_from(&tsi,ss)<0) { turn_session_info_clean(&tsi); } else { if(force_invalid) tsi.valid = 0; if(server->send_turn_session_info(&tsi)<0) { turn_session_info_clean(&tsi); } else { return 0; } } } return -1; } /////////// SS ///////////////// static int mobile_id_to_string(mobile_id_t mid, char *dst, size_t dst_sz) { size_t output_length = 0; if(!dst) return -1; char *s = base64_encode((const unsigned char *)&mid, sizeof(mid), &output_length); if(!s) return -1; if(!output_length || (output_length+1 > dst_sz)) { free(s); return -1; } bcopy(s, dst, output_length); free(s); dst[output_length] = 0; return (int)output_length; } static mobile_id_t string_to_mobile_id(char* src) { mobile_id_t mid = 0; if(src) { size_t output_length = 0; unsigned char *out = base64_decode(src, strlen(src), &output_length); if(out) { if(output_length == sizeof(mid)) { mid = *((mobile_id_t*)out); } free(out); } } return mid; } static mobile_id_t get_new_mobile_id(turn_turnserver* server) { mobile_id_t newid = 0; if(server && server->mobile_connections_map) { ur_map *map = server->mobile_connections_map; uint64_t sid = server->id; sid = sid<<56; do { while (!newid) { if(TURN_RANDOM_SIZE == sizeof(mobile_id_t)) newid = (mobile_id_t)turn_random(); else { newid = (mobile_id_t)turn_random(); newid = (newid<<32) + (mobile_id_t)turn_random(); } if(!newid) { continue; } newid = newid & 0x00FFFFFFFFFFFFFFLL; if(!newid) { continue; } newid = newid | sid; } } while(ur_map_get(map, (ur_map_key_type)newid, NULL)); } return newid; } static void put_session_into_mobile_map(ts_ur_super_session *ss) { if(ss && ss->server) { turn_turnserver* server = (turn_turnserver*)(ss->server); if(*(server->mobility) && server->mobile_connections_map) { if(!(ss->mobile_id)) { ss->mobile_id = get_new_mobile_id(server); mobile_id_to_string(ss->mobile_id, ss->s_mobile_id, sizeof(ss->s_mobile_id)); } ur_map_put(server->mobile_connections_map, (ur_map_key_type)(ss->mobile_id), (ur_map_value_type)ss); } } } static void put_session_into_map(ts_ur_super_session *ss) { if(ss && ss->server) { turn_turnserver* server = (turn_turnserver*)(ss->server); if(!(ss->id)) { ss->id = (turnsession_id)((turnsession_id)server->id * TURN_SESSION_ID_FACTOR); ss->id += ++(server->session_id_counter); ss->start_time = server->ctime; } ur_map_put(server->sessions_map, (ur_map_key_type)(ss->id), (ur_map_value_type)ss); put_session_into_mobile_map(ss); } } static void delete_session_from_mobile_map(ts_ur_super_session *ss) { if(ss && ss->server && ss->mobile_id) { turn_turnserver* server = (turn_turnserver*)(ss->server); if(server->mobile_connections_map) { ur_map_del(server->mobile_connections_map, (ur_map_key_type)(ss->mobile_id), NULL); } ss->mobile_id = 0; ss->s_mobile_id[0] = 0; } } static void delete_session_from_map(ts_ur_super_session *ss) { if(ss && ss->server) { turn_turnserver* server = (turn_turnserver*)(ss->server); ur_map_del(server->sessions_map, (ur_map_key_type)(ss->id), NULL); delete_session_from_mobile_map(ss); } } static ts_ur_super_session* get_session_from_map(turn_turnserver* server, turnsession_id sid) { ts_ur_super_session *ss = NULL; if(server) { ur_map_value_type value = 0; if(ur_map_get(server->sessions_map, (ur_map_key_type)sid, &value) && value) { ss = (ts_ur_super_session*)value; } } return ss; } void turn_cancel_session(turn_turnserver *server, turnsession_id sid) { if(server) { ts_ur_super_session* ts = get_session_from_map(server, sid); if(ts) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Session %018llu to be forcefully canceled\n",(unsigned long long)sid); shutdown_client_connection(server, ts, 0, "Forceful shutdown"); } } } static ts_ur_super_session* get_session_from_mobile_map(turn_turnserver* server, mobile_id_t mid) { ts_ur_super_session *ss = NULL; if(server && *(server->mobility) && server->mobile_connections_map && mid) { ur_map_value_type value = 0; if(ur_map_get(server->mobile_connections_map, (ur_map_key_type)mid, &value) && value) { ss = (ts_ur_super_session*)value; } } return ss; } static ts_ur_super_session* create_new_ss(turn_turnserver* server) { // //printf("%s: 111.111: session size=%lu\n",__FUNCTION__,(unsigned long)sizeof(ts_ur_super_session)); // ts_ur_super_session *ss = (ts_ur_super_session*)malloc(sizeof(ts_ur_super_session)); bzero(ss,sizeof(ts_ur_super_session)); ss->server = server; get_default_realm_options(&(ss->realm_options)); put_session_into_map(ss); init_allocation(ss,&(ss->alloc), server->tcp_relay_connections); return ss; } static void delete_ur_map_ss(void *p) { if (p) { ts_ur_super_session* ss = (ts_ur_super_session*) p; delete_session_from_map(ss); IOA_CLOSE_SOCKET(ss->client_socket); clear_allocation(get_allocation_ss(ss)); IOA_EVENT_DEL(ss->to_be_allocated_timeout_ev); free(p); } } /////////// clean all ///////////////////// static int turn_server_remove_all_from_ur_map_ss(ts_ur_super_session* ss) { if (!ss) return 0; else { int ret = 0; if (ss->client_socket) { clear_ioa_socket_session_if(ss->client_socket, ss); } if (get_relay_socket_ss(ss,AF_INET)) { clear_ioa_socket_session_if(get_relay_socket_ss(ss,AF_INET), ss); } if (get_relay_socket_ss(ss,AF_INET6)) { clear_ioa_socket_session_if(get_relay_socket_ss(ss,AF_INET6), ss); } delete_ur_map_ss(ss); return ret; } } ///////////////////////////////////////////////////////////////// static void client_ss_channel_timeout_handler(ioa_engine_handle e, void* arg) { UNUSED_ARG(e); if (!arg) return; ch_info* chn = (ch_info*) arg; turn_channel_delete(chn); } static void client_ss_perm_timeout_handler(ioa_engine_handle e, void* arg) { UNUSED_ARG(e); if (!arg) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "!!! %s: empty permission to be cleaned\n",__FUNCTION__); return; } turn_permission_info* tinfo = (turn_permission_info*) arg; if(!(tinfo->allocated)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "!!! %s: unallocated permission to be cleaned\n",__FUNCTION__); return; } if(!(tinfo->lifetime_ev)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "!!! %s: strange (1) permission to be cleaned\n",__FUNCTION__); } if(!(tinfo->owner)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "!!! %s: strange (2) permission to be cleaned\n",__FUNCTION__); } turn_permission_clean(tinfo); } /////////////////////////////////////////////////////////////////// static int update_turn_permission_lifetime(ts_ur_super_session *ss, turn_permission_info *tinfo, turn_time_t time_delta) { if (ss && tinfo && tinfo->owner) { turn_turnserver *server = (turn_turnserver *) (ss->server); if (server) { if(!time_delta) time_delta = *(server->permission_lifetime); tinfo->expiration_time = server->ctime + time_delta; IOA_EVENT_DEL(tinfo->lifetime_ev); tinfo->lifetime_ev = set_ioa_timer(server->e, time_delta, 0, client_ss_perm_timeout_handler, tinfo, 0, "client_ss_channel_timeout_handler"); if(server->verbose) { tinfo->verbose = 1; tinfo->session_id = ss->id; char s[257]="\0"; addr_to_string(&(tinfo->addr),(uint8_t*)s); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: peer %s lifetime updated: %lu\n",(unsigned long long)ss->id,s,(unsigned long)time_delta); } return 0; } } return -1; } static int update_channel_lifetime(ts_ur_super_session *ss, ch_info* chn) { if (chn) { turn_permission_info* tinfo = (turn_permission_info*) (chn->owner); if (tinfo && tinfo->owner) { turn_turnserver *server = (turn_turnserver *) (ss->server); if (server) { if (update_turn_permission_lifetime(ss, tinfo, *(server->channel_lifetime)) < 0) return -1; chn->expiration_time = server->ctime + *(server->channel_lifetime); IOA_EVENT_DEL(chn->lifetime_ev); chn->lifetime_ev = set_ioa_timer(server->e, *(server->channel_lifetime), 0, client_ss_channel_timeout_handler, chn, 0, "client_ss_channel_timeout_handler"); return 0; } } } return -1; } /////////////// TURN /////////////////////////// #define SKIP_ATTRIBUTES case STUN_ATTRIBUTE_OAUTH_ACCESS_TOKEN: case STUN_ATTRIBUTE_PRIORITY: case STUN_ATTRIBUTE_FINGERPRINT: case STUN_ATTRIBUTE_MESSAGE_INTEGRITY: break; \ case STUN_ATTRIBUTE_USERNAME: case STUN_ATTRIBUTE_REALM: case STUN_ATTRIBUTE_NONCE: case STUN_ATTRIBUTE_ORIGIN: \ sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh),\ ioa_network_buffer_get_size(in_buffer->nbh), sar); \ continue static uint8_t get_transport_value(const uint8_t *value) { if((value[0] == STUN_ATTRIBUTE_TRANSPORT_UDP_VALUE)|| (value[0] == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE)) { return value[0]; } return 0; } static int handle_turn_allocate(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh) { int err_code4 = 0; int err_code6 = 0; allocation* alloc = get_allocation_ss(ss); if (is_allocation_valid(alloc)) { if (!stun_tid_equals(tid, &(alloc->tid))) { *err_code = 437; *reason = (const uint8_t *)"Wrong TID"; } else { size_t len = ioa_network_buffer_get_size(nbh); ioa_addr xor_relayed_addr1, *pxor_relayed_addr1=NULL; ioa_addr xor_relayed_addr2, *pxor_relayed_addr2=NULL; ioa_addr *relayed_addr1 = get_local_addr_from_ioa_socket(get_relay_socket_ss(ss,AF_INET)); ioa_addr *relayed_addr2 = get_local_addr_from_ioa_socket(get_relay_socket_ss(ss,AF_INET6)); if(get_relay_session_failure(alloc,AF_INET)) { addr_set_any(&xor_relayed_addr1); pxor_relayed_addr1 = &xor_relayed_addr1; } else if(relayed_addr1) { if(server->external_ip_set) { addr_cpy(&xor_relayed_addr1, &(server->external_ip)); addr_set_port(&xor_relayed_addr1,addr_get_port(relayed_addr1)); } else { addr_cpy(&xor_relayed_addr1, relayed_addr1); } pxor_relayed_addr1 = &xor_relayed_addr1; } if(get_relay_session_failure(alloc,AF_INET6)) { addr_set_any(&xor_relayed_addr2); pxor_relayed_addr2 = &xor_relayed_addr2; } else if(relayed_addr2) { if(server->external_ip_set) { addr_cpy(&xor_relayed_addr2, &(server->external_ip)); addr_set_port(&xor_relayed_addr2,addr_get_port(relayed_addr2)); } else { addr_cpy(&xor_relayed_addr2, relayed_addr2); } pxor_relayed_addr2 = &xor_relayed_addr2; } if(pxor_relayed_addr1 || pxor_relayed_addr2) { uint32_t lifetime = 0; if(pxor_relayed_addr1) { lifetime = (get_relay_session(alloc,pxor_relayed_addr1->ss.sa_family)->expiration_time - server->ctime); } else if(pxor_relayed_addr2) { lifetime = (get_relay_session(alloc,pxor_relayed_addr2->ss.sa_family)->expiration_time - server->ctime); } stun_set_allocate_response_str(ioa_network_buffer_data(nbh), &len, tid, pxor_relayed_addr1, pxor_relayed_addr2, get_remote_addr_from_ioa_socket(ss->client_socket), lifetime,*(server->max_allocate_lifetime), 0, NULL, 0, ss->s_mobile_id); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } } } else { uint8_t transport = 0; turn_time_t lifetime = 0; int even_port = -1; int dont_fragment = 0; uint64_t in_reservation_token = 0; int af4 = 0; int af6 = 0; uint8_t username[STUN_MAX_USERNAME_SIZE+1]="\0"; size_t ulen = 0; band_limit_t bps = 0; band_limit_t max_bps = 0; stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); if(attr_type == STUN_ATTRIBUTE_USERNAME) { const uint8_t* value = stun_attr_get_value(sar); if (value) { ulen = stun_attr_get_len(sar); if(ulen>=sizeof(username)) { *err_code = 400; *reason = (const uint8_t *)"User name is too long"; break; } bcopy(value,username,ulen); username[ulen]=0; if(!is_secure_string(username,1)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: wrong username: %s\n", __FUNCTION__, (char*)username); username[0]=0; *err_code = 400; break; } } } switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_NEW_BANDWIDTH: bps = stun_attr_get_bandwidth(sar); break; case STUN_ATTRIBUTE_MOBILITY_TICKET: if(!(*(server->mobility))) { *err_code = 405; *reason = (const uint8_t *)"Mobility Forbidden"; } else if (stun_attr_get_len(sar) != 0) { *err_code = 400; *reason = (const uint8_t *)"Wrong Mobility Field"; } else { ss->is_mobile = 1; } break; case STUN_ATTRIBUTE_REQUESTED_TRANSPORT: { if (stun_attr_get_len(sar) != 4) { *err_code = 400; *reason = (const uint8_t *)"Wrong Transport Field"; } else if(transport) { *err_code = 400; *reason = (const uint8_t *)"Duplicate Transport Fields"; } else { const uint8_t* value = stun_attr_get_value(sar); if (value) { transport = get_transport_value(value); if (!transport) { *err_code = 442; } if((transport == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE) && *(server->no_tcp_relay)) { *err_code = 442; *reason = (const uint8_t *)"TCP Transport is not allowed by the TURN Server configuration"; } else if((transport == STUN_ATTRIBUTE_TRANSPORT_UDP_VALUE) && *(server->no_udp_relay)) { *err_code = 442; *reason = (const uint8_t *)"UDP Transport is not allowed by the TURN Server configuration"; } else if(ss->client_socket) { SOCKET_TYPE cst = get_ioa_socket_type(ss->client_socket); if((transport == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE) && !is_stream_socket(cst)) { *err_code = 400; *reason = (const uint8_t *)"Wrong Transport Data"; } else { ss->is_tcp_relay = (transport == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE); } } } else { *err_code = 400; *reason = (const uint8_t *)"Wrong Transport Data"; } } } break; case STUN_ATTRIBUTE_DONT_FRAGMENT: dont_fragment = 1; if(!(server->dont_fragment)) unknown_attrs[(*ua_num)++] = nswap16(attr_type); break; case STUN_ATTRIBUTE_LIFETIME: { if (stun_attr_get_len(sar) != 4) { *err_code = 400; *reason = (const uint8_t *)"Wrong Lifetime Field"; } else { const uint8_t* value = stun_attr_get_value(sar); if (!value) { *err_code = 400; *reason = (const uint8_t *)"Wrong Lifetime Data"; } else { lifetime = nswap32(*((const uint32_t*)value)); } } } break; case STUN_ATTRIBUTE_EVEN_PORT: { if (in_reservation_token) { *err_code = 400; *reason = (const uint8_t *)"Even Port and Reservation Token cannot be used together"; } else { even_port = stun_attr_get_even_port(sar); if(even_port) { if (af4 && af6) { *err_code = 400; *reason = (const uint8_t *)"Even Port cannot be used with Dual Allocation"; } } } } break; case STUN_ATTRIBUTE_RESERVATION_TOKEN: { int len = stun_attr_get_len(sar); if (len != 8) { *err_code = 400; *reason = (const uint8_t *)"Wrong Format of Reservation Token"; } else if(af4 || af6) { *err_code = 400; *reason = (const uint8_t *)"Address family attribute can not be used with reservation token request"; } else { if (even_port >= 0) { *err_code = 400; *reason = (const uint8_t *)"Reservation Token cannot be used in this request with even port"; } else if (in_reservation_token) { *err_code = 400; *reason = (const uint8_t *)"Reservation Token cannot be used in this request"; } else { in_reservation_token = stun_attr_get_reservation_token_value(sar); } } } break; case STUN_ATTRIBUTE_ADDITIONAL_ADDRESS_FAMILY: if(even_port>0) { *err_code = 400; *reason = (const uint8_t *)"Even Port cannot be used with Dual Allocation"; break; } /* Falls through. */ case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY: { if(in_reservation_token) { *err_code = 400; *reason = (const uint8_t *)"Address family attribute can not be used with reservation token request"; } else if(af4 || af6) { *err_code = 400; *reason = (const uint8_t *)"Extra address family attribute can not be used in the request"; } else { int af_req = stun_get_requested_address_family(sar); switch (af_req) { case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4: if(attr_type == STUN_ATTRIBUTE_ADDITIONAL_ADDRESS_FAMILY) { *err_code = 400; *reason = (const uint8_t *)"Invalid value of the additional address family attribute"; } else { af4 = af_req; } break; case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6: if(attr_type == STUN_ATTRIBUTE_ADDITIONAL_ADDRESS_FAMILY) { af4 = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4; } af6 = af_req; break; default: *err_code = 440; } } } break; default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if (!transport) { *err_code = 400; if(!(*reason)) *reason = (const uint8_t *)"Transport field missed or wrong"; } else if (*ua_num > 0) { *err_code = 420; } else if (*err_code) { ; } else if((transport == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE) && (dont_fragment || in_reservation_token || (even_port!=-1))) { *err_code = 400; if(!(*reason)) *reason = (const uint8_t *)"Request parameters are incompatible with TCP transport"; } else { if(*(server->mobility)) { if(!(ss->is_mobile)) { delete_session_from_mobile_map(ss); } } lifetime = stun_adjust_allocate_lifetime(lifetime, *(server->max_allocate_lifetime), ss->max_session_time_auth); uint64_t out_reservation_token = 0; if(inc_quota(ss, username)<0) { *err_code = 486; } else { if(server->allocate_bps_func) { max_bps = ss->realm_options.perf_options.max_bps; if(max_bps && (!bps || (bps && (bps>max_bps)))) { bps = max_bps; } if(bps && (ss->bps == 0)) { ss->bps = server->allocate_bps_func(bps,1); if(!(ss->bps)) { *err_code = 486; *reason = (const uint8_t *)"Allocation Bandwidth Quota Reached"; } } } if(af4) af4 = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4; if(af6) af6 = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6; if(af4 && af6) { if(server->external_ip_set) { *err_code = 440; *reason = (const uint8_t *)"Dual allocation cannot be supported in the current server configuration"; } if(even_port > 0) { *err_code = 440; *reason = (const uint8_t *)"Dual allocation cannot be supported with even-port functionality"; } } if(!(*err_code)) { if(!af4 && !af6) { int a_family = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_DEFAULT; if (server->keep_address_family) { switch(get_ioa_socket_address_family(ss->client_socket)) { case AF_INET6 : a_family = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6; break; case AF_INET : a_family = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4; break; } } int res = create_relay_connection(server, ss, lifetime, a_family, transport, even_port, in_reservation_token, &out_reservation_token, err_code, reason, tcp_peer_accept_connection); if(res<0) { set_relay_session_failure(alloc,AF_INET); if(!(*err_code)) { *err_code = 437; } } } else if(!af4 && af6) { int af6res = create_relay_connection(server, ss, lifetime, af6, transport, even_port, in_reservation_token, &out_reservation_token, err_code, reason, tcp_peer_accept_connection); if(af6res<0) { set_relay_session_failure(alloc,AF_INET6); if(!(*err_code)) { *err_code = 437; } } } else if(af4 && !af6) { int af4res = create_relay_connection(server, ss, lifetime, af4, transport, even_port, in_reservation_token, &out_reservation_token, err_code, reason, tcp_peer_accept_connection); if(af4res<0) { set_relay_session_failure(alloc,AF_INET); if(!(*err_code)) { *err_code = 437; } } } else { const uint8_t *reason4 = NULL; const uint8_t *reason6 = NULL; { int af4res = create_relay_connection(server, ss, lifetime, af4, transport, even_port, in_reservation_token, &out_reservation_token, &err_code4, &reason4, tcp_peer_accept_connection); if(af4res<0) { set_relay_session_failure(alloc,AF_INET); if(!err_code4) { err_code4 = 440; } } } { int af6res = create_relay_connection(server, ss, lifetime, af6, transport, even_port, in_reservation_token, &out_reservation_token, &err_code6, &reason6, tcp_peer_accept_connection); if(af6res<0) { set_relay_session_failure(alloc,AF_INET6); if(!err_code6) { err_code6 = 440; } } } if(err_code4 && err_code6) { if(reason4) { *err_code = err_code4; *reason = reason4; } else if(reason6) { *err_code = err_code6; *reason = reason6; } else { *err_code = err_code4; } } } } if (*err_code) { if(!(*reason)) { *reason = (const uint8_t *)"Cannot create relay endpoint(s)"; } } else { set_allocation_valid(alloc,1); stun_tid_cpy(&(alloc->tid), tid); size_t len = ioa_network_buffer_get_size(nbh); ioa_addr xor_relayed_addr1, *pxor_relayed_addr1=NULL; ioa_addr xor_relayed_addr2, *pxor_relayed_addr2=NULL; ioa_addr *relayed_addr1 = get_local_addr_from_ioa_socket(get_relay_socket_ss(ss,AF_INET)); ioa_addr *relayed_addr2 = get_local_addr_from_ioa_socket(get_relay_socket_ss(ss,AF_INET6)); if(get_relay_session_failure(alloc,AF_INET)) { addr_set_any(&xor_relayed_addr1); pxor_relayed_addr1 = &xor_relayed_addr1; } else if(relayed_addr1) { if(server->external_ip_set) { addr_cpy(&xor_relayed_addr1, &(server->external_ip)); addr_set_port(&xor_relayed_addr1,addr_get_port(relayed_addr1)); } else { addr_cpy(&xor_relayed_addr1, relayed_addr1); } pxor_relayed_addr1 = &xor_relayed_addr1; } if(get_relay_session_failure(alloc,AF_INET6)) { addr_set_any(&xor_relayed_addr2); pxor_relayed_addr2 = &xor_relayed_addr2; } else if(relayed_addr2) { if(server->external_ip_set) { addr_cpy(&xor_relayed_addr2, &(server->external_ip)); addr_set_port(&xor_relayed_addr2,addr_get_port(relayed_addr2)); } else { addr_cpy(&xor_relayed_addr2, relayed_addr2); } pxor_relayed_addr2 = &xor_relayed_addr2; } if(pxor_relayed_addr1 || pxor_relayed_addr2) { stun_set_allocate_response_str(ioa_network_buffer_data(nbh), &len, tid, pxor_relayed_addr1, pxor_relayed_addr2, get_remote_addr_from_ioa_socket(ss->client_socket), lifetime, *(server->max_allocate_lifetime),0,NULL, out_reservation_token, ss->s_mobile_id); if(ss->bps) { stun_attr_add_bandwidth_str(ioa_network_buffer_data(nbh), &len, ss->bps); } ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; turn_report_allocation_set(&(ss->alloc), lifetime, 0); } } } } } if (!(*resp_constructed)) { if (!(*err_code)) { *err_code = 437; } size_t len = ioa_network_buffer_get_size(nbh); stun_set_allocate_response_str(ioa_network_buffer_data(nbh), &len, tid, NULL, NULL, NULL, 0, *(server->max_allocate_lifetime), *err_code, *reason, 0, ss->s_mobile_id); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } if(*resp_constructed && !(*err_code)) { if(err_code4) { size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_address_error_code(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4, err_code4); ioa_network_buffer_set_size(nbh,len); } if(err_code6) { size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_address_error_code(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6, err_code6); ioa_network_buffer_set_size(nbh,len); } } return 0; } static void copy_auth_parameters(ts_ur_super_session *orig_ss, ts_ur_super_session *ss) { if(orig_ss && ss) { dec_quota(ss); bcopy(orig_ss->nonce,ss->nonce,sizeof(ss->nonce)); ss->nonce_expiration_time = orig_ss->nonce_expiration_time; bcopy(&(orig_ss->realm_options),&(ss->realm_options),sizeof(ss->realm_options)); bcopy(orig_ss->username,ss->username,sizeof(ss->username)); ss->hmackey_set = orig_ss->hmackey_set; bcopy(orig_ss->hmackey,ss->hmackey,sizeof(ss->hmackey)); ss->oauth = orig_ss->oauth; bcopy(orig_ss->origin,ss->origin,sizeof(ss->origin)); ss->origin_set = orig_ss->origin_set; bcopy(orig_ss->pwd,ss->pwd,sizeof(ss->pwd)); ss->max_session_time_auth = orig_ss->max_session_time_auth; inc_quota(ss,ss->username); } } static int handle_turn_refresh(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh, int message_integrity, int *no_response, int can_resume) { allocation* a = get_allocation_ss(ss); int af4c = 0; int af6c = 0; int af4 = 0; int af6 = 0; { int i; for(i = 0;i<ALLOC_PROTOCOLS_NUMBER; ++i) { if(a->relay_sessions[i].s && !ioa_socket_tobeclosed(a->relay_sessions[i].s)) { int family = get_ioa_socket_address_family(a->relay_sessions[i].s); if(AF_INET == family) { af4c = 1; } else if(AF_INET6 == family) { af6c = 1; } } } } if (!is_allocation_valid(a) && !(*(server->mobility))) { *err_code = 437; *reason = (const uint8_t *)"Invalid allocation"; } else { turn_time_t lifetime = 0; int to_delete = 0; mobile_id_t mid = 0; char smid[sizeof(ss->s_mobile_id)] = "\0"; stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_MOBILITY_TICKET: { if(!(*(server->mobility))) { *err_code = 405; *reason = (const uint8_t *)"Mobility forbidden"; } else { int smid_len = stun_attr_get_len(sar); if(smid_len>0 && (((size_t)smid_len)<sizeof(smid))) { const uint8_t* smid_val = stun_attr_get_value(sar); if(smid_val) { bcopy(smid_val, smid, (size_t)smid_len); mid = string_to_mobile_id(smid); if(is_allocation_valid(a) && (mid != ss->old_mobile_id)) { *err_code = 400; *reason = (const uint8_t *)"Mobility ticket cannot be used for a stable, already established allocation"; } } } else { *err_code = 400; *reason = (const uint8_t *)"Mobility ticket has wrong length"; } } } break; case STUN_ATTRIBUTE_LIFETIME: { if (stun_attr_get_len(sar) != 4) { *err_code = 400; *reason = (const uint8_t *)"Wrong Lifetime field format"; } else { const uint8_t* value = stun_attr_get_value(sar); if (!value) { *err_code = 400; *reason = (const uint8_t *)"Wrong lifetime field data"; } else { lifetime = nswap32(*((const uint32_t*)value)); if (!lifetime) to_delete = 1; } } } break; case STUN_ATTRIBUTE_ADDITIONAL_ADDRESS_FAMILY: /* deprecated, for backward compatibility with older versions of TURN-bis */ case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY: { int af_req = stun_get_requested_address_family(sar); { int is_err = 0; switch (af_req) { case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4: if(!af4c) { is_err = 1; } else { af4 = 1; } break; case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6: if(!af6c) { is_err = 1; } else { af6 = 1; } break; default: is_err = 1; } if(is_err) { *err_code = 443; *reason = (const uint8_t *)"Peer Address Family Mismatch (1)"; } } } break; default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if (*ua_num > 0) { *err_code = 420; } else if (*err_code) { ; } else if(!is_allocation_valid(a)) { if(mid && smid[0]) { turnserver_id tsid = ((0xFF00000000000000LL) & mid)>>56; if(tsid != server->id) { if(server->send_socket_to_relay) { ioa_socket_handle new_s = detach_ioa_socket(ss->client_socket); if(new_s) { if(server->send_socket_to_relay(tsid, mid, tid, new_s, message_integrity, RMT_MOBILE_SOCKET, in_buffer, can_resume)<0) { *err_code = 400; *reason = (const uint8_t *)"Wrong mobile ticket"; } else { *no_response = 1; } } else { *err_code = 500; *reason = (const uint8_t *)"Cannot create new socket"; return -1; } } else { *err_code = 500; *reason = (const uint8_t *)"Server send socket procedure is not set"; } ss->to_be_closed = 1; } else { ts_ur_super_session *orig_ss = get_session_from_mobile_map(server, mid); if(!orig_ss || orig_ss->to_be_closed || ioa_socket_tobeclosed(orig_ss->client_socket)) { *err_code = 404; *reason = (const uint8_t *)"Allocation not found"; } else if(orig_ss == ss) { *err_code = 437; *reason = (const uint8_t *)"Invalid allocation"; } else if(!(orig_ss->is_mobile)) { *err_code = 500; *reason = (const uint8_t *)"Software error: invalid mobile allocation"; } else if(orig_ss->client_socket == ss->client_socket) { *err_code = 500; *reason = (const uint8_t *)"Software error: invalid mobile client socket (orig)"; } else if(!(ss->client_socket)) { *err_code = 500; *reason = (const uint8_t *)"Software error: invalid mobile client socket (new)"; } else { get_realm_options_by_name(orig_ss->realm_options.name, &(ss->realm_options)); //Check security: int postpone_reply = 0; if(!(ss->hmackey_set)) { copy_auth_parameters(orig_ss,ss); } if(check_stun_auth(server, ss, tid, resp_constructed, err_code, reason, in_buffer, nbh, STUN_METHOD_REFRESH, &message_integrity, &postpone_reply, can_resume)<0) { if(!(*err_code)) { *err_code = 401; } } if(postpone_reply) { *no_response = 1; } else if(!(*err_code)) { //Session transfer: if (to_delete) lifetime = 0; else { lifetime = stun_adjust_allocate_lifetime(lifetime, *(server->max_allocate_lifetime), ss->max_session_time_auth); } if (af4c && refresh_relay_connection(server, orig_ss, lifetime, 0, 0, 0, err_code, AF_INET) < 0) { if (!(*err_code)) { *err_code = 437; *reason = (const uint8_t *)"Cannot refresh relay connection (internal error)"; } } else if (af6c && refresh_relay_connection(server, orig_ss, lifetime, 0, 0, 0, err_code, AF_INET6) < 0) { if (!(*err_code)) { *err_code = 437; *reason = (const uint8_t *)"Cannot refresh relay connection (internal error)"; } } else { //Transfer socket: ioa_socket_handle s = detach_ioa_socket(ss->client_socket); ss->to_be_closed = 1; if(!s) { *err_code = 500; } else { if(attach_socket_to_session(server, s, orig_ss) < 0) { if(orig_ss->client_socket != s) { IOA_CLOSE_SOCKET(s); } *err_code = 500; } else { if(ss->hmackey_set) { copy_auth_parameters(ss,orig_ss); } delete_session_from_mobile_map(ss); delete_session_from_mobile_map(orig_ss); put_session_into_mobile_map(orig_ss); //Use new buffer and redefine ss: nbh = ioa_network_buffer_allocate(server->e); dec_quota(ss); ss = orig_ss; inc_quota(ss,ss->username); ss->old_mobile_id = mid; size_t len = ioa_network_buffer_get_size(nbh); turn_report_allocation_set(&(ss->alloc), lifetime, 1); stun_init_success_response_str(STUN_METHOD_REFRESH, ioa_network_buffer_data(nbh), &len, tid); uint32_t lt = nswap32(lifetime); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_LIFETIME, (const uint8_t*) &lt, 4); ioa_network_buffer_set_size(nbh,len); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_MOBILITY_TICKET, (uint8_t*)ss->s_mobile_id,strlen(ss->s_mobile_id)); ioa_network_buffer_set_size(nbh,len); { const uint8_t *field = (const uint8_t *) get_version(server); size_t fsz = strlen(get_version(server)); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_SOFTWARE, field, fsz); ioa_network_buffer_set_size(nbh, len); } if(message_integrity) { stun_attr_add_integrity_str(server->ct,ioa_network_buffer_data(nbh),&len,ss->hmackey,ss->pwd,SHATYPE_DEFAULT); ioa_network_buffer_set_size(nbh,len); } if ((server->fingerprint) || ss->enforce_fingerprints) { if (stun_attr_add_fingerprint_str(ioa_network_buffer_data(nbh), &len) < 0) { *err_code = 500; ioa_network_buffer_delete(server->e, nbh); return -1; } ioa_network_buffer_set_size(nbh, len); } *no_response = 1; return write_client_connection(server, ss, nbh, TTL_IGNORE, TOS_IGNORE); } } } } report_turn_session_info(server,orig_ss,0); } } } else { *err_code = 437; *reason = (const uint8_t *)"Invalid allocation"; } } else { if (to_delete) lifetime = 0; else { lifetime = stun_adjust_allocate_lifetime(lifetime, *(server->max_allocate_lifetime), ss->max_session_time_auth); } if(!af4 && !af6) { af4 = af4c; af6 = af6c; } if (af4 && refresh_relay_connection(server, ss, lifetime, 0, 0, 0, err_code, AF_INET) < 0) { if (!(*err_code)) { *err_code = 437; *reason = (const uint8_t *)"Cannot refresh relay connection (internal error)"; } } else if (af6 && refresh_relay_connection(server, ss, lifetime, 0, 0, 0, err_code, AF_INET6) < 0) { if (!(*err_code)) { *err_code = 437; *reason = (const uint8_t *)"Cannot refresh relay connection (internal error)"; } } else { turn_report_allocation_set(&(ss->alloc), lifetime, 1); size_t len = ioa_network_buffer_get_size(nbh); stun_init_success_response_str(STUN_METHOD_REFRESH, ioa_network_buffer_data(nbh), &len, tid); if(ss->s_mobile_id[0]) { stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_MOBILITY_TICKET, (uint8_t*)ss->s_mobile_id,strlen(ss->s_mobile_id)); ioa_network_buffer_set_size(nbh,len); } uint32_t lt = nswap32(lifetime); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_LIFETIME, (const uint8_t*) &lt, 4); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } } } if(!no_response) { if (!(*resp_constructed)) { if (!(*err_code)) { *err_code = 437; } size_t len = ioa_network_buffer_get_size(nbh); stun_init_error_response_str(STUN_METHOD_REFRESH, ioa_network_buffer_data(nbh), &len, *err_code, *reason, tid); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } } return 0; } /* RFC 6062 ==>> */ static void tcp_deliver_delayed_buffer(unsent_buffer *ub, ioa_socket_handle s, ts_ur_super_session *ss) { if(ub && s && ub->bufs && ub->sz && ss) { size_t i = 0; do { ioa_network_buffer_handle nbh = top_unsent_buffer(ub); if(!nbh) break; uint32_t bytes = (uint32_t)ioa_network_buffer_get_size(nbh); int ret = send_data_from_ioa_socket_nbh(s, NULL, nbh, TTL_IGNORE, TOS_IGNORE, NULL); if (ret < 0) { set_ioa_socket_tobeclosed(s); } else { ++(ss->sent_packets); ss->sent_bytes += bytes; turn_report_session_usage(ss, 0); } pop_unsent_buffer(ub); } while(!ioa_socket_tobeclosed(s) && ((i++)<MAX_UNSENT_BUFFER_SIZE)); } } static void tcp_peer_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *in_buffer, void *arg, int can_resume) { if (!(event_type & IOA_EV_READ) || !arg) return; UNUSED_ARG(s); UNUSED_ARG(can_resume); tcp_connection *tc = (tcp_connection*)arg; ts_ur_super_session *ss=NULL; allocation *a=(allocation*)tc->owner; if(a) { ss=(ts_ur_super_session*)a->owner; } if((tc->state != TC_STATE_READY) || !(tc->client_s)) { add_unsent_buffer(&(tc->ub_to_client), in_buffer->nbh); in_buffer->nbh = NULL; return; } ioa_network_buffer_handle nbh = in_buffer->nbh; in_buffer->nbh = NULL; uint32_t bytes = (uint32_t)ioa_network_buffer_get_size(nbh); if (ss) { ++(ss->peer_received_packets); ss->peer_received_bytes += bytes; } int ret = send_data_from_ioa_socket_nbh(tc->client_s, NULL, nbh, TTL_IGNORE, TOS_IGNORE, NULL); if (ret < 0) { set_ioa_socket_tobeclosed(s); } else if(ss) { ++(ss->sent_packets); ss->sent_bytes += bytes; } if (ss) { turn_report_session_usage(ss, 0); } } static void tcp_client_input_handler_rfc6062data(ioa_socket_handle s, int event_type, ioa_net_data *in_buffer, void *arg, int can_resume) { if (!(event_type & IOA_EV_READ) || !arg) return; UNUSED_ARG(s); UNUSED_ARG(can_resume); tcp_connection *tc = (tcp_connection*)arg; ts_ur_super_session *ss=NULL; allocation *a=(allocation*)tc->owner; if(a) { ss=(ts_ur_super_session*)a->owner; } if(tc->state != TC_STATE_READY) return; if(!(tc->peer_s)) return; ioa_network_buffer_handle nbh = in_buffer->nbh; in_buffer->nbh = NULL; uint32_t bytes = (uint32_t)ioa_network_buffer_get_size(nbh); if(ss) { ++(ss->received_packets); ss->received_bytes += bytes; } int skip = 0; int ret = send_data_from_ioa_socket_nbh(tc->peer_s, NULL, nbh, TTL_IGNORE, TOS_IGNORE, &skip); if (ret < 0) { set_ioa_socket_tobeclosed(s); } if (!skip && ss) { ++(ss->peer_sent_packets); ss->peer_sent_bytes += bytes; } if(ss) turn_report_session_usage(ss, 0); } static void tcp_conn_bind_timeout_handler(ioa_engine_handle e, void *arg) { UNUSED_ARG(e); if(arg) { tcp_connection *tc = (tcp_connection *)arg; delete_tcp_connection(tc); } } static void tcp_peer_connection_completed_callback(int success, void *arg) { if(arg) { tcp_connection *tc = (tcp_connection *)arg; allocation *a = (allocation*)(tc->owner); ts_ur_super_session *ss = (ts_ur_super_session*)(a->owner); turn_turnserver *server=(turn_turnserver*)(ss->server); int err_code = 0; IOA_EVENT_DEL(tc->peer_conn_timeout); ioa_network_buffer_handle nbh = ioa_network_buffer_allocate(server->e); size_t len = ioa_network_buffer_get_size(nbh); if(success) { if(register_callback_on_ioa_socket(server->e, tc->peer_s, IOA_EV_READ, tcp_peer_input_handler, tc, 1)<0) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: cannot set TCP peer data input callback\n", __FUNCTION__); success=0; err_code = 500; } } if(success) { tc->state = TC_STATE_PEER_CONNECTED; stun_init_success_response_str(STUN_METHOD_CONNECT, ioa_network_buffer_data(nbh), &len, &(tc->tid)); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_CONNECTION_ID, (const uint8_t*)&(tc->id), 4); IOA_EVENT_DEL(tc->conn_bind_timeout); tc->conn_bind_timeout = set_ioa_timer(server->e, TCP_CONN_BIND_TIMEOUT, 0, tcp_conn_bind_timeout_handler, tc, 0, "tcp_conn_bind_timeout_handler"); } else { tc->state = TC_STATE_FAILED; if(!err_code) { err_code = 447; } { char ls[257]="\0"; char rs[257]="\0"; ioa_addr *laddr = get_local_addr_from_ioa_socket(ss->client_socket); if(laddr) addr_to_string(laddr,(uint8_t*)ls); addr_to_string(&(tc->peer_addr),(uint8_t*)rs); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: failure to connect from %s to %s\n", __FUNCTION__, ls,rs); } stun_init_error_response_str(STUN_METHOD_CONNECT, ioa_network_buffer_data(nbh), &len, err_code, NULL, &(tc->tid)); } ioa_network_buffer_set_size(nbh,len); if(need_stun_authentication(server, ss)) { stun_attr_add_integrity_str(server->ct,ioa_network_buffer_data(nbh),&len,ss->hmackey,ss->pwd,SHATYPE_DEFAULT); ioa_network_buffer_set_size(nbh,len); } write_client_connection(server, ss, nbh, TTL_IGNORE, TOS_IGNORE); if(!success) { delete_tcp_connection(tc); } /* test */ else if(0) { int i = 0; for(i=0;i<22;i++) { ioa_network_buffer_handle nbh_test = ioa_network_buffer_allocate(server->e); size_t len_test = ioa_network_buffer_get_size(nbh_test); uint8_t *data = ioa_network_buffer_data(nbh_test); const char* data_test="111.111.111.111.111"; len_test = strlen(data_test); bcopy(data_test,data,len_test); ioa_network_buffer_set_size(nbh_test,len_test); send_data_from_ioa_socket_nbh(tc->peer_s, NULL, nbh_test, TTL_IGNORE, TOS_IGNORE, NULL); } } } } static void tcp_peer_conn_timeout_handler(ioa_engine_handle e, void *arg) { UNUSED_ARG(e); tcp_peer_connection_completed_callback(0,arg); } static int tcp_start_connection_to_peer(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, allocation *a, ioa_addr *peer_addr, int *err_code, const uint8_t **reason) { FUNCSTART; if(!ss) { *err_code = 500; *reason = (const uint8_t *)"Server error: empty session"; FUNCEND; return -1; } if(!peer_addr) { *err_code = 500; *reason = (const uint8_t *)"Server error: empty peer addr"; FUNCEND; return -1; } if(!get_relay_socket(a,peer_addr->ss.sa_family)) { *err_code = 500; *reason = (const uint8_t *)"Server error: no relay connection created"; FUNCEND; return -1; } tcp_connection *tc = get_tcp_connection_by_peer(a, peer_addr); if(tc) { *err_code = 446; FUNCEND; return -1; } tc = create_tcp_connection(server->id, a, tid, peer_addr, err_code); if(!tc) { if(!(*err_code)) { *err_code = 500; *reason = (const uint8_t *)"Server error: TCP connection object creation failed"; } FUNCEND; return -1; } else if(*err_code) { delete_tcp_connection(tc); FUNCEND; return -1; } IOA_EVENT_DEL(tc->peer_conn_timeout); tc->peer_conn_timeout = set_ioa_timer(server->e, TCP_PEER_CONN_TIMEOUT, 0, tcp_peer_conn_timeout_handler, tc, 0, "tcp_peer_conn_timeout_handler"); ioa_socket_handle tcs = ioa_create_connecting_tcp_relay_socket(get_relay_socket(a,peer_addr->ss.sa_family), peer_addr, tcp_peer_connection_completed_callback, tc); if(!tcs) { delete_tcp_connection(tc); *err_code = 500; *reason = (const uint8_t *)"Server error: TCP relay socket for connection cannot be created"; FUNCEND; return -1; } tc->state = TC_STATE_CLIENT_TO_PEER_CONNECTING; if(tc->peer_s != tcs) { IOA_CLOSE_SOCKET(tc->peer_s); tc->peer_s = tcs; } set_ioa_socket_sub_session(tc->peer_s,tc); FUNCEND; return 0; } static void tcp_peer_accept_connection(ioa_socket_handle s, void *arg) { if(s) { if(!arg) { close_ioa_socket(s); return; } ts_ur_super_session *ss = (ts_ur_super_session*)arg; turn_turnserver *server=(turn_turnserver*)(ss->server); FUNCSTART; allocation *a = &(ss->alloc); ioa_addr *peer_addr = get_remote_addr_from_ioa_socket(s); if(!peer_addr) { close_ioa_socket(s); FUNCEND; return; } tcp_connection *tc = get_tcp_connection_by_peer(a, peer_addr); if(tc) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: peer data socket with this address already exist\n", __FUNCTION__); if(tc->peer_s != s) close_ioa_socket(s); FUNCEND; return; } if(!good_peer_addr(server, ss->realm_options.name, peer_addr)) { uint8_t saddr[256]; addr_to_string(peer_addr, saddr); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: an attempt to connect from a peer with forbidden address: %s\n", __FUNCTION__,saddr); close_ioa_socket(s); FUNCEND; return; } if(!can_accept_tcp_connection_from_peer(a,peer_addr,server->server_relay)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: peer has no permission to connect\n", __FUNCTION__); close_ioa_socket(s); FUNCEND; return; } stun_tid tid; bzero(&tid,sizeof(stun_tid)); int err_code=0; tc = create_tcp_connection(server->id, a, &tid, peer_addr, &err_code); if(!tc) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: cannot create TCP connection\n", __FUNCTION__); close_ioa_socket(s); FUNCEND; return; } tc->state = TC_STATE_PEER_CONNECTED; tc->peer_s = s; set_ioa_socket_session(s,ss); set_ioa_socket_sub_session(s,tc); if(register_callback_on_ioa_socket(server->e, s, IOA_EV_READ, tcp_peer_input_handler, tc, 1)<0) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: cannot set TCP peer data input callback\n", __FUNCTION__); IOA_CLOSE_SOCKET(tc->peer_s); tc->state = TC_STATE_UNKNOWN; FUNCEND; return; } IOA_EVENT_DEL(tc->conn_bind_timeout); tc->conn_bind_timeout = set_ioa_timer(server->e, TCP_CONN_BIND_TIMEOUT, 0, tcp_conn_bind_timeout_handler, tc, 0, "tcp_conn_bind_timeout_handler"); ioa_network_buffer_handle nbh = ioa_network_buffer_allocate(server->e); size_t len = ioa_network_buffer_get_size(nbh); stun_init_indication_str(STUN_METHOD_CONNECTION_ATTEMPT, ioa_network_buffer_data(nbh), &len); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_CONNECTION_ID, (const uint8_t*)&(tc->id), 4); stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, peer_addr); ioa_network_buffer_set_size(nbh,len); { const uint8_t *field = (const uint8_t *) get_version(server); size_t fsz = strlen(get_version(server)); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_SOFTWARE, field, fsz); ioa_network_buffer_set_size(nbh, len); } if ((server->fingerprint) || ss->enforce_fingerprints) { size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_fingerprint_str(ioa_network_buffer_data(nbh), &len); ioa_network_buffer_set_size(nbh, len); } write_client_connection(server, ss, nbh, TTL_IGNORE, TOS_IGNORE); FUNCEND; } } static int handle_turn_connect(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer) { FUNCSTART; ioa_addr peer_addr; int peer_found = 0; addr_set_any(&peer_addr); allocation* a = get_allocation_ss(ss); if(!(ss->is_tcp_relay)) { *err_code = 403; *reason = (const uint8_t *)"Connect cannot be used with UDP relay"; } else if (!is_allocation_valid(a)) { *err_code = 437; } else { stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_XOR_PEER_ADDRESS: { if(stun_attr_get_addr_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar, &peer_addr, NULL) == -1) { *err_code = 400; *reason = (const uint8_t *)"Bad Peer Address"; } else { if(!get_relay_socket(a,peer_addr.ss.sa_family)) { *err_code = 443; *reason = (const uint8_t *)"Peer Address Family Mismatch (2)"; } peer_found = 1; } break; } default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if (*ua_num > 0) { *err_code = 420; } else if (*err_code) { ; } else if (!peer_found) { *err_code = 400; *reason = (const uint8_t *)"Where is Peer Address ?"; } else { if(!good_peer_addr(server,ss->realm_options.name,&peer_addr)) { *err_code = 403; *reason = (const uint8_t *) "Forbidden IP"; } else { tcp_start_connection_to_peer(server, ss, tid, a, &peer_addr, err_code, reason); } } } FUNCEND; return 0; } static int handle_turn_connection_bind(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh, int message_integrity, int can_resume) { allocation* a = get_allocation_ss(ss); uint16_t method = STUN_METHOD_CONNECTION_BIND; if(ss->to_be_closed) { *err_code = 400; } else if (is_allocation_valid(a)) { *err_code = 400; *reason = (const uint8_t *)"Bad request: CONNECTION_BIND cannot be issued after allocation"; } else if(!is_stream_socket(get_ioa_socket_type(ss->client_socket))) { *err_code = 400; *reason = (const uint8_t *)"Bad request: CONNECTION_BIND only possible with TCP/TLS"; } else { tcp_connection_id id = 0; stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_CONNECTION_ID: { if (stun_attr_get_len(sar) != 4) { *err_code = 400; *reason = (const uint8_t *)"Wrong Connection ID field format"; } else { const uint8_t* value = stun_attr_get_value(sar); if (!value) { *err_code = 400; *reason = (const uint8_t *)"Wrong Connection ID field data"; } else { id = *((const uint32_t*)value); //AS-IS encoding, no conversion to/from network byte order } } } break; default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if (*ua_num > 0) { *err_code = 420; } else if (*err_code) { ; } else { if(server->send_socket_to_relay) { turnserver_id sid = (id & 0xFF000000)>>24; ioa_socket_handle s = ss->client_socket; if(s && !ioa_socket_tobeclosed(s)) { ioa_socket_handle new_s = detach_ioa_socket(s); if(new_s) { if(server->send_socket_to_relay(sid, id, tid, new_s, message_integrity, RMT_CB_SOCKET, in_buffer, can_resume)<0) { *err_code = 400; *reason = (const uint8_t *)"Wrong connection id"; } } else { *err_code = 500; } } else { *err_code = 500; } } else { *err_code = 500; } ss->to_be_closed = 1; } } if (!(*resp_constructed) && ss->client_socket && !ioa_socket_tobeclosed(ss->client_socket)) { if (!(*err_code)) { *err_code = 437; } size_t len = ioa_network_buffer_get_size(nbh); stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, *err_code, *reason, tid); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } return 0; } int turnserver_accept_tcp_client_data_connection(turn_turnserver *server, tcp_connection_id tcid, stun_tid *tid, ioa_socket_handle s, int message_integrity, ioa_net_data *in_buffer, int can_resume) { if(!server) return -1; FUNCSTART; tcp_connection *tc = NULL; ts_ur_super_session *ss = NULL; int err_code = 0; const uint8_t *reason = NULL; ioa_socket_handle s_to_delete = s; if(tcid && tid && s) { tc = get_tcp_connection_by_id(server->tcp_relay_connections, tcid); ioa_network_buffer_handle nbh = ioa_network_buffer_allocate(server->e); int resp_constructed = 0; if(!tc || (tc->state == TC_STATE_READY) || (tc->client_s)) { err_code = 400; } else { allocation *a = (allocation*)(tc->owner); if(!a || !(a->owner)) { err_code = 500; } else { ss = (ts_ur_super_session*)(a->owner); if(ss->to_be_closed || ioa_socket_tobeclosed(ss->client_socket)) { err_code = 404; } else { //Check security: int postpone_reply = 0; check_stun_auth(server, ss, tid, &resp_constructed, &err_code, &reason, in_buffer, nbh, STUN_METHOD_CONNECTION_BIND, &message_integrity, &postpone_reply, can_resume); if(postpone_reply) { ioa_network_buffer_delete(server->e, nbh); return 0; } else if(!err_code) { tc->state = TC_STATE_READY; tc->client_s = s; s_to_delete = NULL; set_ioa_socket_session(s,ss); set_ioa_socket_sub_session(s,tc); set_ioa_socket_app_type(s,TCP_CLIENT_DATA_SOCKET); if(register_callback_on_ioa_socket(server->e, s, IOA_EV_READ, tcp_client_input_handler_rfc6062data, tc, 1)<0) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: cannot set TCP client data input callback\n", __FUNCTION__); err_code = 500; } else { IOA_EVENT_DEL(tc->conn_bind_timeout); } } } } } if(tc) get_and_clean_tcp_connection_by_id(server->tcp_relay_connections, tcid); if(!resp_constructed) { if(!err_code) { size_t len = ioa_network_buffer_get_size(nbh); stun_init_success_response_str(STUN_METHOD_CONNECTION_BIND, ioa_network_buffer_data(nbh), &len, tid); ioa_network_buffer_set_size(nbh,len); } else { size_t len = ioa_network_buffer_get_size(nbh); stun_init_error_response_str(STUN_METHOD_CONNECTION_BIND, ioa_network_buffer_data(nbh), &len, err_code, NULL, tid); ioa_network_buffer_set_size(nbh,len); } } { size_t fsz = strlen(get_version(server)); const uint8_t *field = (const uint8_t *) get_version(server); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_SOFTWARE, field, fsz); ioa_network_buffer_set_size(nbh, len); } if(message_integrity && ss) { size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_integrity_str(server->ct,ioa_network_buffer_data(nbh),&len,ss->hmackey,ss->pwd,SHATYPE_DEFAULT); ioa_network_buffer_set_size(nbh,len); } if ((server->fingerprint) || (ss &&(ss->enforce_fingerprints))) { size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_fingerprint_str(ioa_network_buffer_data(nbh), &len); ioa_network_buffer_set_size(nbh, len); } if(server->verbose) { log_method(ss, "CONNECTION_BIND", err_code, reason); } if(ss && !err_code) { send_data_from_ioa_socket_nbh(s, NULL, nbh, TTL_IGNORE, TOS_IGNORE, NULL); tcp_deliver_delayed_buffer(&(tc->ub_to_client),s,ss); IOA_CLOSE_SOCKET(s_to_delete); FUNCEND; return 0; } else { /* Just to set the necessary structures for the packet sending: */ if(register_callback_on_ioa_socket(server->e, s, IOA_EV_READ, NULL, NULL, 1)<0) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: cannot set TCP tmp client data input callback\n", __FUNCTION__); ioa_network_buffer_delete(server->e, nbh); } else { send_data_from_ioa_socket_nbh(s, NULL, nbh, TTL_IGNORE, TOS_IGNORE, NULL); } } } IOA_CLOSE_SOCKET(s_to_delete); FUNCEND; return -1; } /* <<== RFC 6062 */ static int handle_turn_channel_bind(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh) { FUNCSTART; uint16_t chnum = 0; ioa_addr peer_addr; addr_set_any(&peer_addr); allocation* a = get_allocation_ss(ss); int addr_found = 0; if(ss->is_tcp_relay) { *err_code = 403; *reason = (const uint8_t *)"Channel bind cannot be used with TCP relay"; } else if (is_allocation_valid(a)) { stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_CHANNEL_NUMBER: { if (chnum) { chnum = 0; *err_code = 400; *reason = (const uint8_t *)"Channel number cannot be duplicated in this request"; break; } chnum = stun_attr_get_channel_number(sar); if (!chnum) { *err_code = 400; *reason = (const uint8_t *)"Channel number cannot be zero in this request"; break; } } break; case STUN_ATTRIBUTE_XOR_PEER_ADDRESS: { stun_attr_get_addr_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar, &peer_addr, NULL); if(!get_relay_socket(a,peer_addr.ss.sa_family)) { *err_code = 443; *reason = (const uint8_t *)"Peer Address Family Mismatch (3)"; } if(addr_get_port(&peer_addr) < 1) { *err_code = 400; *reason = (const uint8_t *)"Empty port number in channel bind request"; } else { addr_found = 1; } break; } default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if (*ua_num > 0) { *err_code = 420; } else if (*err_code) { ; } else if (!chnum || addr_any(&peer_addr) || !addr_found) { *err_code = 400; *reason = (const uint8_t *)"Bad channel bind request"; } else if(!STUN_VALID_CHANNEL(chnum)) { *err_code = 400; *reason = (const uint8_t *)"Bad channel number"; } else { ch_info* chn = allocation_get_ch_info(a, chnum); turn_permission_info* tinfo = NULL; if (chn) { if (!addr_eq(&peer_addr, &(chn->peer_addr))) { *err_code = 400; *reason = (const uint8_t *)"You cannot use the same channel number with different peer"; } else { tinfo = (turn_permission_info*) (chn->owner); if (!tinfo) { *err_code = 500; *reason = (const uint8_t *)"Wrong permission info"; } else { if (!addr_eq_no_port(&peer_addr, &(tinfo->addr))) { *err_code = 500; *reason = (const uint8_t *)"Wrong permission info and peer addr combination"; } else if (chn->port != addr_get_port(&peer_addr)) { *err_code = 500; *reason = (const uint8_t *)"Wrong port number"; } } } } else { chn = allocation_get_ch_info_by_peer_addr(a, &peer_addr); if(chn) { *err_code = 400; *reason = (const uint8_t *)"You cannot use the same peer with different channel number"; } else { if(!good_peer_addr(server,ss->realm_options.name,&peer_addr)) { *err_code = 403; *reason = (const uint8_t *) "Forbidden IP"; } else { chn = allocation_get_new_ch_info(a, chnum, &peer_addr); if (!chn) { *err_code = 500; *reason = (const uint8_t *) "Cannot find channel data"; } else { tinfo = (turn_permission_info*) (chn->owner); if (!tinfo) { *err_code = 500; *reason = (const uint8_t *) "Wrong turn permission info"; } } } } } if (!(*err_code) && chn && tinfo) { if (update_channel_lifetime(ss,chn) < 0) { *err_code = 500; *reason = (const uint8_t *)"Cannot update channel lifetime (internal error)"; } else { size_t len = ioa_network_buffer_get_size(nbh); stun_set_channel_bind_response_str(ioa_network_buffer_data(nbh), &len, tid, 0, NULL); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; if(!(ss->is_mobile)) { if(get_ioa_socket_type(ss->client_socket) == UDP_SOCKET || get_ioa_socket_type(ss->client_socket) == TCP_SOCKET || get_ioa_socket_type(ss->client_socket) == SCTP_SOCKET) { if(get_ioa_socket_type(get_relay_socket(&(ss->alloc),peer_addr.ss.sa_family)) == UDP_SOCKET) { chn->kernel_channel = CREATE_TURN_CHANNEL_KERNEL(chn->chnum, get_ioa_socket_address_family(ss->client_socket), peer_addr.ss.sa_family, (get_ioa_socket_type(ss->client_socket)==UDP_SOCKET ? IPPROTO_UDP : IPPROTO_TCP), &(get_remote_addr_from_ioa_socket(ss->client_socket)->ss), &(get_local_addr_from_ioa_socket(ss->client_socket)->ss), &(get_local_addr_from_ioa_socket(get_relay_socket(&(ss->alloc),peer_addr.ss.sa_family))), &(get_remote_addr_from_ioa_socket(get_relay_socket(&(ss->alloc),peer_addr.ss.sa_family))) ); } } } } } } } FUNCEND; return 0; } static int handle_turn_binding(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh, int *origin_changed, ioa_addr *response_origin, int *dest_changed, ioa_addr *response_destination, uint32_t cookie, int old_stun) { FUNCSTART; int change_ip = 0; int change_port = 0; int padding = 0; int response_port_present = 0; uint16_t response_port = 0; SOCKET_TYPE st = get_ioa_socket_type(ss->client_socket); int use_reflected_from = 0; if(!(ss->client_socket)) return -1; *origin_changed = 0; *dest_changed = 0; stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { case OLD_STUN_ATTRIBUTE_PASSWORD: SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_CHANGE_REQUEST: /* * This fix allows the client program from the Stuntman source to make STUN binding requests * to this server. * * It was provided by John Selbie, from STUNTMAN project: * * "Here's the gist of the change. Stuntman comes with a STUN client library * and client program. The client program displays the mapped IP address and * port if it gets back a successful binding response. * It also interops with JSTUN, a Java implementation of STUN. * However, the JSTUN server refuses to respond to any binding request that * doesn't have a CHANGE-REQUEST attribute in it. * ... workaround is for the client to make a request with an empty CHANGE-REQUEST * attribute (neither the ip or port bit are set)." * */ stun_attr_get_change_request_str(sar, &change_ip, &change_port); if( (!is_rfc5780(server)) && (change_ip || change_port)) { *err_code = 420; *reason = (const uint8_t *)"Unknown attribute: TURN server was configured without RFC 5780 support"; break; } if(change_ip || change_port) { if(st != UDP_SOCKET) { *err_code = 400; *reason = (const uint8_t *)"Wrong request: applicable only to UDP protocol"; } } break; case STUN_ATTRIBUTE_PADDING: if(response_port_present) { *err_code = 400; *reason = (const uint8_t *)"Wrong request format: you cannot use PADDING and RESPONSE_PORT together"; } else if((st != UDP_SOCKET) && (st != DTLS_SOCKET)) { *err_code = 400; *reason = (const uint8_t *)"Wrong request: padding applicable only to UDP and DTLS protocols"; } else { padding = 1; } break; case STUN_ATTRIBUTE_RESPONSE_PORT: if(padding) { *err_code = 400; *reason = (const uint8_t *)"Wrong request format: you cannot use PADDING and RESPONSE_PORT together"; } else if(st != UDP_SOCKET) { *err_code = 400; *reason = (const uint8_t *)"Wrong request: applicable only to UDP protocol"; } else { int rp = stun_attr_get_response_port_str(sar); if(rp>=0) { response_port_present = 1; response_port = (uint16_t)rp; } else { *err_code = 400; *reason = (const uint8_t *)"Wrong response port format"; } } break; case OLD_STUN_ATTRIBUTE_RESPONSE_ADDRESS: if(old_stun) { use_reflected_from = 1; stun_attr_get_addr_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar, response_destination, response_destination); } break; default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if (*ua_num > 0) { *err_code = 420; } else if (*err_code) { ; } else if(ss->client_socket && get_remote_addr_from_ioa_socket(ss->client_socket)) { size_t len = ioa_network_buffer_get_size(nbh); if (stun_set_binding_response_str(ioa_network_buffer_data(nbh), &len, tid, get_remote_addr_from_ioa_socket(ss->client_socket), 0, NULL, cookie, old_stun) >= 0) { addr_cpy(response_origin, get_local_addr_from_ioa_socket(ss->client_socket)); *resp_constructed = 1; if(old_stun && use_reflected_from) { stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_REFLECTED_FROM, get_remote_addr_from_ioa_socket(ss->client_socket)); } if(!is_rfc5780(server)) { if(old_stun) { stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_SOURCE_ADDRESS, response_origin); stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_CHANGED_ADDRESS, response_origin); } else { stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_RESPONSE_ORIGIN, response_origin); } } else if(ss->client_socket) { ioa_addr other_address; if(get_other_address(server,ss,&other_address) == 0) { addr_cpy(response_destination, get_remote_addr_from_ioa_socket(ss->client_socket)); if(change_ip) { *origin_changed = 1; if(change_port) { addr_cpy(response_origin,&other_address); } else { int old_port = addr_get_port(response_origin); addr_cpy(response_origin,&other_address); addr_set_port(response_origin,old_port); } } else if(change_port) { *origin_changed = 1; addr_set_port(response_origin,addr_get_port(&other_address)); } if(old_stun) { stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_SOURCE_ADDRESS, response_origin); stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_CHANGED_ADDRESS, &other_address); } else { stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_RESPONSE_ORIGIN, response_origin); stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_OTHER_ADDRESS, &other_address); } if(response_port_present) { *dest_changed = 1; addr_set_port(response_destination, (int)response_port); } if(padding) { int mtu = get_local_mtu_ioa_socket(ss->client_socket); if(mtu<68) mtu=1500; mtu = (mtu >> 2) << 2; stun_attr_add_padding_str(ioa_network_buffer_data(nbh), &len, (uint16_t)mtu); } } } } ioa_network_buffer_set_size(nbh, len); } FUNCEND; return 0; } static int handle_turn_send(turn_turnserver *server, ts_ur_super_session *ss, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer) { FUNCSTART; ioa_addr peer_addr; const uint8_t* value = NULL; int len = -1; int addr_found = 0; int set_df = 0; addr_set_any(&peer_addr); allocation* a = get_allocation_ss(ss); if(ss->is_tcp_relay) { *err_code = 403; *reason = (const uint8_t *)"Send cannot be used with TCP relay"; } else if (is_allocation_valid(a) && (in_buffer->recv_ttl != 0)) { stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_DONT_FRAGMENT: if(!(server->dont_fragment)) unknown_attrs[(*ua_num)++] = nswap16(attr_type); else set_df = 1; break; case STUN_ATTRIBUTE_XOR_PEER_ADDRESS: { if (addr_found) { *err_code = 400; *reason = (const uint8_t *)"Address duplication"; } else { stun_attr_get_addr_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar, &peer_addr, NULL); } } break; case STUN_ATTRIBUTE_DATA: { if (len >= 0) { *err_code = 400; *reason = (const uint8_t *)"Data duplication"; } else { len = stun_attr_get_len(sar); value = stun_attr_get_value(sar); } } break; default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if (*err_code) { ; } else if (*ua_num > 0) { *err_code = 420; } else if (!addr_any(&peer_addr) && len >= 0) { turn_permission_info* tinfo = NULL; if(!(server->server_relay)) tinfo = allocation_get_permission(a, &peer_addr); if (tinfo || (server->server_relay)) { set_df_on_ioa_socket(get_relay_socket_ss(ss,peer_addr.ss.sa_family), set_df); ioa_network_buffer_handle nbh = in_buffer->nbh; if(value && len>0) { uint16_t offset = (uint16_t)(value - ioa_network_buffer_data(nbh)); ioa_network_buffer_add_offset_size(nbh,offset,0,len); } else { len = 0; ioa_network_buffer_set_size(nbh,len); } ioa_network_buffer_header_init(nbh); int skip = 0; send_data_from_ioa_socket_nbh(get_relay_socket_ss(ss,peer_addr.ss.sa_family), &peer_addr, nbh, in_buffer->recv_ttl-1, in_buffer->recv_tos, &skip); if (!skip) { ++(ss->peer_sent_packets); ss->peer_sent_bytes += len; turn_report_session_usage(ss, 0); } in_buffer->nbh = NULL; } } else { *err_code = 400; *reason = (const uint8_t *)"No address found"; } } FUNCEND; return 0; } static int update_permission(ts_ur_super_session *ss, ioa_addr *peer_addr) { if (!ss || !peer_addr) return -1; allocation* a = get_allocation_ss(ss); turn_permission_info* tinfo = allocation_get_permission(a, peer_addr); if (!tinfo) { tinfo = allocation_add_permission(a, peer_addr); } if (!tinfo) return -1; if (update_turn_permission_lifetime(ss, tinfo, 0) < 0) return -1; ch_info *chn = get_turn_channel(tinfo, peer_addr); if(chn) { if (update_channel_lifetime(ss, chn) < 0) return -1; } return 0; } static int handle_turn_create_permission(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh) { int ret = -1; int addr_found = 0; UNUSED_ARG(server); allocation* a = get_allocation_ss(ss); if (is_allocation_valid(a)) { { stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_XOR_PEER_ADDRESS: { ioa_addr peer_addr; addr_set_any(&peer_addr); stun_attr_get_addr_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar, &peer_addr, NULL); if(!get_relay_socket(a,peer_addr.ss.sa_family)) { *err_code = 443; *reason = (const uint8_t *)"Peer Address Family Mismatch (4)"; } else if(!good_peer_addr(server, ss->realm_options.name, &peer_addr)) { *err_code = 403; *reason = (const uint8_t *) "Forbidden IP"; } else { addr_found++; } } break; default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } } if (*ua_num > 0) { *err_code = 420; } else if (*err_code) { ; } else if (!addr_found) { *err_code = 400; *reason = (const uint8_t *)"No address found"; } else { stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_XOR_PEER_ADDRESS: { ioa_addr peer_addr; addr_set_any(&peer_addr); stun_attr_get_addr_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar, &peer_addr, NULL); addr_set_port(&peer_addr, 0); if (update_permission(ss, &peer_addr) < 0) { *err_code = 500; *reason = (const uint8_t *)"Cannot update some permissions (critical server software error)"; } } break; default: ; } sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if(*err_code == 0) { size_t len = ioa_network_buffer_get_size(nbh); stun_init_success_response_str(STUN_METHOD_CREATE_PERMISSION, ioa_network_buffer_data(nbh), &len, tid); ioa_network_buffer_set_size(nbh,len); ret = 0; *resp_constructed = 1; } } } return ret; } // AUTH ==>> static int need_stun_authentication(turn_turnserver *server, ts_ur_super_session *ss) { UNUSED_ARG(ss); if(server) { switch(server->ct) { case TURN_CREDENTIALS_LONG_TERM: return 1; default: ; }; } return 0; } static int create_challenge_response(ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, ioa_network_buffer_handle nbh, uint16_t method) { size_t len = ioa_network_buffer_get_size(nbh); stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, *err_code, *reason, tid); *resp_constructed = 1; stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_NONCE, ss->nonce, (int)(NONCE_MAX_SIZE-1)); char *realm = ss->realm_options.name; stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_REALM, (uint8_t*)realm, (int)(strlen((char*)(realm)))); if(ss->server) { turn_turnserver* server = (turn_turnserver*)ss->server; if(server->oauth) { const char *server_name = server->oauth_server_name; if(!(server_name && server_name[0])) { server_name = realm; } stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_THIRD_PARTY_AUTHORIZATION, (const uint8_t*)(server_name), strlen(server_name)); } } ioa_network_buffer_set_size(nbh,len); return 0; } #if !defined(min) #define min(a,b) ((a)<=(b) ? (a) : (b)) #endif static void resume_processing_after_username_check(int success, int oauth, int max_session_time, hmackey_t hmackey, password_t pwd, turn_turnserver *server, uint64_t ctxkey, ioa_net_data *in_buffer, uint8_t *realm) { if(server && in_buffer && in_buffer->nbh) { ts_ur_super_session *ss = get_session_from_map(server,(turnsession_id)ctxkey); if(ss && ss->client_socket) { turn_turnserver *server = (turn_turnserver *)ss->server; if(success) { bcopy(hmackey,ss->hmackey,sizeof(hmackey_t)); ss->hmackey_set = 1; ss->oauth = oauth; ss->max_session_time_auth = (turn_time_t)max_session_time; bcopy(pwd,ss->pwd,sizeof(password_t)); if(realm && realm[0] && strcmp((char*)realm,ss->realm_options.name)) { dec_quota(ss); get_realm_options_by_name((char*)realm, &(ss->realm_options)); inc_quota(ss,ss->username); } } read_client_connection(server,ss,in_buffer,0,0); close_ioa_socket_after_processing_if_necessary(ss->client_socket); ioa_network_buffer_delete(server->e, in_buffer->nbh); in_buffer->nbh=NULL; } } } static int check_stun_auth(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh, uint16_t method, int *message_integrity, int *postpone_reply, int can_resume) { uint8_t usname[STUN_MAX_USERNAME_SIZE+1]; uint8_t nonce[STUN_MAX_NONCE_SIZE+1]; uint8_t realm[STUN_MAX_REALM_SIZE+1]; size_t alen = 0; if(!need_stun_authentication(server, ss)) return 0; int new_nonce = 0; { int generate_new_nonce = 0; if(ss->nonce[0]==0) { generate_new_nonce = 1; new_nonce = 1; } if(*(server->stale_nonce)) { if(turn_time_before(ss->nonce_expiration_time,server->ctime)) { generate_new_nonce = 1; } } if(generate_new_nonce) { int i = 0; if(TURN_RANDOM_SIZE == 8) { for(i=0;i<(NONCE_LENGTH_32BITS>>1);i++) { uint8_t *s = ss->nonce + 8*i; uint64_t rand=(uint64_t)turn_random(); snprintf((char*)s, NONCE_MAX_SIZE-8*i, "%08lx",(unsigned long)rand); } } else { for(i=0;i<NONCE_LENGTH_32BITS;i++) { uint8_t *s = ss->nonce + 4*i; uint32_t rand=(uint32_t)turn_random(); snprintf((char*)s, NONCE_MAX_SIZE-4*i, "%04x",(unsigned int)rand); } } ss->nonce_expiration_time = server->ctime + *(server->stale_nonce); } } /* MESSAGE_INTEGRITY ATTR: */ stun_attr_ref sar = stun_attr_get_first_by_type_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), STUN_ATTRIBUTE_MESSAGE_INTEGRITY); if(!sar) { *err_code = 401; return create_challenge_response(ss,tid,resp_constructed,err_code,reason,nbh,method); } { int sarlen = stun_attr_get_len(sar); switch(sarlen) { case SHA1SIZEBYTES: break; case SHA256SIZEBYTES: case SHA384SIZEBYTES: case SHA512SIZEBYTES: default: *err_code = 401; return create_challenge_response(ss,tid,resp_constructed,err_code,reason,nbh,method); }; } { /* REALM ATTR: */ sar = stun_attr_get_first_by_type_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), STUN_ATTRIBUTE_REALM); if(!sar) { *err_code = 400; return -1; } alen = min((size_t)stun_attr_get_len(sar),sizeof(realm)-1); bcopy(stun_attr_get_value(sar),realm,alen); realm[alen]=0; if(!is_secure_string(realm,0)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: wrong realm: %s\n", __FUNCTION__, (char*)realm); realm[0]=0; *err_code = 400; return -1; } if(method == STUN_METHOD_CONNECTION_BIND) { get_realm_options_by_name((char *)realm, &(ss->realm_options)); } else if(strcmp((char*)realm, (char*)(ss->realm_options.name))) { if(!(ss->oauth)){ if(method == STUN_METHOD_ALLOCATE) { *err_code = 437; *reason = (const uint8_t*)"Allocation mismatch: wrong credentials: the realm value is incorrect"; } else { *err_code = 441; *reason = (const uint8_t*)"Wrong credentials: the realm value is incorrect"; } return -1; } else { bcopy(ss->realm_options.name,realm,sizeof(ss->realm_options.name)); } } } /* USERNAME ATTR: */ sar = stun_attr_get_first_by_type_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), STUN_ATTRIBUTE_USERNAME); if(!sar) { *err_code = 400; return -1; } alen = min((size_t)stun_attr_get_len(sar),sizeof(usname)-1); bcopy(stun_attr_get_value(sar),usname,alen); usname[alen]=0; if(!is_secure_string(usname,1)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: wrong username: %s\n", __FUNCTION__, (char*)usname); usname[0]=0; *err_code = 400; return -1; } else if(ss->username[0]) { if(strcmp((char*)ss->username,(char*)usname)) { if(ss->oauth) { ss->hmackey_set = 0; STRCPY(ss->username,usname); } else { if(method == STUN_METHOD_ALLOCATE) { *err_code = 437; *reason = (const uint8_t*)"Allocation mismatch: wrong credentials"; } else { *err_code = 441; } return -1; } } } else { STRCPY(ss->username,usname); } { /* NONCE ATTR: */ sar = stun_attr_get_first_by_type_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), STUN_ATTRIBUTE_NONCE); if(!sar) { *err_code = 400; return -1; } alen = min((size_t)stun_attr_get_len(sar),sizeof(nonce)-1); bcopy(stun_attr_get_value(sar),nonce,alen); nonce[alen]=0; /* Stale Nonce check: */ if(new_nonce) { *err_code = 438; *reason = (const uint8_t*)"Wrong nonce"; return create_challenge_response(ss,tid,resp_constructed,err_code,reason,nbh,method); } if(strcmp((char*)ss->nonce,(char*)nonce)) { *err_code = 438; *reason = (const uint8_t*)"Stale nonce"; return create_challenge_response(ss,tid,resp_constructed,err_code,reason,nbh,method); } } /* Password */ if(!(ss->hmackey_set) && (ss->pwd[0] == 0)) { if(can_resume) { (server->userkeycb)(server->id, server->ct, server->oauth, &(ss->oauth), usname, realm, resume_processing_after_username_check, in_buffer, ss->id, postpone_reply); if(*postpone_reply) { return 0; } } TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: Cannot find credentials of user <%s>\n", __FUNCTION__, (char*)usname); *err_code = 401; return create_challenge_response(ss,tid,resp_constructed,err_code,reason,nbh,method); } /* Check integrity */ if(stun_check_message_integrity_by_key_str(server->ct,ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), ss->hmackey, ss->pwd, SHATYPE_DEFAULT)<1) { if(can_resume) { (server->userkeycb)(server->id, server->ct, server->oauth, &(ss->oauth), usname, realm, resume_processing_after_username_check, in_buffer, ss->id, postpone_reply); if(*postpone_reply) { return 0; } } TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: user %s credentials are incorrect\n", __FUNCTION__, (char*)usname); *err_code = 401; return create_challenge_response(ss,tid,resp_constructed,err_code,reason,nbh,method); } *message_integrity = 1; return 0; } //<<== AUTH static void set_alternate_server(turn_server_addrs_list_t *asl, const ioa_addr *local_addr, size_t *counter, uint16_t method, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, ioa_network_buffer_handle nbh) { if(asl && asl->size && local_addr) { size_t i; /* to prevent indefinite cycle: */ for(i=0;i<asl->size;++i) { ioa_addr *addr = &(asl->addrs[i]); if(addr_eq(addr,local_addr)) return; } for(i=0;i<asl->size;++i) { if(*counter>=asl->size) *counter = 0; ioa_addr *addr = &(asl->addrs[*counter]); *counter +=1; if(addr->ss.sa_family == local_addr->ss.sa_family) { *err_code = 300; size_t len = ioa_network_buffer_get_size(nbh); stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, *err_code, *reason, tid); *resp_constructed = 1; stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_ALTERNATE_SERVER, addr); ioa_network_buffer_set_size(nbh,len); return; } } } } static int handle_turn_command(turn_turnserver *server, ts_ur_super_session *ss, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh, int *resp_constructed, int can_resume) { stun_tid tid; int err_code = 0; const uint8_t *reason = NULL; int no_response = 0; int message_integrity = 0; if(!(ss->client_socket)) return -1; uint16_t unknown_attrs[MAX_NUMBER_OF_UNKNOWN_ATTRS]; uint16_t ua_num = 0; uint16_t method = stun_get_method_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); *resp_constructed = 0; stun_tid_from_message_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), &tid); if (stun_is_request_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh))) { if((method == STUN_METHOD_BINDING) && (*(server->no_stun))) { no_response = 1; if(server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: STUN method 0x%x ignored\n", __FUNCTION__, (unsigned int)method); } } else if((method != STUN_METHOD_BINDING) && (*(server->stun_only))) { no_response = 1; if(server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: STUN method 0x%x ignored\n", __FUNCTION__, (unsigned int)method); } } else if((method != STUN_METHOD_BINDING) || (*(server->secure_stun))) { if(method == STUN_METHOD_ALLOCATE) { allocation *a = get_allocation_ss(ss); if(is_allocation_valid(a)) { if(!stun_tid_equals(&(a->tid), &tid)) { err_code = 437; reason = (const uint8_t *)"Mismatched allocation: wrong transaction ID"; } } if(!err_code) { SOCKET_TYPE cst = get_ioa_socket_type(ss->client_socket); turn_server_addrs_list_t *asl = server->alternate_servers_list; if(((cst == UDP_SOCKET)||(cst == DTLS_SOCKET)) && server->self_udp_balance && server->aux_servers_list && server->aux_servers_list->size) { asl = server->aux_servers_list; } else if(((cst == TLS_SOCKET) || (cst == DTLS_SOCKET) ||(cst == TLS_SCTP_SOCKET)) && server->tls_alternate_servers_list && server->tls_alternate_servers_list->size) { asl = server->tls_alternate_servers_list; } if(asl && asl->size) { turn_mutex_lock(&(asl->m)); set_alternate_server(asl,get_local_addr_from_ioa_socket(ss->client_socket),&(server->as_counter),method,&tid,resp_constructed,&err_code,&reason,nbh); turn_mutex_unlock(&(asl->m)); } } } /* check that the realm is the same as in the original request */ if(ss->origin_set) { stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); int origin_found = 0; int norigins = 0; while(sar && !origin_found) { if(stun_attr_get_type(sar) == STUN_ATTRIBUTE_ORIGIN) { int sarlen = stun_attr_get_len(sar); if(sarlen>0) { ++norigins; char *o = (char*)malloc(sarlen+1); bcopy(stun_attr_get_value(sar),o,sarlen); o[sarlen]=0; char *corigin = (char*)malloc(STUN_MAX_ORIGIN_SIZE+1); corigin[0]=0; if(get_canonic_origin(o,corigin,STUN_MAX_ORIGIN_SIZE)<0) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: Wrong origin format: %s\n", __FUNCTION__, o); } if(!strncmp(ss->origin,corigin,STUN_MAX_ORIGIN_SIZE)) { origin_found = 1; } free(corigin); free(o); } } sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if(server->check_origin && *(server->check_origin)) { if(ss->origin[0]) { if(!origin_found) { err_code = 441; reason = (const uint8_t *)"The origin attribute does not match the initial session origin value"; if(server->verbose) { char smethod[129]; stun_method_str(method,smethod); log_method(ss, smethod, err_code, reason); } } } else if(norigins > 0){ err_code = 441; reason = (const uint8_t *)"The origin attribute is empty, does not match the initial session origin value"; if(server->verbose) { char smethod[129]; stun_method_str(method,smethod); log_method(ss, smethod, err_code, reason); } } } } /* get the initial origin value */ if(!err_code && !(ss->origin_set) && (method == STUN_METHOD_ALLOCATE)) { stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); int origin_found = 0; while(sar && !origin_found) { if(stun_attr_get_type(sar) == STUN_ATTRIBUTE_ORIGIN) { int sarlen = stun_attr_get_len(sar); if(sarlen>0) { char *o = (char*)malloc(sarlen+1); bcopy(stun_attr_get_value(sar),o,sarlen); o[sarlen]=0; char *corigin = (char*)malloc(STUN_MAX_ORIGIN_SIZE+1); corigin[0]=0; if(get_canonic_origin(o,corigin,STUN_MAX_ORIGIN_SIZE)<0) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: Wrong origin format: %s\n", __FUNCTION__, o); } strncpy(ss->origin,corigin,STUN_MAX_ORIGIN_SIZE); free(corigin); free(o); origin_found = get_realm_options_by_origin(ss->origin,&(ss->realm_options)); } } sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } ss->origin_set = 1; } if(!err_code && !(*resp_constructed) && !no_response) { if(method == STUN_METHOD_CONNECTION_BIND) { ; } else if(!(*(server->mobility)) || (method != STUN_METHOD_REFRESH) || is_allocation_valid(get_allocation_ss(ss))) { int postpone_reply = 0; check_stun_auth(server, ss, &tid, resp_constructed, &err_code, &reason, in_buffer, nbh, method, &message_integrity, &postpone_reply, can_resume); if(postpone_reply) no_response = 1; } } } if (!err_code && !(*resp_constructed) && !no_response) { switch (method){ case STUN_METHOD_ALLOCATE: { handle_turn_allocate(server, ss, &tid, resp_constructed, &err_code, &reason, unknown_attrs, &ua_num, in_buffer, nbh); if(server->verbose) { log_method(ss, "ALLOCATE", err_code, reason); } break; } case STUN_METHOD_CONNECT: handle_turn_connect(server, ss, &tid, &err_code, &reason, unknown_attrs, &ua_num, in_buffer); if(server->verbose) { log_method(ss, "CONNECT", err_code, reason); } if(!err_code) no_response = 1; break; case STUN_METHOD_CONNECTION_BIND: handle_turn_connection_bind(server, ss, &tid, resp_constructed, &err_code, &reason, unknown_attrs, &ua_num, in_buffer, nbh, message_integrity, can_resume); if(server->verbose && err_code) { log_method(ss, "CONNECTION_BIND", err_code, reason); } break; case STUN_METHOD_REFRESH: handle_turn_refresh(server, ss, &tid, resp_constructed, &err_code, &reason, unknown_attrs, &ua_num, in_buffer, nbh, message_integrity, &no_response, can_resume); if(server->verbose) { log_method(ss, "REFRESH", err_code, reason); } break; case STUN_METHOD_CHANNEL_BIND: handle_turn_channel_bind(server, ss, &tid, resp_constructed, &err_code, &reason, unknown_attrs, &ua_num, in_buffer, nbh); if(server->verbose) { log_method(ss, "CHANNEL_BIND", err_code, reason); } break; case STUN_METHOD_CREATE_PERMISSION: handle_turn_create_permission(server, ss, &tid, resp_constructed, &err_code, &reason, unknown_attrs, &ua_num, in_buffer, nbh); if(server->verbose) { log_method(ss, "CREATE_PERMISSION", err_code, reason); } break; case STUN_METHOD_BINDING: { int origin_changed=0; ioa_addr response_origin; int dest_changed=0; ioa_addr response_destination; handle_turn_binding(server, ss, &tid, resp_constructed, &err_code, &reason, unknown_attrs, &ua_num, in_buffer, nbh, &origin_changed, &response_origin, &dest_changed, &response_destination, 0, 0); if(server->verbose && server->log_binding) { log_method(ss, "BINDING", err_code, reason); } if(*resp_constructed && !err_code && (origin_changed || dest_changed)) { if (server->verbose && server->log_binding) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "RFC 5780 request successfully processed\n"); } { const uint8_t *field = (const uint8_t *) get_version(server); size_t fsz = strlen(get_version(server)); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_SOFTWARE, field, fsz); ioa_network_buffer_set_size(nbh, len); } send_turn_message_to(server, nbh, &response_origin, &response_destination); no_response = 1; } break; } default: TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unsupported STUN request received, method 0x%x\n",(unsigned int)method); }; } } else if (stun_is_indication_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh))) { no_response = 1; int postpone = 0; if (!postpone && !err_code) { switch (method){ case STUN_METHOD_BINDING: //ICE ? break; case STUN_METHOD_SEND: handle_turn_send(server, ss, &err_code, &reason, unknown_attrs, &ua_num, in_buffer); if(eve(server->verbose)) { log_method(ss, "SEND", err_code, reason); } break; case STUN_METHOD_DATA: err_code = 403; if(eve(server->verbose)) { log_method(ss, "DATA", err_code, reason); } break; default: if (server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Unsupported STUN indication received: method 0x%x\n",(unsigned int)method); } } }; } else { no_response = 1; if (server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Wrong STUN message received\n"); } } if(ss->to_be_closed || !(ss->client_socket) || ioa_socket_tobeclosed(ss->client_socket)) return 0; if (ua_num > 0) { err_code = 420; size_t len = ioa_network_buffer_get_size(nbh); stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, err_code, NULL, &tid); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_UNKNOWN_ATTRIBUTES, (const uint8_t*) unknown_attrs, (ua_num * 2)); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } if (!no_response) { if (!(*resp_constructed)) { if (!err_code) err_code = 400; size_t len = ioa_network_buffer_get_size(nbh); stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, err_code, reason, &tid); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } { const uint8_t *field = (const uint8_t *) get_version(server); size_t fsz = strlen(get_version(server)); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_SOFTWARE, field, fsz); ioa_network_buffer_set_size(nbh, len); } if(message_integrity) { size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_integrity_str(server->ct,ioa_network_buffer_data(nbh),&len,ss->hmackey,ss->pwd,SHATYPE_DEFAULT); ioa_network_buffer_set_size(nbh,len); } if(err_code) { if(server->verbose) { log_method(ss, "message", err_code, reason); } } } else { *resp_constructed = 0; } return 0; } static int handle_old_stun_command(turn_turnserver *server, ts_ur_super_session *ss, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh, int *resp_constructed, uint32_t cookie) { stun_tid tid; int err_code = 0; const uint8_t *reason = NULL; int no_response = 0; uint16_t unknown_attrs[MAX_NUMBER_OF_UNKNOWN_ATTRS]; uint16_t ua_num = 0; uint16_t method = stun_get_method_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); *resp_constructed = 0; stun_tid_from_message_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), &tid); if (stun_is_request_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh))) { if(method != STUN_METHOD_BINDING) { no_response = 1; if(server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: OLD STUN method 0x%x ignored\n", __FUNCTION__, (unsigned int)method); } } if (!err_code && !(*resp_constructed) && !no_response) { int origin_changed=0; ioa_addr response_origin; int dest_changed=0; ioa_addr response_destination; handle_turn_binding(server, ss, &tid, resp_constructed, &err_code, &reason, unknown_attrs, &ua_num, in_buffer, nbh, &origin_changed, &response_origin, &dest_changed, &response_destination, cookie,1); if(server->verbose && *(server->log_binding)) { log_method(ss, "OLD BINDING", err_code, reason); } if(*resp_constructed && !err_code && (origin_changed || dest_changed)) { if (server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "RFC3489 CHANGE request successfully processed\n"); } { size_t oldsz = strlen(get_version(server)); size_t newsz = (((oldsz)>>2) + 1)<<2; uint8_t software[120]; bzero(software,sizeof(software)); if(newsz>sizeof(software)) newsz = sizeof(software); bcopy(get_version(server),software,oldsz); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_SERVER, software, newsz); ioa_network_buffer_set_size(nbh, len); } send_turn_message_to(server, nbh, &response_origin, &response_destination); no_response = 1; } } } else { no_response = 1; if (server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Wrong OLD STUN message received\n"); } } if (ua_num > 0) { err_code = 420; size_t len = ioa_network_buffer_get_size(nbh); old_stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, err_code, NULL, &tid, cookie); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_UNKNOWN_ATTRIBUTES, (const uint8_t*) unknown_attrs, (ua_num * 2)); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } if (!no_response) { if (!(*resp_constructed)) { if (!err_code) err_code = 400; size_t len = ioa_network_buffer_get_size(nbh); old_stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, err_code, reason, &tid, cookie); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } { size_t oldsz = strlen(get_version(server)); size_t newsz = (((oldsz)>>2) + 1)<<2; uint8_t software[120]; bzero(software,sizeof(software)); if(newsz>sizeof(software)) newsz = sizeof(software); bcopy(get_version(server),software,oldsz); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_SERVER, software, newsz); ioa_network_buffer_set_size(nbh, len); } if(err_code) { if(server->verbose) { log_method(ss, "OLD STUN message", err_code, reason); } } } else { *resp_constructed = 0; } return 0; } ////////////////////////////////////////////////////////////////// static int write_to_peerchannel(ts_ur_super_session* ss, uint16_t chnum, ioa_net_data *in_buffer) { int rc = 0; if (ss && (in_buffer->recv_ttl!=0)) { allocation* a = get_allocation_ss(ss); if (is_allocation_valid(a)) { ch_info* chn = allocation_get_ch_info(a, chnum); if (!chn) return -1; /* Channel packets are always sent with DF=0: */ set_df_on_ioa_socket(get_relay_socket_ss(ss, chn->peer_addr.ss.sa_family), 0); ioa_network_buffer_handle nbh = in_buffer->nbh; ioa_network_buffer_add_offset_size(in_buffer->nbh, STUN_CHANNEL_HEADER_LENGTH, 0, ioa_network_buffer_get_size(in_buffer->nbh)-STUN_CHANNEL_HEADER_LENGTH); ioa_network_buffer_header_init(nbh); int skip = 0; rc = send_data_from_ioa_socket_nbh(get_relay_socket_ss(ss, chn->peer_addr.ss.sa_family), &(chn->peer_addr), nbh, in_buffer->recv_ttl-1, in_buffer->recv_tos, &skip); if (!skip && rc > -1) { ++(ss->peer_sent_packets); ss->peer_sent_bytes += (uint32_t)ioa_network_buffer_get_size(in_buffer->nbh); turn_report_session_usage(ss, 0); } in_buffer->nbh = NULL; } } return rc; } static void client_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *data, void *arg, int can_resume); static void peer_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *data, void *arg, int can_resume); /////////////// Client actions ///////////////// int shutdown_client_connection(turn_turnserver *server, ts_ur_super_session *ss, int force, const char* reason) { FUNCSTART; if (!ss) return -1; turn_report_session_usage(ss, 1); dec_quota(ss); dec_bps(ss); allocation* alloc = get_allocation_ss(ss); if (!is_allocation_valid(alloc)) { force = 1; } if(!force && ss->is_mobile) { if (ss->client_socket && server->verbose) { char sraddr[129]="\0"; char sladdr[129]="\0"; addr_to_string(get_remote_addr_from_ioa_socket(ss->client_socket),(uint8_t*)sraddr); addr_to_string(get_local_addr_from_ioa_socket(ss->client_socket),(uint8_t*)sladdr); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: closed (1st stage), user <%s> realm <%s> origin <%s>, local %s, remote %s, reason: %s\n",(unsigned long long)(ss->id),(char*)ss->username,(char*)ss->realm_options.name,(char*)ss->origin, sladdr,sraddr,reason); } IOA_CLOSE_SOCKET(ss->client_socket); FUNCEND; return 0; } if (eve(server->verbose)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "closing session 0x%lx, client socket 0x%lx (socket session=0x%lx)\n", (long) ss, (long) ss->client_socket, (long)get_ioa_socket_session(ss->client_socket)); } if (server->disconnect) server->disconnect(ss); if (server->verbose) { char sraddr[129]="\0"; char sladdr[129]="\0"; addr_to_string(get_remote_addr_from_ioa_socket(ss->client_socket),(uint8_t*)sraddr); addr_to_string(get_local_addr_from_ioa_socket(ss->client_socket),(uint8_t*)sladdr); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: closed (2nd stage), user <%s> realm <%s> origin <%s>, local %s, remote %s, reason: %s\n", (unsigned long long)(ss->id), (char*)ss->username,(char*)ss->realm_options.name,(char*)ss->origin, sladdr,sraddr, reason); } IOA_CLOSE_SOCKET(ss->client_socket); { int i; for(i=0;i<ALLOC_PROTOCOLS_NUMBER;++i) { IOA_CLOSE_SOCKET(ss->alloc.relay_sessions[i].s); } } turn_server_remove_all_from_ur_map_ss(ss); FUNCEND; return 0; } static void client_to_be_allocated_timeout_handler(ioa_engine_handle e, void *arg) { if (!arg) return; UNUSED_ARG(e); ts_ur_super_session* ss = (ts_ur_super_session*) arg; turn_turnserver* server = (turn_turnserver*) (ss->server); if (!server) return; FUNCSTART; int to_close = 0; ioa_socket_handle s = ss->client_socket; if(!s || ioa_socket_tobeclosed(s)) { to_close = 1; } else if(get_ioa_socket_app_type(s) == HTTPS_CLIENT_SOCKET) { ; } else { ioa_socket_handle rs4 = ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].s; ioa_socket_handle rs6 = ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].s; if((!rs4 || ioa_socket_tobeclosed(rs4)) && (!rs6 || ioa_socket_tobeclosed(rs6))) { to_close = 1; } else if(ss->client_socket == NULL) { to_close = 1; } else if(!(ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].lifetime_ev) && !(ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].lifetime_ev)) { to_close = 1; } else if(!(ss->to_be_allocated_timeout_ev)) { to_close = 1; } } if(to_close) { IOA_EVENT_DEL(ss->to_be_allocated_timeout_ev); shutdown_client_connection(server, ss, 1, "allocation watchdog determined stale session state"); } FUNCEND; } static int write_client_connection(turn_turnserver *server, ts_ur_super_session* ss, ioa_network_buffer_handle nbh, int ttl, int tos) { FUNCSTART; if (!(ss->client_socket)) { ioa_network_buffer_delete(server->e, nbh); FUNCEND; return -1; } else { if (eve(server->verbose)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: prepare to write to s 0x%lx\n", __FUNCTION__, (long) (ss->client_socket)); } int skip = 0; int ret = send_data_from_ioa_socket_nbh(ss->client_socket, NULL, nbh, ttl, tos, &skip); if(!skip && ret>-1) { ++(ss->sent_packets); ss->sent_bytes += (uint32_t)ioa_network_buffer_get_size(nbh); turn_report_session_usage(ss, 0); } FUNCEND; return ret; } } static void client_ss_allocation_timeout_handler(ioa_engine_handle e, void *arg) { UNUSED_ARG(e); if (!arg) return; relay_endpoint_session *rsession = (relay_endpoint_session*)arg; if(!(rsession->s)) return; ts_ur_super_session* ss = get_ioa_socket_session(rsession->s); if (!ss) return; allocation* a = get_allocation_ss(ss); turn_turnserver* server = (turn_turnserver*) (ss->server); if (!server) { clear_allocation(a); return; } FUNCSTART; int family = get_ioa_socket_address_family(rsession->s); set_allocation_family_invalid(a,family); if(!get_relay_socket(a, AF_INET) && !get_relay_socket(a, AF_INET6)) { shutdown_client_connection(server, ss, 0, "allocation timeout"); } FUNCEND; } static int create_relay_connection(turn_turnserver* server, ts_ur_super_session *ss, uint32_t lifetime, int address_family, uint8_t transport, int even_port, uint64_t in_reservation_token, uint64_t *out_reservation_token, int *err_code, const uint8_t **reason, accept_cb acb) { if (server && ss && ss->client_socket && !ioa_socket_tobeclosed(ss->client_socket)) { allocation* a = get_allocation_ss(ss); relay_endpoint_session* newelem = NULL; ioa_socket_handle rtcp_s = NULL; if (in_reservation_token) { ioa_socket_handle s = NULL; if ((get_ioa_socket_from_reservation(server->e, in_reservation_token,&s) < 0)|| !s || ioa_socket_tobeclosed(s)) { IOA_CLOSE_SOCKET(s); *err_code = 404; *reason = (const uint8_t *)"Cannot find reserved socket"; return -1; } int family = get_ioa_socket_address_family(s); newelem = get_relay_session_ss(ss,family); if(newelem->s != s) { IOA_CLOSE_SOCKET(newelem->s); bzero(newelem, sizeof(relay_endpoint_session)); newelem->s = s; } addr_debug_print(server->verbose, get_local_addr_from_ioa_socket(newelem->s), "Local relay addr (RTCP)"); } else { int family = get_family(address_family,server->e,ss->client_socket); newelem = get_relay_session_ss(ss,family); IOA_CLOSE_SOCKET(newelem->s); bzero(newelem, sizeof(relay_endpoint_session)); newelem->s = NULL; int res = create_relay_ioa_sockets(server->e, ss->client_socket, address_family, transport, even_port, &(newelem->s), &rtcp_s, out_reservation_token, err_code, reason, acb, ss); if (res < 0) { if(!(*err_code)) *err_code = 508; if(!(*reason)) *reason = (const uint8_t *)"Cannot create socket"; IOA_CLOSE_SOCKET(newelem->s); IOA_CLOSE_SOCKET(rtcp_s); return -1; } } if (newelem->s == NULL) { IOA_CLOSE_SOCKET(rtcp_s); *err_code = 508; *reason = (const uint8_t *)"Cannot create relay socket"; return -1; } if (rtcp_s) { if (out_reservation_token && *out_reservation_token) { /* OK */ } else { IOA_CLOSE_SOCKET(newelem->s); IOA_CLOSE_SOCKET(rtcp_s); *err_code = 500; *reason = (const uint8_t *)"Wrong reservation tokens (internal error)"; return -1; } } /* RFC6156: do not use DF when IPv6 is involved: */ if((get_ioa_socket_address_family(newelem->s) == AF_INET6) || (get_ioa_socket_address_family(ss->client_socket) == AF_INET6)) set_do_not_use_df(newelem->s); if(get_ioa_socket_type(newelem->s) != TCP_SOCKET) { if(register_callback_on_ioa_socket(server->e, newelem->s, IOA_EV_READ,peer_input_handler, ss, 0)<0) { return -1; } } if (lifetime<1) lifetime = STUN_DEFAULT_ALLOCATE_LIFETIME; else if(lifetime>(uint32_t)*(server->max_allocate_lifetime)) lifetime = (uint32_t)*(server->max_allocate_lifetime); ioa_timer_handle ev = set_ioa_timer(server->e, lifetime, 0, client_ss_allocation_timeout_handler, newelem, 0, "client_ss_allocation_timeout_handler"); set_allocation_lifetime_ev(a, server->ctime + lifetime, ev, get_ioa_socket_address_family(newelem->s)); set_ioa_socket_session(newelem->s, ss); } return 0; } static int refresh_relay_connection(turn_turnserver* server, ts_ur_super_session *ss, uint32_t lifetime, int even_port, uint64_t in_reservation_token, uint64_t *out_reservation_token, int *err_code, int family) { UNUSED_ARG(even_port); UNUSED_ARG(in_reservation_token); UNUSED_ARG(out_reservation_token); UNUSED_ARG(err_code); allocation* a = get_allocation_ss(ss); if (server && ss && is_allocation_valid(a)) { if (lifetime < 1) { lifetime = 1; } ioa_timer_handle ev = set_ioa_timer(server->e, lifetime, 0, client_ss_allocation_timeout_handler, get_relay_session(a,family), 0, "refresh_client_ss_allocation_timeout_handler"); set_allocation_lifetime_ev(a, server->ctime + lifetime, ev, family); return 0; } else { return -1; } } static int read_client_connection(turn_turnserver *server, ts_ur_super_session *ss, ioa_net_data *in_buffer, int can_resume, int count_usage) { FUNCSTART; if (!server || !ss || !in_buffer || !(ss->client_socket) || ss->to_be_closed || ioa_socket_tobeclosed(ss->client_socket)) { FUNCEND; return -1; } int ret = (int)ioa_network_buffer_get_size(in_buffer->nbh); if (ret < 0) { FUNCEND; return -1; } if(count_usage) { ++(ss->received_packets); ss->received_bytes += (uint32_t)ioa_network_buffer_get_size(in_buffer->nbh); turn_report_session_usage(ss, 0); } if (eve(server->verbose)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: data.buffer=0x%lx, data.len=%ld\n", __FUNCTION__, (long)ioa_network_buffer_data(in_buffer->nbh), (long)ioa_network_buffer_get_size(in_buffer->nbh)); } uint16_t chnum = 0; uint32_t old_stun_cookie = 0; size_t blen = ioa_network_buffer_get_size(in_buffer->nbh); size_t orig_blen = blen; SOCKET_TYPE st = get_ioa_socket_type(ss->client_socket); SOCKET_APP_TYPE sat = get_ioa_socket_app_type(ss->client_socket); int is_padding_mandatory = is_stream_socket(st); if(sat == HTTP_CLIENT_SOCKET) { if(server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: HTTP connection input: %s\n", __FUNCTION__, (char*)ioa_network_buffer_data(in_buffer->nbh)); } handle_http_echo(ss->client_socket); } else if(sat == HTTPS_CLIENT_SOCKET) { //??? } else if (stun_is_channel_message_str(ioa_network_buffer_data(in_buffer->nbh), &blen, &chnum, is_padding_mandatory)) { if(ss->is_tcp_relay) { //Forbidden FUNCEND; return -1; } int rc = 0; if(blen<=orig_blen) { ioa_network_buffer_set_size(in_buffer->nbh,blen); rc = write_to_peerchannel(ss, chnum, in_buffer); } if (eve(server->verbose)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: wrote to peer %d bytes\n", __FUNCTION__, (int) rc); } FUNCEND; return 0; } else if (stun_is_command_message_full_check_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), 0, &(ss->enforce_fingerprints))) { ioa_network_buffer_handle nbh = ioa_network_buffer_allocate(server->e); int resp_constructed = 0; uint16_t method = stun_get_method_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); handle_turn_command(server, ss, in_buffer, nbh, &resp_constructed, can_resume); if((method != STUN_METHOD_BINDING) && (method != STUN_METHOD_SEND)) report_turn_session_info(server,ss,0); if(ss->to_be_closed || ioa_socket_tobeclosed(ss->client_socket)) { FUNCEND; ioa_network_buffer_delete(server->e, nbh); return 0; } if (resp_constructed) { if ((server->fingerprint) || ss->enforce_fingerprints) { size_t len = ioa_network_buffer_get_size(nbh); if (stun_attr_add_fingerprint_str(ioa_network_buffer_data(nbh), &len) < 0) { FUNCEND ; ioa_network_buffer_delete(server->e, nbh); return -1; } ioa_network_buffer_set_size(nbh, len); } int ret = write_client_connection(server, ss, nbh, TTL_IGNORE, TOS_IGNORE); FUNCEND ; return ret; } else { ioa_network_buffer_delete(server->e, nbh); return 0; } } else if (old_stun_is_command_message_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), &old_stun_cookie) && !(*(server->no_stun))) { ioa_network_buffer_handle nbh = ioa_network_buffer_allocate(server->e); int resp_constructed = 0; handle_old_stun_command(server, ss, in_buffer, nbh, &resp_constructed, old_stun_cookie); if (resp_constructed) { int ret = write_client_connection(server, ss, nbh, TTL_IGNORE, TOS_IGNORE); FUNCEND ; return ret; } else { ioa_network_buffer_delete(server->e, nbh); return 0; } } else { SOCKET_TYPE st = get_ioa_socket_type(ss->client_socket); if(is_stream_socket(st)) { if(is_http((char*)ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh))) { const char *proto = "HTTP"; if ((st == TCP_SOCKET) && ( try_acme_redirect( (char*)ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), server->acme_redirect, ss->client_socket ) == 0 ) ) { ss->to_be_closed = 1; return 0; } else if (*server->web_admin_listen_on_workers) { if(st==TLS_SOCKET) { proto = "HTTPS"; set_ioa_socket_app_type(ss->client_socket,HTTPS_CLIENT_SOCKET); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: %s (%s %s) request: %s\n", __FUNCTION__, proto, get_ioa_socket_cipher(ss->client_socket), get_ioa_socket_ssl_method(ss->client_socket), ioa_network_buffer_get_size(in_buffer->nbh)); if(server->send_https_socket) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s socket to be detached: 0x%lx, st=%d, sat=%d\n", __FUNCTION__,(long)ss->client_socket, get_ioa_socket_type(ss->client_socket), get_ioa_socket_app_type(ss->client_socket)); ioa_socket_handle new_s = detach_ioa_socket(ss->client_socket); if(new_s) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s new detached socket: 0x%lx, st=%d, sat=%d\n", __FUNCTION__,(long)new_s, get_ioa_socket_type(new_s), get_ioa_socket_app_type(new_s)); server->send_https_socket(new_s); } ss->to_be_closed = 1; } } else { set_ioa_socket_app_type(ss->client_socket,HTTP_CLIENT_SOCKET); if(server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: %s request: %s\n", __FUNCTION__, proto, ioa_network_buffer_get_size(in_buffer->nbh)); } handle_http_echo(ss->client_socket); } return 0; } else { ss->to_be_closed = 1; return 0; } } } } //Unrecognized message received, ignore it FUNCEND; return -1; } static int attach_socket_to_session(turn_turnserver* server, ioa_socket_handle s, ts_ur_super_session* ss) { int ret = -1; FUNCSTART; if(s && server && ss && !ioa_socket_tobeclosed(s)) { if(ss->client_socket != s) { IOA_CLOSE_SOCKET(ss->client_socket); ss->client_socket = s; if(register_callback_on_ioa_socket(server->e, s, IOA_EV_READ, client_input_handler, ss, 0)<0) { return -1; } set_ioa_socket_session(s, ss); } ret = 0; } FUNCEND; return ret; } int open_client_connection_session(turn_turnserver* server, struct socket_message *sm) { FUNCSTART; if (!server) return -1; if (!(sm->s)) return -1; ts_ur_super_session* ss = create_new_ss(server); ss->client_socket = sm->s; if(register_callback_on_ioa_socket(server->e, ss->client_socket, IOA_EV_READ, client_input_handler, ss, 0)<0) { return -1; } set_ioa_socket_session(ss->client_socket, ss); int at = TURN_MAX_ALLOCATE_TIMEOUT; if(*(server->stun_only)) at = TURN_MAX_ALLOCATE_TIMEOUT_STUN_ONLY; IOA_EVENT_DEL(ss->to_be_allocated_timeout_ev); ss->to_be_allocated_timeout_ev = set_ioa_timer(server->e, at, 0, client_to_be_allocated_timeout_handler, ss, 1, "client_to_be_allocated_timeout_handler"); if(sm->nd.nbh) { client_input_handler(ss->client_socket,IOA_EV_READ,&(sm->nd),ss,sm->can_resume); ioa_network_buffer_delete(server->e, sm->nd.nbh); sm->nd.nbh = NULL; } FUNCEND; return 0; } /////////////// io handlers /////////////////// static void peer_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *in_buffer, void *arg, int can_resume) { if (!(event_type & IOA_EV_READ) || !arg) return; if(in_buffer->recv_ttl==0) return; UNUSED_ARG(can_resume); if(!s || ioa_socket_tobeclosed(s)) return; ts_ur_super_session* ss = (ts_ur_super_session*) arg; if(!ss) return; if(ss->to_be_closed) return; if(!(ss->client_socket) || ioa_socket_tobeclosed(ss->client_socket)) return; turn_turnserver *server = (turn_turnserver*) (ss->server); if (!server) return; relay_endpoint_session* elem = get_relay_session_ss(ss, get_ioa_socket_address_family(s)); if (elem->s == NULL) { return; } int offset = STUN_CHANNEL_HEADER_LENGTH; int ilen = min((int)ioa_network_buffer_get_size(in_buffer->nbh), (int)(ioa_network_buffer_get_capacity_udp() - offset)); if (ilen >= 0) { ++(ss->peer_received_packets); ss->peer_received_bytes += ilen; turn_report_session_usage(ss, 0); allocation* a = get_allocation_ss(ss); if (is_allocation_valid(a)) { uint16_t chnum = 0; ioa_network_buffer_handle nbh = NULL; turn_permission_info* tinfo = allocation_get_permission(a, &(in_buffer->src_addr)); if (tinfo) { chnum = get_turn_channel_number(tinfo, &(in_buffer->src_addr)); } else if(!(server->server_relay)) { return; } if (chnum) { size_t len = (size_t)(ilen); nbh = in_buffer->nbh; ioa_network_buffer_add_offset_size(nbh, 0, STUN_CHANNEL_HEADER_LENGTH, ioa_network_buffer_get_size(nbh)+STUN_CHANNEL_HEADER_LENGTH); ioa_network_buffer_header_init(nbh); SOCKET_TYPE st = get_ioa_socket_type(ss->client_socket); int do_padding = is_stream_socket(st); stun_init_channel_message_str(chnum, ioa_network_buffer_data(nbh), &len, len, do_padding); ioa_network_buffer_set_size(nbh,len); in_buffer->nbh = NULL; if (eve(server->verbose)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: send channel 0x%x\n", __FUNCTION__, (int) (chnum)); } } else { size_t len = 0; nbh = ioa_network_buffer_allocate(server->e); stun_init_indication_str(STUN_METHOD_DATA, ioa_network_buffer_data(nbh), &len); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_DATA, ioa_network_buffer_data(in_buffer->nbh), (size_t)ilen); stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, &(in_buffer->src_addr)); ioa_network_buffer_set_size(nbh,len); { const uint8_t *field = (const uint8_t *) get_version(server); size_t fsz = strlen(get_version(server)); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_SOFTWARE, field, fsz); ioa_network_buffer_set_size(nbh, len); } if ((server->fingerprint) || ss->enforce_fingerprints) { size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_fingerprint_str(ioa_network_buffer_data(nbh), &len); ioa_network_buffer_set_size(nbh, len); } } if (eve(server->verbose)) { uint16_t* t = (uint16_t*) ioa_network_buffer_data(nbh); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Send data: 0x%x\n", (int) (nswap16(t[0]))); } write_client_connection(server, ss, nbh, in_buffer->recv_ttl-1, in_buffer->recv_tos); } } } static void client_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *data, void *arg, int can_resume) { if (!arg) return; UNUSED_ARG(s); UNUSED_ARG(event_type); ts_ur_super_session* ss = (ts_ur_super_session*)arg; turn_turnserver *server = (turn_turnserver*)ss->server; if (!server) { return; } if (ss->client_socket != s) { return; } read_client_connection(server, ss, data, can_resume, 1); if (ss->to_be_closed) { if(server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: client socket to be closed in client handler: ss=0x%lx\n", (unsigned long long)(ss->id), (long)ss); } set_ioa_socket_tobeclosed(s); } } /////////////////////////////////////////////////////////// void init_turn_server(turn_turnserver* server, turnserver_id id, int verbose, ioa_engine_handle e, turn_credential_type ct, int stun_port, int fingerprint, dont_fragment_option_t dont_fragment, get_user_key_cb userkeycb, check_new_allocation_quota_cb chquotacb, release_allocation_quota_cb raqcb, ioa_addr *external_ip, vintp check_origin, vintp no_tcp_relay, vintp no_udp_relay, vintp stale_nonce, vintp max_allocate_lifetime, vintp channel_lifetime, vintp permission_lifetime, vintp stun_only, vintp no_stun, vintp no_software_attribute, vintp web_admin_listen_on_workers, turn_server_addrs_list_t *alternate_servers_list, turn_server_addrs_list_t *tls_alternate_servers_list, turn_server_addrs_list_t *aux_servers_list, int self_udp_balance, vintp no_multicast_peers, vintp allow_loopback_peers, ip_range_list_t* ip_whitelist, ip_range_list_t* ip_blacklist, send_socket_to_relay_cb send_socket_to_relay, vintp secure_stun, vintp mobility, int server_relay, send_turn_session_info_cb send_turn_session_info, send_https_socket_cb send_https_socket, allocate_bps_cb allocate_bps_func, int oauth, const char* oauth_server_name, const char* acme_redirect, int keep_address_family, vintp log_binding) { if (!server) return; bzero(server,sizeof(turn_turnserver)); server->e = e; server->id = id; server->ctime = turn_time(); server->session_id_counter = 0; server->sessions_map = ur_map_create(); server->tcp_relay_connections = ur_map_create(); server->ct = ct; server->userkeycb = userkeycb; server->chquotacb = chquotacb; server->raqcb = raqcb; server->no_multicast_peers = no_multicast_peers; server->allow_loopback_peers = allow_loopback_peers; server->secure_stun = secure_stun; server->mobility = mobility; server->server_relay = server_relay; server->send_turn_session_info = send_turn_session_info; server->send_https_socket = send_https_socket; server->oauth = oauth; if(oauth) server->oauth_server_name = oauth_server_name; if(mobility) server->mobile_connections_map = ur_map_create(); server->acme_redirect = acme_redirect; TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"turn server id=%d created\n",(int)id); server->check_origin = check_origin; server->no_tcp_relay = no_tcp_relay; server->no_udp_relay = no_udp_relay; server->alternate_servers_list = alternate_servers_list; server->tls_alternate_servers_list = tls_alternate_servers_list; server->aux_servers_list = aux_servers_list; server->self_udp_balance = self_udp_balance; server->stale_nonce = stale_nonce; server->max_allocate_lifetime = max_allocate_lifetime; server->channel_lifetime = channel_lifetime; server->permission_lifetime = permission_lifetime; server->stun_only = stun_only; server->no_stun = no_stun; server->no_software_attribute = no_software_attribute; server-> web_admin_listen_on_workers = web_admin_listen_on_workers; server->dont_fragment = dont_fragment; server->fingerprint = fingerprint; if(external_ip) { addr_cpy(&(server->external_ip), external_ip); server->external_ip_set = 1; } if (stun_port < 1) stun_port = DEFAULT_STUN_PORT; server->verbose = verbose; server->ip_whitelist = ip_whitelist; server->ip_blacklist = ip_blacklist; server->send_socket_to_relay = send_socket_to_relay; server->allocate_bps_func = allocate_bps_func; server->keep_address_family = keep_address_family; set_ioa_timer(server->e, 1, 0, timer_timeout_handler, server, 1, "timer_timeout_handler"); server->log_binding = log_binding; } ioa_engine_handle turn_server_get_engine(turn_turnserver *s) { if(s) return s->e; return NULL; } void set_disconnect_cb(turn_turnserver* server, int(*disconnect)( ts_ur_super_session*)) { server->disconnect = disconnect; } //////////////////////////////////////////////////////////////////
./CrossVul/dataset_final_sorted/CWE-441/c/good_4375_2
crossvul-cpp_data_bad_4375_0
/* * Copyright (C) 2011, 2012, 2013 Citrix Systems * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ns_turn_ioaddr.h" #include <netdb.h> #include <string.h> ////////////////////////////////////////////////////////////// uint32_t get_ioa_addr_len(const ioa_addr* addr) { if(addr->ss.sa_family == AF_INET) return sizeof(struct sockaddr_in); else if(addr->ss.sa_family == AF_INET6) return sizeof(struct sockaddr_in6); return 0; } /////////////////////////////////////////////////////////////// void addr_set_any(ioa_addr *addr) { if(addr) bzero(addr,sizeof(ioa_addr)); } int addr_any(const ioa_addr* addr) { if(!addr) return 1; if(addr->ss.sa_family == AF_INET) { return ((addr->s4.sin_addr.s_addr==0)&&(addr->s4.sin_port==0)); } else if(addr->ss.sa_family == AF_INET6) { if(addr->s6.sin6_port!=0) return 0; else { size_t i; for(i=0;i<sizeof(addr->s6.sin6_addr);i++) if(((const char*)&(addr->s6.sin6_addr))[i]) return 0; } } return 1; } int addr_any_no_port(const ioa_addr* addr) { if(!addr) return 1; if(addr->ss.sa_family == AF_INET) { return (addr->s4.sin_addr.s_addr==0); } else if(addr->ss.sa_family == AF_INET6) { size_t i; for(i=0;i<sizeof(addr->s6.sin6_addr);i++) if(((const char*)(&(addr->s6.sin6_addr)))[i]) return 0; } return 1; } uint32_t hash_int32(uint32_t a) { a = a ^ (a>>4); a = (a^0xdeadbeef) + (a<<5); a = a ^ (a>>11); return a; } uint64_t hash_int64(uint64_t a) { a = a ^ (a>>4); a = (a^0xdeadbeefdeadbeefLL) + (a<<5); a = a ^ (a>>11); return a; } uint32_t addr_hash(const ioa_addr *addr) { if(!addr) return 0; uint32_t ret = 0; if (addr->ss.sa_family == AF_INET) { ret = hash_int32(addr->s4.sin_addr.s_addr + addr->s4.sin_port); } else { uint64_t a[2]; bcopy(&(addr->s6.sin6_addr), &a, sizeof(a)); ret = (uint32_t)((hash_int64(a[0])<<3) + (hash_int64(a[1] + addr->s6.sin6_port))); } return ret; } uint32_t addr_hash_no_port(const ioa_addr *addr) { if(!addr) return 0; uint32_t ret = 0; if (addr->ss.sa_family == AF_INET) { ret = hash_int32(addr->s4.sin_addr.s_addr); } else { uint64_t a[2]; bcopy(&(addr->s6.sin6_addr), &a, sizeof(a)); ret = (uint32_t)((hash_int64(a[0])<<3) + (hash_int64(a[1]))); } return ret; } void addr_cpy(ioa_addr* dst, const ioa_addr* src) { if(dst && src) bcopy(src,dst,sizeof(ioa_addr)); } void addr_cpy4(ioa_addr* dst, const struct sockaddr_in* src) { if(src && dst) bcopy(src,dst,sizeof(struct sockaddr_in)); } void addr_cpy6(ioa_addr* dst, const struct sockaddr_in6* src) { if(src && dst) bcopy(src,dst,sizeof(struct sockaddr_in6)); } int addr_eq(const ioa_addr* a1, const ioa_addr *a2) { if(!a1) return (!a2); else if(!a2) return (!a1); if(a1->ss.sa_family == a2->ss.sa_family) { if(a1->ss.sa_family == AF_INET && a1->s4.sin_port == a2->s4.sin_port) { if((int)a1->s4.sin_addr.s_addr == (int)a2->s4.sin_addr.s_addr) { return 1; } } else if(a1->ss.sa_family == AF_INET6 && a1->s6.sin6_port == a2->s6.sin6_port) { if( memcmp(&(a1->s6.sin6_addr), &(a2->s6.sin6_addr) ,sizeof(struct in6_addr)) == 0 ) { return 1; } } } return 0; } int addr_eq_no_port(const ioa_addr* a1, const ioa_addr *a2) { if(!a1) return (!a2); else if(!a2) return (!a1); if(a1->ss.sa_family == a2->ss.sa_family) { if(a1->ss.sa_family == AF_INET) { if((int)a1->s4.sin_addr.s_addr == (int)a2->s4.sin_addr.s_addr) { return 1; } } else if(a1->ss.sa_family == AF_INET6) { if( memcmp(&(a1->s6.sin6_addr), &(a2->s6.sin6_addr) ,sizeof(struct in6_addr)) == 0 ) { return 1; } } } return 0; } int make_ioa_addr(const uint8_t* saddr0, int port, ioa_addr *addr) { if(!saddr0 || !addr) return -1; char ssaddr[257]; STRCPY(ssaddr,saddr0); char* saddr=ssaddr; while(*saddr == ' ') ++saddr; size_t len=strlen(saddr); while(len>0) { if(saddr[len-1]==' ') { saddr[len-1]=0; --len; } else { break; } } bzero(addr, sizeof(ioa_addr)); if((len == 0)|| (inet_pton(AF_INET, saddr, &addr->s4.sin_addr) == 1)) { addr->s4.sin_family = AF_INET; #if defined(TURN_HAS_SIN_LEN) /* tested when configured */ addr->s4.sin_len = sizeof(struct sockaddr_in); #endif addr->s4.sin_port = nswap16(port); } else if (inet_pton(AF_INET6, saddr, &addr->s6.sin6_addr) == 1) { addr->s6.sin6_family = AF_INET6; #if defined(SIN6_LEN) /* this define is required by IPv6 if used */ addr->s6.sin6_len = sizeof(struct sockaddr_in6); #endif addr->s6.sin6_port = nswap16(port); } else { struct addrinfo addr_hints; struct addrinfo *addr_result = NULL; int err; memset(&addr_hints, 0, sizeof(struct addrinfo)); addr_hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ addr_hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */ addr_hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */ addr_hints.ai_protocol = 0; /* Any protocol */ addr_hints.ai_canonname = NULL; addr_hints.ai_addr = NULL; addr_hints.ai_next = NULL; err = getaddrinfo(saddr, NULL, &addr_hints, &addr_result); if ((err != 0)||(!addr_result)) { fprintf(stderr,"error resolving '%s' hostname: %s\n",saddr,gai_strerror(err)); return -1; } int family = AF_INET; struct addrinfo *addr_result_orig = addr_result; int found = 0; beg_af: while(addr_result) { if(addr_result->ai_family == family) { if (addr_result->ai_family == AF_INET) { bcopy(addr_result->ai_addr, addr, addr_result->ai_addrlen); addr->s4.sin_port = nswap16(port); #if defined(TURN_HAS_SIN_LEN) /* tested when configured */ addr->s4.sin_len = sizeof(struct sockaddr_in); #endif found = 1; break; } else if (addr_result->ai_family == AF_INET6) { bcopy(addr_result->ai_addr, addr, addr_result->ai_addrlen); addr->s6.sin6_port = nswap16(port); #if defined(SIN6_LEN) /* this define is required by IPv6 if used */ addr->s6.sin6_len = sizeof(struct sockaddr_in6); #endif found = 1; break; } } addr_result = addr_result->ai_next; } if(!found && family == AF_INET) { family = AF_INET6; addr_result = addr_result_orig; goto beg_af; } freeaddrinfo(addr_result_orig); } return 0; } static char* get_addr_string_and_port(char* s0, int *port) { char *s = s0; while(*s && (*s==' ')) ++s; if(*s == '[') { ++s; char *tail = strstr(s,"]"); if(tail) { *tail=0; ++tail; while(*tail && (*tail==' ')) ++tail; if(*tail==':') { ++tail; *port = atoi(tail); return s; } else if(*tail == 0) { *port = 0; return s; } } } else { char *tail = strstr(s,":"); if(tail) { *tail = 0; ++tail; *port = atoi(tail); return s; } else { *port = 0; return s; } } return NULL; } int make_ioa_addr_from_full_string(const uint8_t* saddr, int default_port, ioa_addr *addr) { if(!addr) return -1; int ret = -1; int port = 0; char* s = strdup((const char*)saddr); char *sa = get_addr_string_and_port(s,&port); if(sa) { if(port<1) port = default_port; ret = make_ioa_addr((uint8_t*)sa,port,addr); } free(s); return ret; } int addr_to_string(const ioa_addr* addr, uint8_t* saddr) { if (addr && saddr) { char addrtmp[INET6_ADDRSTRLEN]; if (addr->ss.sa_family == AF_INET) { inet_ntop(AF_INET, &addr->s4.sin_addr, addrtmp, INET_ADDRSTRLEN); if(addr_get_port(addr)>0) snprintf((char*)saddr, MAX_IOA_ADDR_STRING, "%s:%d", addrtmp, addr_get_port(addr)); else strncpy((char*)saddr, addrtmp, MAX_IOA_ADDR_STRING); } else if (addr->ss.sa_family == AF_INET6) { inet_ntop(AF_INET6, &addr->s6.sin6_addr, addrtmp, INET6_ADDRSTRLEN); if(addr_get_port(addr)>0) snprintf((char*)saddr, MAX_IOA_ADDR_STRING, "[%s]:%d", addrtmp, addr_get_port(addr)); else strncpy((char*)saddr, addrtmp, MAX_IOA_ADDR_STRING); } else { return -1; } return 0; } return -1; } int addr_to_string_no_port(const ioa_addr* addr, uint8_t* saddr) { if (addr && saddr) { char addrtmp[MAX_IOA_ADDR_STRING]; if (addr->ss.sa_family == AF_INET) { inet_ntop(AF_INET, &addr->s4.sin_addr, addrtmp, INET_ADDRSTRLEN); strncpy((char*)saddr, addrtmp, MAX_IOA_ADDR_STRING); } else if (addr->ss.sa_family == AF_INET6) { inet_ntop(AF_INET6, &addr->s6.sin6_addr, addrtmp, INET6_ADDRSTRLEN); strncpy((char*)saddr, addrtmp, MAX_IOA_ADDR_STRING); } else { return -1; } return 0; } return -1; } void addr_set_port(ioa_addr* addr, int port) { if(addr) { if(addr->s4.sin_family == AF_INET) { addr->s4.sin_port = nswap16(port); } else if(addr->s6.sin6_family == AF_INET6) { addr->s6.sin6_port = nswap16(port); } } } int addr_get_port(const ioa_addr* addr) { if(!addr) return 0; if(addr->s4.sin_family == AF_INET) { return nswap16(addr->s4.sin_port); } else if(addr->s6.sin6_family == AF_INET6) { return nswap16(addr->s6.sin6_port); } return 0; } ///////////////////////////////////////////////////////////////////////////// void ioa_addr_range_set(ioa_addr_range* range, const ioa_addr* addr_min, const ioa_addr* addr_max) { if(range) { if(addr_min) addr_cpy(&(range->min),addr_min); else addr_set_any(&(range->min)); if(addr_max) addr_cpy(&(range->max),addr_max); else addr_set_any(&(range->max)); } } int addr_less_eq(const ioa_addr* addr1, const ioa_addr* addr2) { if(!addr1) return 1; else if(!addr2) return 0; else { if(addr1->ss.sa_family != addr2->ss.sa_family) return (addr1->ss.sa_family < addr2->ss.sa_family); else if(addr1->ss.sa_family == AF_INET) { return ((uint32_t)nswap32(addr1->s4.sin_addr.s_addr) <= (uint32_t)nswap32(addr2->s4.sin_addr.s_addr)); } else if(addr1->ss.sa_family == AF_INET6) { int i; for(i=0;i<16;i++) { if((uint8_t)(((const char*)&(addr1->s6.sin6_addr))[i]) > (uint8_t)(((const char*)&(addr2->s6.sin6_addr))[i])) return 0; } return 1; } else return 1; } } int ioa_addr_in_range(const ioa_addr_range* range, const ioa_addr* addr) { if(range && addr) { if(addr_any(&(range->min)) || addr_less_eq(&(range->min),addr)) { if(addr_any(&(range->max))) { return 1; } else { return addr_less_eq(addr,&(range->max)); } } } return 0; } void ioa_addr_range_cpy(ioa_addr_range* dest, const ioa_addr_range* src) { if(dest && src) { addr_cpy(&(dest->min),&(src->min)); addr_cpy(&(dest->max),&(src->max)); } } /////// Check whether this is a good address ////////////// int ioa_addr_is_multicast(ioa_addr *addr) { if(addr) { if(addr->ss.sa_family == AF_INET) { const uint8_t *u = ((const uint8_t*)&(addr->s4.sin_addr)); return (u[0] > 223); } else if(addr->ss.sa_family == AF_INET6) { uint8_t u = ((const uint8_t*)&(addr->s6.sin6_addr))[0]; return (u == 255); } } return 0; } int ioa_addr_is_loopback(ioa_addr *addr) { if(addr) { if(addr->ss.sa_family == AF_INET) { const uint8_t *u = ((const uint8_t*)&(addr->s4.sin_addr)); return (u[0] == 127); } else if(addr->ss.sa_family == AF_INET6) { const uint8_t *u = ((const uint8_t*)&(addr->s6.sin6_addr)); if(u[7] == 1) { int i; for(i=0;i<7;++i) { if(u[i]) return 0; } return 1; } } } return 0; } /////// Map "public" address to "private" address ////////////// // Must be called only in a single-threaded context, // before the program starts spawning threads: static ioa_addr **public_addrs = NULL; static ioa_addr **private_addrs = NULL; static size_t mcount = 0; static size_t msz = 0; void ioa_addr_add_mapping(ioa_addr *apub, ioa_addr *apriv) { size_t new_size = msz + sizeof(ioa_addr*); public_addrs = (ioa_addr**)realloc(public_addrs, new_size); private_addrs = (ioa_addr**)realloc(private_addrs, new_size); public_addrs[mcount]=(ioa_addr*)malloc(sizeof(ioa_addr)); private_addrs[mcount]=(ioa_addr*)malloc(sizeof(ioa_addr)); addr_cpy(public_addrs[mcount],apub); addr_cpy(private_addrs[mcount],apriv); ++mcount; msz += sizeof(ioa_addr*); } void map_addr_from_public_to_private(const ioa_addr *public_addr, ioa_addr *private_addr) { size_t i; for(i=0;i<mcount;++i) { if(addr_eq_no_port(public_addr,public_addrs[i])) { addr_cpy(private_addr,private_addrs[i]); addr_set_port(private_addr,addr_get_port(public_addr)); return; } } addr_cpy(private_addr,public_addr); } void map_addr_from_private_to_public(const ioa_addr *private_addr, ioa_addr *public_addr) { size_t i; for(i=0;i<mcount;++i) { if(addr_eq_no_port(private_addr,private_addrs[i])) { addr_cpy(public_addr,public_addrs[i]); addr_set_port(public_addr,addr_get_port(private_addr)); return; } } addr_cpy(public_addr,private_addr); } //////////////////////////////////////////////////////////////////////////////
./CrossVul/dataset_final_sorted/CWE-441/c/bad_4375_0
crossvul-cpp_data_good_4375_0
/* * Copyright (C) 2011, 2012, 2013 Citrix Systems * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ns_turn_ioaddr.h" #include <netdb.h> #include <string.h> ////////////////////////////////////////////////////////////// uint32_t get_ioa_addr_len(const ioa_addr* addr) { if(addr->ss.sa_family == AF_INET) return sizeof(struct sockaddr_in); else if(addr->ss.sa_family == AF_INET6) return sizeof(struct sockaddr_in6); return 0; } /////////////////////////////////////////////////////////////// void addr_set_any(ioa_addr *addr) { if(addr) bzero(addr,sizeof(ioa_addr)); } int addr_any(const ioa_addr* addr) { if(!addr) return 1; if(addr->ss.sa_family == AF_INET) { return ((addr->s4.sin_addr.s_addr==0)&&(addr->s4.sin_port==0)); } else if(addr->ss.sa_family == AF_INET6) { if(addr->s6.sin6_port!=0) return 0; else { size_t i; for(i=0;i<sizeof(addr->s6.sin6_addr);i++) if(((const char*)&(addr->s6.sin6_addr))[i]) return 0; } } return 1; } int addr_any_no_port(const ioa_addr* addr) { if(!addr) return 1; if(addr->ss.sa_family == AF_INET) { return (addr->s4.sin_addr.s_addr==0); } else if(addr->ss.sa_family == AF_INET6) { size_t i; for(i=0;i<sizeof(addr->s6.sin6_addr);i++) if(((const char*)(&(addr->s6.sin6_addr)))[i]) return 0; } return 1; } uint32_t hash_int32(uint32_t a) { a = a ^ (a>>4); a = (a^0xdeadbeef) + (a<<5); a = a ^ (a>>11); return a; } uint64_t hash_int64(uint64_t a) { a = a ^ (a>>4); a = (a^0xdeadbeefdeadbeefLL) + (a<<5); a = a ^ (a>>11); return a; } uint32_t addr_hash(const ioa_addr *addr) { if(!addr) return 0; uint32_t ret = 0; if (addr->ss.sa_family == AF_INET) { ret = hash_int32(addr->s4.sin_addr.s_addr + addr->s4.sin_port); } else { uint64_t a[2]; bcopy(&(addr->s6.sin6_addr), &a, sizeof(a)); ret = (uint32_t)((hash_int64(a[0])<<3) + (hash_int64(a[1] + addr->s6.sin6_port))); } return ret; } uint32_t addr_hash_no_port(const ioa_addr *addr) { if(!addr) return 0; uint32_t ret = 0; if (addr->ss.sa_family == AF_INET) { ret = hash_int32(addr->s4.sin_addr.s_addr); } else { uint64_t a[2]; bcopy(&(addr->s6.sin6_addr), &a, sizeof(a)); ret = (uint32_t)((hash_int64(a[0])<<3) + (hash_int64(a[1]))); } return ret; } void addr_cpy(ioa_addr* dst, const ioa_addr* src) { if(dst && src) bcopy(src,dst,sizeof(ioa_addr)); } void addr_cpy4(ioa_addr* dst, const struct sockaddr_in* src) { if(src && dst) bcopy(src,dst,sizeof(struct sockaddr_in)); } void addr_cpy6(ioa_addr* dst, const struct sockaddr_in6* src) { if(src && dst) bcopy(src,dst,sizeof(struct sockaddr_in6)); } int addr_eq(const ioa_addr* a1, const ioa_addr *a2) { if(!a1) return (!a2); else if(!a2) return (!a1); if(a1->ss.sa_family == a2->ss.sa_family) { if(a1->ss.sa_family == AF_INET && a1->s4.sin_port == a2->s4.sin_port) { if((int)a1->s4.sin_addr.s_addr == (int)a2->s4.sin_addr.s_addr) { return 1; } } else if(a1->ss.sa_family == AF_INET6 && a1->s6.sin6_port == a2->s6.sin6_port) { if( memcmp(&(a1->s6.sin6_addr), &(a2->s6.sin6_addr) ,sizeof(struct in6_addr)) == 0 ) { return 1; } } } return 0; } int addr_eq_no_port(const ioa_addr* a1, const ioa_addr *a2) { if(!a1) return (!a2); else if(!a2) return (!a1); if(a1->ss.sa_family == a2->ss.sa_family) { if(a1->ss.sa_family == AF_INET) { if((int)a1->s4.sin_addr.s_addr == (int)a2->s4.sin_addr.s_addr) { return 1; } } else if(a1->ss.sa_family == AF_INET6) { if( memcmp(&(a1->s6.sin6_addr), &(a2->s6.sin6_addr) ,sizeof(struct in6_addr)) == 0 ) { return 1; } } } return 0; } int make_ioa_addr(const uint8_t* saddr0, int port, ioa_addr *addr) { if(!saddr0 || !addr) return -1; char ssaddr[257]; STRCPY(ssaddr,saddr0); char* saddr=ssaddr; while(*saddr == ' ') ++saddr; size_t len=strlen(saddr); while(len>0) { if(saddr[len-1]==' ') { saddr[len-1]=0; --len; } else { break; } } bzero(addr, sizeof(ioa_addr)); if((len == 0)|| (inet_pton(AF_INET, saddr, &addr->s4.sin_addr) == 1)) { addr->s4.sin_family = AF_INET; #if defined(TURN_HAS_SIN_LEN) /* tested when configured */ addr->s4.sin_len = sizeof(struct sockaddr_in); #endif addr->s4.sin_port = nswap16(port); } else if (inet_pton(AF_INET6, saddr, &addr->s6.sin6_addr) == 1) { addr->s6.sin6_family = AF_INET6; #if defined(SIN6_LEN) /* this define is required by IPv6 if used */ addr->s6.sin6_len = sizeof(struct sockaddr_in6); #endif addr->s6.sin6_port = nswap16(port); } else { struct addrinfo addr_hints; struct addrinfo *addr_result = NULL; int err; memset(&addr_hints, 0, sizeof(struct addrinfo)); addr_hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ addr_hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */ addr_hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */ addr_hints.ai_protocol = 0; /* Any protocol */ addr_hints.ai_canonname = NULL; addr_hints.ai_addr = NULL; addr_hints.ai_next = NULL; err = getaddrinfo(saddr, NULL, &addr_hints, &addr_result); if ((err != 0)||(!addr_result)) { fprintf(stderr,"error resolving '%s' hostname: %s\n",saddr,gai_strerror(err)); return -1; } int family = AF_INET; struct addrinfo *addr_result_orig = addr_result; int found = 0; beg_af: while(addr_result) { if(addr_result->ai_family == family) { if (addr_result->ai_family == AF_INET) { bcopy(addr_result->ai_addr, addr, addr_result->ai_addrlen); addr->s4.sin_port = nswap16(port); #if defined(TURN_HAS_SIN_LEN) /* tested when configured */ addr->s4.sin_len = sizeof(struct sockaddr_in); #endif found = 1; break; } else if (addr_result->ai_family == AF_INET6) { bcopy(addr_result->ai_addr, addr, addr_result->ai_addrlen); addr->s6.sin6_port = nswap16(port); #if defined(SIN6_LEN) /* this define is required by IPv6 if used */ addr->s6.sin6_len = sizeof(struct sockaddr_in6); #endif found = 1; break; } } addr_result = addr_result->ai_next; } if(!found && family == AF_INET) { family = AF_INET6; addr_result = addr_result_orig; goto beg_af; } freeaddrinfo(addr_result_orig); } return 0; } static char* get_addr_string_and_port(char* s0, int *port) { char *s = s0; while(*s && (*s==' ')) ++s; if(*s == '[') { ++s; char *tail = strstr(s,"]"); if(tail) { *tail=0; ++tail; while(*tail && (*tail==' ')) ++tail; if(*tail==':') { ++tail; *port = atoi(tail); return s; } else if(*tail == 0) { *port = 0; return s; } } } else { char *tail = strstr(s,":"); if(tail) { *tail = 0; ++tail; *port = atoi(tail); return s; } else { *port = 0; return s; } } return NULL; } int make_ioa_addr_from_full_string(const uint8_t* saddr, int default_port, ioa_addr *addr) { if(!addr) return -1; int ret = -1; int port = 0; char* s = strdup((const char*)saddr); char *sa = get_addr_string_and_port(s,&port); if(sa) { if(port<1) port = default_port; ret = make_ioa_addr((uint8_t*)sa,port,addr); } free(s); return ret; } int addr_to_string(const ioa_addr* addr, uint8_t* saddr) { if (addr && saddr) { char addrtmp[INET6_ADDRSTRLEN]; if (addr->ss.sa_family == AF_INET) { inet_ntop(AF_INET, &addr->s4.sin_addr, addrtmp, INET_ADDRSTRLEN); if(addr_get_port(addr)>0) snprintf((char*)saddr, MAX_IOA_ADDR_STRING, "%s:%d", addrtmp, addr_get_port(addr)); else strncpy((char*)saddr, addrtmp, MAX_IOA_ADDR_STRING); } else if (addr->ss.sa_family == AF_INET6) { inet_ntop(AF_INET6, &addr->s6.sin6_addr, addrtmp, INET6_ADDRSTRLEN); if(addr_get_port(addr)>0) snprintf((char*)saddr, MAX_IOA_ADDR_STRING, "[%s]:%d", addrtmp, addr_get_port(addr)); else strncpy((char*)saddr, addrtmp, MAX_IOA_ADDR_STRING); } else { return -1; } return 0; } return -1; } int addr_to_string_no_port(const ioa_addr* addr, uint8_t* saddr) { if (addr && saddr) { char addrtmp[MAX_IOA_ADDR_STRING]; if (addr->ss.sa_family == AF_INET) { inet_ntop(AF_INET, &addr->s4.sin_addr, addrtmp, INET_ADDRSTRLEN); strncpy((char*)saddr, addrtmp, MAX_IOA_ADDR_STRING); } else if (addr->ss.sa_family == AF_INET6) { inet_ntop(AF_INET6, &addr->s6.sin6_addr, addrtmp, INET6_ADDRSTRLEN); strncpy((char*)saddr, addrtmp, MAX_IOA_ADDR_STRING); } else { return -1; } return 0; } return -1; } void addr_set_port(ioa_addr* addr, int port) { if(addr) { if(addr->s4.sin_family == AF_INET) { addr->s4.sin_port = nswap16(port); } else if(addr->s6.sin6_family == AF_INET6) { addr->s6.sin6_port = nswap16(port); } } } int addr_get_port(const ioa_addr* addr) { if(!addr) return 0; if(addr->s4.sin_family == AF_INET) { return nswap16(addr->s4.sin_port); } else if(addr->s6.sin6_family == AF_INET6) { return nswap16(addr->s6.sin6_port); } return 0; } ///////////////////////////////////////////////////////////////////////////// void ioa_addr_range_set(ioa_addr_range* range, const ioa_addr* addr_min, const ioa_addr* addr_max) { if(range) { if(addr_min) addr_cpy(&(range->min),addr_min); else addr_set_any(&(range->min)); if(addr_max) addr_cpy(&(range->max),addr_max); else addr_set_any(&(range->max)); } } int addr_less_eq(const ioa_addr* addr1, const ioa_addr* addr2) { if(!addr1) return 1; else if(!addr2) return 0; else { if(addr1->ss.sa_family != addr2->ss.sa_family) return (addr1->ss.sa_family < addr2->ss.sa_family); else if(addr1->ss.sa_family == AF_INET) { return ((uint32_t)nswap32(addr1->s4.sin_addr.s_addr) <= (uint32_t)nswap32(addr2->s4.sin_addr.s_addr)); } else if(addr1->ss.sa_family == AF_INET6) { int i; for(i=0;i<16;i++) { if((uint8_t)(((const char*)&(addr1->s6.sin6_addr))[i]) > (uint8_t)(((const char*)&(addr2->s6.sin6_addr))[i])) return 0; } return 1; } else return 1; } } int ioa_addr_in_range(const ioa_addr_range* range, const ioa_addr* addr) { if(range && addr) { if(addr_any(&(range->min)) || addr_less_eq(&(range->min),addr)) { if(addr_any(&(range->max))) { return 1; } else { return addr_less_eq(addr,&(range->max)); } } } return 0; } void ioa_addr_range_cpy(ioa_addr_range* dest, const ioa_addr_range* src) { if(dest && src) { addr_cpy(&(dest->min),&(src->min)); addr_cpy(&(dest->max),&(src->max)); } } /////// Check whether this is a good address ////////////// int ioa_addr_is_multicast(ioa_addr *addr) { if(addr) { if(addr->ss.sa_family == AF_INET) { const uint8_t *u = ((const uint8_t*)&(addr->s4.sin_addr)); return (u[0] > 223); } else if(addr->ss.sa_family == AF_INET6) { uint8_t u = ((const uint8_t*)&(addr->s6.sin6_addr))[0]; return (u == 255); } } return 0; } int ioa_addr_is_loopback(ioa_addr *addr) { if(addr) { if(addr->ss.sa_family == AF_INET) { const uint8_t *u = ((const uint8_t*)&(addr->s4.sin_addr)); return (u[0] == 127); } else if(addr->ss.sa_family == AF_INET6) { const uint8_t *u = ((const uint8_t*)&(addr->s6.sin6_addr)); if(u[15] == 1) { int i; for(i=0;i<15;++i) { if(u[i]) return 0; } return 1; } } } return 0; } /* To avoid a vulnerability this function checks whether the addr is in 0.0.0.0/8 or ::/128. Source from (INADDR_ANY) 0.0.0.0/32 and (in6addr_any) ::/128 routed to loopback on Linux systems for old BSD backward compatibility. https://github.com/torvalds/linux/blob/a2f5ea9e314ba6778f885c805c921e9362ec0420/net/ipv6/tcp_ipv6.c#L182 To avoid any trouble we match the whole 0.0.0.0/8 that defined in RFC6890 as local network "this". */ int ioa_addr_is_zero(ioa_addr *addr) { if(addr) { if(addr->ss.sa_family == AF_INET) { const uint8_t *u = ((const uint8_t*)&(addr->s4.sin_addr)); return (u[0] == 0); } else if(addr->ss.sa_family == AF_INET6) { const uint8_t *u = ((const uint8_t*)&(addr->s6.sin6_addr)); int i; for(i=0;i<=15;++i) { if(u[i]) return 0; } return 1; } } return 0; } /////// Map "public" address to "private" address ////////////// // Must be called only in a single-threaded context, // before the program starts spawning threads: static ioa_addr **public_addrs = NULL; static ioa_addr **private_addrs = NULL; static size_t mcount = 0; static size_t msz = 0; void ioa_addr_add_mapping(ioa_addr *apub, ioa_addr *apriv) { size_t new_size = msz + sizeof(ioa_addr*); public_addrs = (ioa_addr**)realloc(public_addrs, new_size); private_addrs = (ioa_addr**)realloc(private_addrs, new_size); public_addrs[mcount]=(ioa_addr*)malloc(sizeof(ioa_addr)); private_addrs[mcount]=(ioa_addr*)malloc(sizeof(ioa_addr)); addr_cpy(public_addrs[mcount],apub); addr_cpy(private_addrs[mcount],apriv); ++mcount; msz += sizeof(ioa_addr*); } void map_addr_from_public_to_private(const ioa_addr *public_addr, ioa_addr *private_addr) { size_t i; for(i=0;i<mcount;++i) { if(addr_eq_no_port(public_addr,public_addrs[i])) { addr_cpy(private_addr,private_addrs[i]); addr_set_port(private_addr,addr_get_port(public_addr)); return; } } addr_cpy(private_addr,public_addr); } void map_addr_from_private_to_public(const ioa_addr *private_addr, ioa_addr *public_addr) { size_t i; for(i=0;i<mcount;++i) { if(addr_eq_no_port(private_addr,private_addrs[i])) { addr_cpy(public_addr,public_addrs[i]); addr_set_port(public_addr,addr_get_port(private_addr)); return; } } addr_cpy(public_addr,private_addr); } //////////////////////////////////////////////////////////////////////////////
./CrossVul/dataset_final_sorted/CWE-441/c/good_4375_0
crossvul-cpp_data_bad_4375_2
/* * Copyright (C) 2011, 2012, 2013 Citrix Systems * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ns_turn_server.h" #include "ns_turn_utils.h" #include "ns_turn_allocation.h" #include "ns_turn_msg_addr.h" #include "ns_turn_ioalib.h" #include "../apps/relay/ns_ioalib_impl.h" /////////////////////////////////////////// #define FUNCSTART if(server && eve(server->verbose)) TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"%s:%d:start\n",__FUNCTION__,__LINE__) #define FUNCEND if(server && eve(server->verbose)) TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"%s:%d:end\n",__FUNCTION__,__LINE__) //////////////////////////////////////////////// static inline int get_family(int stun_family, ioa_engine_handle e, ioa_socket_handle client_socket) { switch(stun_family) { case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4: return AF_INET; break; case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6: return AF_INET6; break; case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_DEFAULT: if(e->default_relays && get_ioa_socket_address_family(client_socket) == AF_INET6) return AF_INET6; else return AF_INET; default: return AF_INET; }; } //////////////////////////////////////////////// const char * get_version(turn_turnserver *server) { if(server && !*server->no_software_attribute) { return (const char *) TURN_SOFTWARE; } else { return (const char *) "None"; } } #define MAX_NUMBER_OF_UNKNOWN_ATTRS (128) int TURN_MAX_ALLOCATE_TIMEOUT = 60; int TURN_MAX_ALLOCATE_TIMEOUT_STUN_ONLY = 3; static inline void log_method(ts_ur_super_session* ss, const char *method, int err_code, const uint8_t *reason) { if(ss) { if(!method) method = "unknown"; if(!err_code) { if(ss->origin[0]) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: origin <%s> realm <%s> user <%s>: incoming packet %s processed, success\n", (unsigned long long)(ss->id), (const char*)(ss->origin),(const char*)(ss->realm_options.name),(const char*)(ss->username),method); } else { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: realm <%s> user <%s>: incoming packet %s processed, success\n", (unsigned long long)(ss->id), (const char*)(ss->realm_options.name),(const char*)(ss->username),method); } } else { if(!reason) reason=get_default_reason(err_code); if(ss->origin[0]) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: origin <%s> realm <%s> user <%s>: incoming packet %s processed, error %d: %s\n", (unsigned long long)(ss->id), (const char*)(ss->origin),(const char*)(ss->realm_options.name),(const char*)(ss->username), method, err_code, reason); } else { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: realm <%s> user <%s>: incoming packet %s processed, error %d: %s\n", (unsigned long long)(ss->id), (const char*)(ss->realm_options.name),(const char*)(ss->username), method, err_code, reason); } } } } /////////////////////////////////////////// static int attach_socket_to_session(turn_turnserver* server, ioa_socket_handle s, ts_ur_super_session* ss); static int check_stun_auth(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh, uint16_t method, int *message_integrity, int *postpone_reply, int can_resume); static int create_relay_connection(turn_turnserver* server, ts_ur_super_session *ss, uint32_t lifetime, int address_family, uint8_t transport, int even_port, uint64_t in_reservation_token, uint64_t *out_reservation_token, int *err_code, const uint8_t **reason, accept_cb acb); static int refresh_relay_connection(turn_turnserver* server, ts_ur_super_session *ss, uint32_t lifetime, int even_port, uint64_t in_reservation_token, uint64_t *out_reservation_token, int *err_code, int family); static int write_client_connection(turn_turnserver *server, ts_ur_super_session* ss, ioa_network_buffer_handle nbh, int ttl, int tos); static void tcp_peer_accept_connection(ioa_socket_handle s, void *arg); static int read_client_connection(turn_turnserver *server, ts_ur_super_session *ss, ioa_net_data *in_buffer, int can_resume, int count_usage); static int need_stun_authentication(turn_turnserver *server, ts_ur_super_session *ss); /////////////////// timer ////////////////////////// static void timer_timeout_handler(ioa_engine_handle e, void *arg) { UNUSED_ARG(e); if(arg) { turn_turnserver *server=(turn_turnserver*)arg; server->ctime = turn_time(); } } turn_time_t get_turn_server_time(turn_turnserver *server) { if(server) { return server->ctime; } return turn_time(); } /////////////////// quota ////////////////////// static int inc_quota(ts_ur_super_session* ss, uint8_t *username) { if(ss && !(ss->quota_used) && ss->server && ((turn_turnserver*)ss->server)->chquotacb && username) { if(((turn_turnserver*)ss->server)->ct == TURN_CREDENTIALS_LONG_TERM) { if(!(ss->origin_set)) { return -1; } } if((((turn_turnserver*)ss->server)->chquotacb)(username, ss->oauth, (uint8_t*)ss->realm_options.name)<0) { return -1; } else { STRCPY(ss->username,username); ss->quota_used = 1; } } return 0; } static void dec_quota(ts_ur_super_session* ss) { if(ss && ss->quota_used && ss->server && ((turn_turnserver*)ss->server)->raqcb) { ss->quota_used = 0; (((turn_turnserver*)ss->server)->raqcb)(ss->username, ss->oauth, (uint8_t*)ss->realm_options.name); } } static void dec_bps(ts_ur_super_session* ss) { if(ss && ss->server) { if(ss->bps) { if(((turn_turnserver*)ss->server)->allocate_bps_func) { ((turn_turnserver*)ss->server)->allocate_bps_func(ss->bps,0); } ss->bps = 0; } } } /////////////////// server lists /////////////////// void init_turn_server_addrs_list(turn_server_addrs_list_t *l) { if(l) { l->addrs = NULL; l->size = 0; turn_mutex_init(&(l->m)); } } /////////////////// RFC 5780 /////////////////////// void set_rfc5780(turn_turnserver *server, get_alt_addr_cb cb, send_message_cb smcb) { if(server) { if(!cb || !smcb) { server->rfc5780 = 0; server->alt_addr_cb = NULL; server->sm_cb = NULL; } else { server->rfc5780 = 1; server->alt_addr_cb = cb; server->sm_cb = smcb; } } } static int is_rfc5780(turn_turnserver *server) { if(!server) return 0; return ((server->rfc5780) && (server->alt_addr_cb)); } static int get_other_address(turn_turnserver *server, ts_ur_super_session *ss, ioa_addr *alt_addr) { if(is_rfc5780(server) && ss && ss->client_socket) { int ret = server->alt_addr_cb(get_local_addr_from_ioa_socket(ss->client_socket), alt_addr); return ret; } return -1; } static int send_turn_message_to(turn_turnserver *server, ioa_network_buffer_handle nbh, ioa_addr *response_origin, ioa_addr *response_destination) { if(is_rfc5780(server) && nbh && response_origin && response_destination) { return server->sm_cb(server->e, nbh, response_origin, response_destination); } return -1; } /////////////////// Peer addr check ///////////////////////////// static int good_peer_addr(turn_turnserver *server, const char* realm, ioa_addr *peer_addr) { #define CHECK_REALM(r) if((r)[0] && realm && realm[0] && strcmp((r),realm)) continue if(server && peer_addr) { if(*(server->no_multicast_peers) && ioa_addr_is_multicast(peer_addr)) return 0; if( !*(server->allow_loopback_peers) && ioa_addr_is_loopback(peer_addr)) return 0; { int i; if(server->ip_whitelist) { // White listing of addr ranges for (i = server->ip_whitelist->ranges_number - 1; i >= 0; --i) { CHECK_REALM(server->ip_whitelist->rs[i].realm); if (ioa_addr_in_range(&(server->ip_whitelist->rs[i].enc), peer_addr)) return 1; } } { ioa_lock_whitelist(server->e); const ip_range_list_t* wl = ioa_get_whitelist(server->e); if(wl) { // White listing of addr ranges for (i = wl->ranges_number - 1; i >= 0; --i) { CHECK_REALM(wl->rs[i].realm); if (ioa_addr_in_range(&(wl->rs[i].enc), peer_addr)) { ioa_unlock_whitelist(server->e); return 1; } } } ioa_unlock_whitelist(server->e); } if(server->ip_blacklist) { // Black listing of addr ranges for (i = server->ip_blacklist->ranges_number - 1; i >= 0; --i) { CHECK_REALM(server->ip_blacklist->rs[i].realm); if (ioa_addr_in_range(&(server->ip_blacklist->rs[i].enc), peer_addr)) { char saddr[129]; addr_to_string_no_port(peer_addr,(uint8_t*)saddr); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "A peer IP %s denied in the range: %s\n",saddr,server->ip_blacklist->rs[i].str); return 0; } } } { ioa_lock_blacklist(server->e); const ip_range_list_t* bl = ioa_get_blacklist(server->e); if(bl) { // Black listing of addr ranges for (i = bl->ranges_number - 1; i >= 0; --i) { CHECK_REALM(bl->rs[i].realm); if (ioa_addr_in_range(&(bl->rs[i].enc), peer_addr)) { ioa_unlock_blacklist(server->e); char saddr[129]; addr_to_string_no_port(peer_addr,(uint8_t*)saddr); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "A peer IP %s denied in the range: %s\n",saddr,bl->rs[i].str); return 0; } } } ioa_unlock_blacklist(server->e); } } } #undef CHECK_REALM return 1; } /////////////////// Allocation ////////////////////////////////// allocation* get_allocation_ss(ts_ur_super_session *ss) { return &(ss->alloc); } static inline relay_endpoint_session *get_relay_session_ss(ts_ur_super_session *ss, int family) { return get_relay_session(&(ss->alloc),family); } static inline ioa_socket_handle get_relay_socket_ss(ts_ur_super_session *ss, int family) { return get_relay_socket(&(ss->alloc),family); } /////////// Session info /////// void turn_session_info_init(struct turn_session_info* tsi) { if(tsi) { bzero(tsi,sizeof(struct turn_session_info)); } } void turn_session_info_clean(struct turn_session_info* tsi) { if(tsi) { if(tsi->extra_peers_data) { free(tsi->extra_peers_data); } turn_session_info_init(tsi); } } void turn_session_info_add_peer(struct turn_session_info* tsi, ioa_addr *peer) { if(tsi && peer) { { size_t i; for(i=0;i<tsi->main_peers_size;++i) { if(addr_eq(peer, &(tsi->main_peers_data[i].addr))) { return; } } if(tsi->main_peers_size < TURN_MAIN_PEERS_ARRAY_SIZE) { addr_cpy(&(tsi->main_peers_data[tsi->main_peers_size].addr),peer); addr_to_string(&(tsi->main_peers_data[tsi->main_peers_size].addr), (uint8_t*)tsi->main_peers_data[tsi->main_peers_size].saddr); tsi->main_peers_size += 1; return; } } if(tsi->extra_peers_data) { size_t sz; for(sz=0;sz<tsi->extra_peers_size;++sz) { if(addr_eq(peer, &(tsi->extra_peers_data[sz].addr))) { return; } } } tsi->extra_peers_data = (addr_data*)realloc(tsi->extra_peers_data,(tsi->extra_peers_size+1)*sizeof(addr_data)); addr_cpy(&(tsi->extra_peers_data[tsi->extra_peers_size].addr),peer); addr_to_string(&(tsi->extra_peers_data[tsi->extra_peers_size].addr), (uint8_t*)tsi->extra_peers_data[tsi->extra_peers_size].saddr); tsi->extra_peers_size += 1; } } struct tsi_arg { struct turn_session_info* tsi; ioa_addr *addr; }; static int turn_session_info_foreachcb(ur_map_key_type key, ur_map_value_type value, void *arg) { UNUSED_ARG(value); int port = (int)key; struct tsi_arg *ta = (struct tsi_arg *)arg; if(port && ta && ta->tsi && ta->addr) { ioa_addr a; addr_cpy(&a,ta->addr); addr_set_port(&a,port); turn_session_info_add_peer(ta->tsi,&a); } return 0; } int turn_session_info_copy_from(struct turn_session_info* tsi, ts_ur_super_session *ss) { int ret = -1; if(tsi && ss) { tsi->id = ss->id; tsi->bps = ss->bps; tsi->start_time = ss->start_time; tsi->valid = is_allocation_valid(&(ss->alloc)) && !(ss->to_be_closed) && (ss->quota_used); if(tsi->valid) { if(ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].s) { tsi->expiration_time = ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].expiration_time; if(ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].s) { if(turn_time_before(tsi->expiration_time,ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].expiration_time)) { tsi->expiration_time = ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].expiration_time; } } } else if(ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].s) { tsi->expiration_time = ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].expiration_time; } if(ss->client_socket) { tsi->client_protocol = get_ioa_socket_type(ss->client_socket); addr_cpy(&(tsi->local_addr_data.addr),get_local_addr_from_ioa_socket(ss->client_socket)); addr_to_string(&(tsi->local_addr_data.addr),(uint8_t*)tsi->local_addr_data.saddr); addr_cpy(&(tsi->remote_addr_data.addr),get_remote_addr_from_ioa_socket(ss->client_socket)); addr_to_string(&(tsi->remote_addr_data.addr),(uint8_t*)tsi->remote_addr_data.saddr); } { if(ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].s) { tsi->peer_protocol = get_ioa_socket_type(ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].s); if(ss->alloc.is_valid) { addr_cpy(&(tsi->relay_addr_data_ipv4.addr),get_local_addr_from_ioa_socket(ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].s)); addr_to_string(&(tsi->relay_addr_data_ipv4.addr),(uint8_t*)tsi->relay_addr_data_ipv4.saddr); } } if(ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].s) { tsi->peer_protocol = get_ioa_socket_type(ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].s); if(ss->alloc.is_valid) { addr_cpy(&(tsi->relay_addr_data_ipv6.addr),get_local_addr_from_ioa_socket(ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].s)); addr_to_string(&(tsi->relay_addr_data_ipv6.addr),(uint8_t*)tsi->relay_addr_data_ipv6.saddr); } } } STRCPY(tsi->username,ss->username); tsi->enforce_fingerprints = ss->enforce_fingerprints; STRCPY(tsi->tls_method, get_ioa_socket_tls_method(ss->client_socket)); STRCPY(tsi->tls_cipher, get_ioa_socket_tls_cipher(ss->client_socket)); STRCPY(tsi->realm, ss->realm_options.name); STRCPY(tsi->origin, ss->origin); if(ss->t_received_packets > ss->received_packets) tsi->received_packets = ss->t_received_packets; else tsi->received_packets = ss->received_packets; if(ss->t_sent_packets > ss->sent_packets) tsi->sent_packets = ss->t_sent_packets; else tsi->sent_packets = ss->sent_packets; if(ss->t_received_bytes > ss->received_bytes) tsi->received_bytes = ss->t_received_bytes; else tsi->received_bytes = ss->received_bytes; if(ss->t_sent_bytes > ss->sent_bytes) tsi->sent_bytes = ss->t_sent_bytes; else tsi->sent_bytes = ss->sent_bytes; if (ss->t_peer_received_packets > ss->peer_received_packets) tsi->peer_received_packets = ss->t_peer_received_packets; else tsi->peer_received_packets = ss->peer_received_packets; if (ss->t_peer_sent_packets > ss->peer_sent_packets) tsi->peer_sent_packets = ss->t_peer_sent_packets; else tsi->peer_sent_packets = ss->peer_sent_packets; if (ss->t_peer_received_bytes > ss->peer_received_bytes) tsi->peer_received_bytes = ss->t_peer_received_bytes; else tsi->peer_received_bytes = ss->peer_received_bytes; if (ss->t_peer_sent_bytes > ss->peer_sent_bytes) tsi->peer_sent_bytes = ss->t_peer_sent_bytes; else tsi->peer_sent_bytes = ss->peer_sent_bytes; { tsi->received_rate = ss->received_rate; tsi->sent_rate = ss->sent_rate; tsi->total_rate = tsi->received_rate + tsi->sent_rate; tsi->peer_received_rate = ss->peer_received_rate; tsi->peer_sent_rate = ss->peer_sent_rate; tsi->peer_total_rate = tsi->peer_received_rate + tsi->peer_sent_rate; } tsi->is_mobile = ss->is_mobile; { size_t i; for(i=0;i<TURN_PERMISSION_HASHTABLE_SIZE;++i) { turn_permission_array *parray = &(ss->alloc.addr_to_perm.table[i]); { size_t j; for(j=0;j<TURN_PERMISSION_ARRAY_SIZE;++j) { turn_permission_slot* slot = &(parray->main_slots[j]); if(slot->info.allocated) { turn_session_info_add_peer(tsi,&(slot->info.addr)); struct tsi_arg arg = { tsi, &(slot->info.addr) }; lm_map_foreach_arg(&(slot->info.chns), turn_session_info_foreachcb, &arg); } } } { turn_permission_slot **slots = parray->extra_slots; if(slots) { size_t sz = parray->extra_sz; size_t j; for(j=0;j<sz;++j) { turn_permission_slot* slot = slots[j]; if(slot && slot->info.allocated) { turn_session_info_add_peer(tsi,&(slot->info.addr)); struct tsi_arg arg = { tsi, &(slot->info.addr) }; lm_map_foreach_arg(&(slot->info.chns), turn_session_info_foreachcb, &arg); } } } } } } { tcp_connection_list *tcl = &(ss->alloc.tcs); if(tcl->elems) { size_t i; size_t sz = tcl->sz; for(i=0;i<sz;++i) { if(tcl->elems[i]) { tcp_connection *tc = tcl->elems[i]; if(tc) { turn_session_info_add_peer(tsi,&(tc->peer_addr)); } } } } } } ret = 0; } return ret; } int report_turn_session_info(turn_turnserver *server, ts_ur_super_session *ss, int force_invalid) { if(server && ss && server->send_turn_session_info) { struct turn_session_info tsi; turn_session_info_init(&tsi); if(turn_session_info_copy_from(&tsi,ss)<0) { turn_session_info_clean(&tsi); } else { if(force_invalid) tsi.valid = 0; if(server->send_turn_session_info(&tsi)<0) { turn_session_info_clean(&tsi); } else { return 0; } } } return -1; } /////////// SS ///////////////// static int mobile_id_to_string(mobile_id_t mid, char *dst, size_t dst_sz) { size_t output_length = 0; if(!dst) return -1; char *s = base64_encode((const unsigned char *)&mid, sizeof(mid), &output_length); if(!s) return -1; if(!output_length || (output_length+1 > dst_sz)) { free(s); return -1; } bcopy(s, dst, output_length); free(s); dst[output_length] = 0; return (int)output_length; } static mobile_id_t string_to_mobile_id(char* src) { mobile_id_t mid = 0; if(src) { size_t output_length = 0; unsigned char *out = base64_decode(src, strlen(src), &output_length); if(out) { if(output_length == sizeof(mid)) { mid = *((mobile_id_t*)out); } free(out); } } return mid; } static mobile_id_t get_new_mobile_id(turn_turnserver* server) { mobile_id_t newid = 0; if(server && server->mobile_connections_map) { ur_map *map = server->mobile_connections_map; uint64_t sid = server->id; sid = sid<<56; do { while (!newid) { if(TURN_RANDOM_SIZE == sizeof(mobile_id_t)) newid = (mobile_id_t)turn_random(); else { newid = (mobile_id_t)turn_random(); newid = (newid<<32) + (mobile_id_t)turn_random(); } if(!newid) { continue; } newid = newid & 0x00FFFFFFFFFFFFFFLL; if(!newid) { continue; } newid = newid | sid; } } while(ur_map_get(map, (ur_map_key_type)newid, NULL)); } return newid; } static void put_session_into_mobile_map(ts_ur_super_session *ss) { if(ss && ss->server) { turn_turnserver* server = (turn_turnserver*)(ss->server); if(*(server->mobility) && server->mobile_connections_map) { if(!(ss->mobile_id)) { ss->mobile_id = get_new_mobile_id(server); mobile_id_to_string(ss->mobile_id, ss->s_mobile_id, sizeof(ss->s_mobile_id)); } ur_map_put(server->mobile_connections_map, (ur_map_key_type)(ss->mobile_id), (ur_map_value_type)ss); } } } static void put_session_into_map(ts_ur_super_session *ss) { if(ss && ss->server) { turn_turnserver* server = (turn_turnserver*)(ss->server); if(!(ss->id)) { ss->id = (turnsession_id)((turnsession_id)server->id * TURN_SESSION_ID_FACTOR); ss->id += ++(server->session_id_counter); ss->start_time = server->ctime; } ur_map_put(server->sessions_map, (ur_map_key_type)(ss->id), (ur_map_value_type)ss); put_session_into_mobile_map(ss); } } static void delete_session_from_mobile_map(ts_ur_super_session *ss) { if(ss && ss->server && ss->mobile_id) { turn_turnserver* server = (turn_turnserver*)(ss->server); if(server->mobile_connections_map) { ur_map_del(server->mobile_connections_map, (ur_map_key_type)(ss->mobile_id), NULL); } ss->mobile_id = 0; ss->s_mobile_id[0] = 0; } } static void delete_session_from_map(ts_ur_super_session *ss) { if(ss && ss->server) { turn_turnserver* server = (turn_turnserver*)(ss->server); ur_map_del(server->sessions_map, (ur_map_key_type)(ss->id), NULL); delete_session_from_mobile_map(ss); } } static ts_ur_super_session* get_session_from_map(turn_turnserver* server, turnsession_id sid) { ts_ur_super_session *ss = NULL; if(server) { ur_map_value_type value = 0; if(ur_map_get(server->sessions_map, (ur_map_key_type)sid, &value) && value) { ss = (ts_ur_super_session*)value; } } return ss; } void turn_cancel_session(turn_turnserver *server, turnsession_id sid) { if(server) { ts_ur_super_session* ts = get_session_from_map(server, sid); if(ts) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Session %018llu to be forcefully canceled\n",(unsigned long long)sid); shutdown_client_connection(server, ts, 0, "Forceful shutdown"); } } } static ts_ur_super_session* get_session_from_mobile_map(turn_turnserver* server, mobile_id_t mid) { ts_ur_super_session *ss = NULL; if(server && *(server->mobility) && server->mobile_connections_map && mid) { ur_map_value_type value = 0; if(ur_map_get(server->mobile_connections_map, (ur_map_key_type)mid, &value) && value) { ss = (ts_ur_super_session*)value; } } return ss; } static ts_ur_super_session* create_new_ss(turn_turnserver* server) { // //printf("%s: 111.111: session size=%lu\n",__FUNCTION__,(unsigned long)sizeof(ts_ur_super_session)); // ts_ur_super_session *ss = (ts_ur_super_session*)malloc(sizeof(ts_ur_super_session)); bzero(ss,sizeof(ts_ur_super_session)); ss->server = server; get_default_realm_options(&(ss->realm_options)); put_session_into_map(ss); init_allocation(ss,&(ss->alloc), server->tcp_relay_connections); return ss; } static void delete_ur_map_ss(void *p) { if (p) { ts_ur_super_session* ss = (ts_ur_super_session*) p; delete_session_from_map(ss); IOA_CLOSE_SOCKET(ss->client_socket); clear_allocation(get_allocation_ss(ss)); IOA_EVENT_DEL(ss->to_be_allocated_timeout_ev); free(p); } } /////////// clean all ///////////////////// static int turn_server_remove_all_from_ur_map_ss(ts_ur_super_session* ss) { if (!ss) return 0; else { int ret = 0; if (ss->client_socket) { clear_ioa_socket_session_if(ss->client_socket, ss); } if (get_relay_socket_ss(ss,AF_INET)) { clear_ioa_socket_session_if(get_relay_socket_ss(ss,AF_INET), ss); } if (get_relay_socket_ss(ss,AF_INET6)) { clear_ioa_socket_session_if(get_relay_socket_ss(ss,AF_INET6), ss); } delete_ur_map_ss(ss); return ret; } } ///////////////////////////////////////////////////////////////// static void client_ss_channel_timeout_handler(ioa_engine_handle e, void* arg) { UNUSED_ARG(e); if (!arg) return; ch_info* chn = (ch_info*) arg; turn_channel_delete(chn); } static void client_ss_perm_timeout_handler(ioa_engine_handle e, void* arg) { UNUSED_ARG(e); if (!arg) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "!!! %s: empty permission to be cleaned\n",__FUNCTION__); return; } turn_permission_info* tinfo = (turn_permission_info*) arg; if(!(tinfo->allocated)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "!!! %s: unallocated permission to be cleaned\n",__FUNCTION__); return; } if(!(tinfo->lifetime_ev)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "!!! %s: strange (1) permission to be cleaned\n",__FUNCTION__); } if(!(tinfo->owner)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "!!! %s: strange (2) permission to be cleaned\n",__FUNCTION__); } turn_permission_clean(tinfo); } /////////////////////////////////////////////////////////////////// static int update_turn_permission_lifetime(ts_ur_super_session *ss, turn_permission_info *tinfo, turn_time_t time_delta) { if (ss && tinfo && tinfo->owner) { turn_turnserver *server = (turn_turnserver *) (ss->server); if (server) { if(!time_delta) time_delta = *(server->permission_lifetime); tinfo->expiration_time = server->ctime + time_delta; IOA_EVENT_DEL(tinfo->lifetime_ev); tinfo->lifetime_ev = set_ioa_timer(server->e, time_delta, 0, client_ss_perm_timeout_handler, tinfo, 0, "client_ss_channel_timeout_handler"); if(server->verbose) { tinfo->verbose = 1; tinfo->session_id = ss->id; char s[257]="\0"; addr_to_string(&(tinfo->addr),(uint8_t*)s); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: peer %s lifetime updated: %lu\n",(unsigned long long)ss->id,s,(unsigned long)time_delta); } return 0; } } return -1; } static int update_channel_lifetime(ts_ur_super_session *ss, ch_info* chn) { if (chn) { turn_permission_info* tinfo = (turn_permission_info*) (chn->owner); if (tinfo && tinfo->owner) { turn_turnserver *server = (turn_turnserver *) (ss->server); if (server) { if (update_turn_permission_lifetime(ss, tinfo, *(server->channel_lifetime)) < 0) return -1; chn->expiration_time = server->ctime + *(server->channel_lifetime); IOA_EVENT_DEL(chn->lifetime_ev); chn->lifetime_ev = set_ioa_timer(server->e, *(server->channel_lifetime), 0, client_ss_channel_timeout_handler, chn, 0, "client_ss_channel_timeout_handler"); return 0; } } } return -1; } /////////////// TURN /////////////////////////// #define SKIP_ATTRIBUTES case STUN_ATTRIBUTE_OAUTH_ACCESS_TOKEN: case STUN_ATTRIBUTE_PRIORITY: case STUN_ATTRIBUTE_FINGERPRINT: case STUN_ATTRIBUTE_MESSAGE_INTEGRITY: break; \ case STUN_ATTRIBUTE_USERNAME: case STUN_ATTRIBUTE_REALM: case STUN_ATTRIBUTE_NONCE: case STUN_ATTRIBUTE_ORIGIN: \ sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh),\ ioa_network_buffer_get_size(in_buffer->nbh), sar); \ continue static uint8_t get_transport_value(const uint8_t *value) { if((value[0] == STUN_ATTRIBUTE_TRANSPORT_UDP_VALUE)|| (value[0] == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE)) { return value[0]; } return 0; } static int handle_turn_allocate(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh) { int err_code4 = 0; int err_code6 = 0; allocation* alloc = get_allocation_ss(ss); if (is_allocation_valid(alloc)) { if (!stun_tid_equals(tid, &(alloc->tid))) { *err_code = 437; *reason = (const uint8_t *)"Wrong TID"; } else { size_t len = ioa_network_buffer_get_size(nbh); ioa_addr xor_relayed_addr1, *pxor_relayed_addr1=NULL; ioa_addr xor_relayed_addr2, *pxor_relayed_addr2=NULL; ioa_addr *relayed_addr1 = get_local_addr_from_ioa_socket(get_relay_socket_ss(ss,AF_INET)); ioa_addr *relayed_addr2 = get_local_addr_from_ioa_socket(get_relay_socket_ss(ss,AF_INET6)); if(get_relay_session_failure(alloc,AF_INET)) { addr_set_any(&xor_relayed_addr1); pxor_relayed_addr1 = &xor_relayed_addr1; } else if(relayed_addr1) { if(server->external_ip_set) { addr_cpy(&xor_relayed_addr1, &(server->external_ip)); addr_set_port(&xor_relayed_addr1,addr_get_port(relayed_addr1)); } else { addr_cpy(&xor_relayed_addr1, relayed_addr1); } pxor_relayed_addr1 = &xor_relayed_addr1; } if(get_relay_session_failure(alloc,AF_INET6)) { addr_set_any(&xor_relayed_addr2); pxor_relayed_addr2 = &xor_relayed_addr2; } else if(relayed_addr2) { if(server->external_ip_set) { addr_cpy(&xor_relayed_addr2, &(server->external_ip)); addr_set_port(&xor_relayed_addr2,addr_get_port(relayed_addr2)); } else { addr_cpy(&xor_relayed_addr2, relayed_addr2); } pxor_relayed_addr2 = &xor_relayed_addr2; } if(pxor_relayed_addr1 || pxor_relayed_addr2) { uint32_t lifetime = 0; if(pxor_relayed_addr1) { lifetime = (get_relay_session(alloc,pxor_relayed_addr1->ss.sa_family)->expiration_time - server->ctime); } else if(pxor_relayed_addr2) { lifetime = (get_relay_session(alloc,pxor_relayed_addr2->ss.sa_family)->expiration_time - server->ctime); } stun_set_allocate_response_str(ioa_network_buffer_data(nbh), &len, tid, pxor_relayed_addr1, pxor_relayed_addr2, get_remote_addr_from_ioa_socket(ss->client_socket), lifetime,*(server->max_allocate_lifetime), 0, NULL, 0, ss->s_mobile_id); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } } } else { uint8_t transport = 0; turn_time_t lifetime = 0; int even_port = -1; int dont_fragment = 0; uint64_t in_reservation_token = 0; int af4 = 0; int af6 = 0; uint8_t username[STUN_MAX_USERNAME_SIZE+1]="\0"; size_t ulen = 0; band_limit_t bps = 0; band_limit_t max_bps = 0; stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); if(attr_type == STUN_ATTRIBUTE_USERNAME) { const uint8_t* value = stun_attr_get_value(sar); if (value) { ulen = stun_attr_get_len(sar); if(ulen>=sizeof(username)) { *err_code = 400; *reason = (const uint8_t *)"User name is too long"; break; } bcopy(value,username,ulen); username[ulen]=0; if(!is_secure_string(username,1)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: wrong username: %s\n", __FUNCTION__, (char*)username); username[0]=0; *err_code = 400; break; } } } switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_NEW_BANDWIDTH: bps = stun_attr_get_bandwidth(sar); break; case STUN_ATTRIBUTE_MOBILITY_TICKET: if(!(*(server->mobility))) { *err_code = 405; *reason = (const uint8_t *)"Mobility Forbidden"; } else if (stun_attr_get_len(sar) != 0) { *err_code = 400; *reason = (const uint8_t *)"Wrong Mobility Field"; } else { ss->is_mobile = 1; } break; case STUN_ATTRIBUTE_REQUESTED_TRANSPORT: { if (stun_attr_get_len(sar) != 4) { *err_code = 400; *reason = (const uint8_t *)"Wrong Transport Field"; } else if(transport) { *err_code = 400; *reason = (const uint8_t *)"Duplicate Transport Fields"; } else { const uint8_t* value = stun_attr_get_value(sar); if (value) { transport = get_transport_value(value); if (!transport) { *err_code = 442; } if((transport == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE) && *(server->no_tcp_relay)) { *err_code = 442; *reason = (const uint8_t *)"TCP Transport is not allowed by the TURN Server configuration"; } else if((transport == STUN_ATTRIBUTE_TRANSPORT_UDP_VALUE) && *(server->no_udp_relay)) { *err_code = 442; *reason = (const uint8_t *)"UDP Transport is not allowed by the TURN Server configuration"; } else if(ss->client_socket) { SOCKET_TYPE cst = get_ioa_socket_type(ss->client_socket); if((transport == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE) && !is_stream_socket(cst)) { *err_code = 400; *reason = (const uint8_t *)"Wrong Transport Data"; } else { ss->is_tcp_relay = (transport == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE); } } } else { *err_code = 400; *reason = (const uint8_t *)"Wrong Transport Data"; } } } break; case STUN_ATTRIBUTE_DONT_FRAGMENT: dont_fragment = 1; if(!(server->dont_fragment)) unknown_attrs[(*ua_num)++] = nswap16(attr_type); break; case STUN_ATTRIBUTE_LIFETIME: { if (stun_attr_get_len(sar) != 4) { *err_code = 400; *reason = (const uint8_t *)"Wrong Lifetime Field"; } else { const uint8_t* value = stun_attr_get_value(sar); if (!value) { *err_code = 400; *reason = (const uint8_t *)"Wrong Lifetime Data"; } else { lifetime = nswap32(*((const uint32_t*)value)); } } } break; case STUN_ATTRIBUTE_EVEN_PORT: { if (in_reservation_token) { *err_code = 400; *reason = (const uint8_t *)"Even Port and Reservation Token cannot be used together"; } else { even_port = stun_attr_get_even_port(sar); if(even_port) { if (af4 && af6) { *err_code = 400; *reason = (const uint8_t *)"Even Port cannot be used with Dual Allocation"; } } } } break; case STUN_ATTRIBUTE_RESERVATION_TOKEN: { int len = stun_attr_get_len(sar); if (len != 8) { *err_code = 400; *reason = (const uint8_t *)"Wrong Format of Reservation Token"; } else if(af4 || af6) { *err_code = 400; *reason = (const uint8_t *)"Address family attribute can not be used with reservation token request"; } else { if (even_port >= 0) { *err_code = 400; *reason = (const uint8_t *)"Reservation Token cannot be used in this request with even port"; } else if (in_reservation_token) { *err_code = 400; *reason = (const uint8_t *)"Reservation Token cannot be used in this request"; } else { in_reservation_token = stun_attr_get_reservation_token_value(sar); } } } break; case STUN_ATTRIBUTE_ADDITIONAL_ADDRESS_FAMILY: if(even_port>0) { *err_code = 400; *reason = (const uint8_t *)"Even Port cannot be used with Dual Allocation"; break; } /* Falls through. */ case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY: { if(in_reservation_token) { *err_code = 400; *reason = (const uint8_t *)"Address family attribute can not be used with reservation token request"; } else if(af4 || af6) { *err_code = 400; *reason = (const uint8_t *)"Extra address family attribute can not be used in the request"; } else { int af_req = stun_get_requested_address_family(sar); switch (af_req) { case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4: if(attr_type == STUN_ATTRIBUTE_ADDITIONAL_ADDRESS_FAMILY) { *err_code = 400; *reason = (const uint8_t *)"Invalid value of the additional address family attribute"; } else { af4 = af_req; } break; case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6: if(attr_type == STUN_ATTRIBUTE_ADDITIONAL_ADDRESS_FAMILY) { af4 = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4; } af6 = af_req; break; default: *err_code = 440; } } } break; default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if (!transport) { *err_code = 400; if(!(*reason)) *reason = (const uint8_t *)"Transport field missed or wrong"; } else if (*ua_num > 0) { *err_code = 420; } else if (*err_code) { ; } else if((transport == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE) && (dont_fragment || in_reservation_token || (even_port!=-1))) { *err_code = 400; if(!(*reason)) *reason = (const uint8_t *)"Request parameters are incompatible with TCP transport"; } else { if(*(server->mobility)) { if(!(ss->is_mobile)) { delete_session_from_mobile_map(ss); } } lifetime = stun_adjust_allocate_lifetime(lifetime, *(server->max_allocate_lifetime), ss->max_session_time_auth); uint64_t out_reservation_token = 0; if(inc_quota(ss, username)<0) { *err_code = 486; } else { if(server->allocate_bps_func) { max_bps = ss->realm_options.perf_options.max_bps; if(max_bps && (!bps || (bps && (bps>max_bps)))) { bps = max_bps; } if(bps && (ss->bps == 0)) { ss->bps = server->allocate_bps_func(bps,1); if(!(ss->bps)) { *err_code = 486; *reason = (const uint8_t *)"Allocation Bandwidth Quota Reached"; } } } if(af4) af4 = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4; if(af6) af6 = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6; if(af4 && af6) { if(server->external_ip_set) { *err_code = 440; *reason = (const uint8_t *)"Dual allocation cannot be supported in the current server configuration"; } if(even_port > 0) { *err_code = 440; *reason = (const uint8_t *)"Dual allocation cannot be supported with even-port functionality"; } } if(!(*err_code)) { if(!af4 && !af6) { int a_family = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_DEFAULT; if (server->keep_address_family) { switch(get_ioa_socket_address_family(ss->client_socket)) { case AF_INET6 : a_family = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6; break; case AF_INET : a_family = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4; break; } } int res = create_relay_connection(server, ss, lifetime, a_family, transport, even_port, in_reservation_token, &out_reservation_token, err_code, reason, tcp_peer_accept_connection); if(res<0) { set_relay_session_failure(alloc,AF_INET); if(!(*err_code)) { *err_code = 437; } } } else if(!af4 && af6) { int af6res = create_relay_connection(server, ss, lifetime, af6, transport, even_port, in_reservation_token, &out_reservation_token, err_code, reason, tcp_peer_accept_connection); if(af6res<0) { set_relay_session_failure(alloc,AF_INET6); if(!(*err_code)) { *err_code = 437; } } } else if(af4 && !af6) { int af4res = create_relay_connection(server, ss, lifetime, af4, transport, even_port, in_reservation_token, &out_reservation_token, err_code, reason, tcp_peer_accept_connection); if(af4res<0) { set_relay_session_failure(alloc,AF_INET); if(!(*err_code)) { *err_code = 437; } } } else { const uint8_t *reason4 = NULL; const uint8_t *reason6 = NULL; { int af4res = create_relay_connection(server, ss, lifetime, af4, transport, even_port, in_reservation_token, &out_reservation_token, &err_code4, &reason4, tcp_peer_accept_connection); if(af4res<0) { set_relay_session_failure(alloc,AF_INET); if(!err_code4) { err_code4 = 440; } } } { int af6res = create_relay_connection(server, ss, lifetime, af6, transport, even_port, in_reservation_token, &out_reservation_token, &err_code6, &reason6, tcp_peer_accept_connection); if(af6res<0) { set_relay_session_failure(alloc,AF_INET6); if(!err_code6) { err_code6 = 440; } } } if(err_code4 && err_code6) { if(reason4) { *err_code = err_code4; *reason = reason4; } else if(reason6) { *err_code = err_code6; *reason = reason6; } else { *err_code = err_code4; } } } } if (*err_code) { if(!(*reason)) { *reason = (const uint8_t *)"Cannot create relay endpoint(s)"; } } else { set_allocation_valid(alloc,1); stun_tid_cpy(&(alloc->tid), tid); size_t len = ioa_network_buffer_get_size(nbh); ioa_addr xor_relayed_addr1, *pxor_relayed_addr1=NULL; ioa_addr xor_relayed_addr2, *pxor_relayed_addr2=NULL; ioa_addr *relayed_addr1 = get_local_addr_from_ioa_socket(get_relay_socket_ss(ss,AF_INET)); ioa_addr *relayed_addr2 = get_local_addr_from_ioa_socket(get_relay_socket_ss(ss,AF_INET6)); if(get_relay_session_failure(alloc,AF_INET)) { addr_set_any(&xor_relayed_addr1); pxor_relayed_addr1 = &xor_relayed_addr1; } else if(relayed_addr1) { if(server->external_ip_set) { addr_cpy(&xor_relayed_addr1, &(server->external_ip)); addr_set_port(&xor_relayed_addr1,addr_get_port(relayed_addr1)); } else { addr_cpy(&xor_relayed_addr1, relayed_addr1); } pxor_relayed_addr1 = &xor_relayed_addr1; } if(get_relay_session_failure(alloc,AF_INET6)) { addr_set_any(&xor_relayed_addr2); pxor_relayed_addr2 = &xor_relayed_addr2; } else if(relayed_addr2) { if(server->external_ip_set) { addr_cpy(&xor_relayed_addr2, &(server->external_ip)); addr_set_port(&xor_relayed_addr2,addr_get_port(relayed_addr2)); } else { addr_cpy(&xor_relayed_addr2, relayed_addr2); } pxor_relayed_addr2 = &xor_relayed_addr2; } if(pxor_relayed_addr1 || pxor_relayed_addr2) { stun_set_allocate_response_str(ioa_network_buffer_data(nbh), &len, tid, pxor_relayed_addr1, pxor_relayed_addr2, get_remote_addr_from_ioa_socket(ss->client_socket), lifetime, *(server->max_allocate_lifetime),0,NULL, out_reservation_token, ss->s_mobile_id); if(ss->bps) { stun_attr_add_bandwidth_str(ioa_network_buffer_data(nbh), &len, ss->bps); } ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; turn_report_allocation_set(&(ss->alloc), lifetime, 0); } } } } } if (!(*resp_constructed)) { if (!(*err_code)) { *err_code = 437; } size_t len = ioa_network_buffer_get_size(nbh); stun_set_allocate_response_str(ioa_network_buffer_data(nbh), &len, tid, NULL, NULL, NULL, 0, *(server->max_allocate_lifetime), *err_code, *reason, 0, ss->s_mobile_id); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } if(*resp_constructed && !(*err_code)) { if(err_code4) { size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_address_error_code(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4, err_code4); ioa_network_buffer_set_size(nbh,len); } if(err_code6) { size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_address_error_code(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6, err_code6); ioa_network_buffer_set_size(nbh,len); } } return 0; } static void copy_auth_parameters(ts_ur_super_session *orig_ss, ts_ur_super_session *ss) { if(orig_ss && ss) { dec_quota(ss); bcopy(orig_ss->nonce,ss->nonce,sizeof(ss->nonce)); ss->nonce_expiration_time = orig_ss->nonce_expiration_time; bcopy(&(orig_ss->realm_options),&(ss->realm_options),sizeof(ss->realm_options)); bcopy(orig_ss->username,ss->username,sizeof(ss->username)); ss->hmackey_set = orig_ss->hmackey_set; bcopy(orig_ss->hmackey,ss->hmackey,sizeof(ss->hmackey)); ss->oauth = orig_ss->oauth; bcopy(orig_ss->origin,ss->origin,sizeof(ss->origin)); ss->origin_set = orig_ss->origin_set; bcopy(orig_ss->pwd,ss->pwd,sizeof(ss->pwd)); ss->max_session_time_auth = orig_ss->max_session_time_auth; inc_quota(ss,ss->username); } } static int handle_turn_refresh(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh, int message_integrity, int *no_response, int can_resume) { allocation* a = get_allocation_ss(ss); int af4c = 0; int af6c = 0; int af4 = 0; int af6 = 0; { int i; for(i = 0;i<ALLOC_PROTOCOLS_NUMBER; ++i) { if(a->relay_sessions[i].s && !ioa_socket_tobeclosed(a->relay_sessions[i].s)) { int family = get_ioa_socket_address_family(a->relay_sessions[i].s); if(AF_INET == family) { af4c = 1; } else if(AF_INET6 == family) { af6c = 1; } } } } if (!is_allocation_valid(a) && !(*(server->mobility))) { *err_code = 437; *reason = (const uint8_t *)"Invalid allocation"; } else { turn_time_t lifetime = 0; int to_delete = 0; mobile_id_t mid = 0; char smid[sizeof(ss->s_mobile_id)] = "\0"; stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_MOBILITY_TICKET: { if(!(*(server->mobility))) { *err_code = 405; *reason = (const uint8_t *)"Mobility forbidden"; } else { int smid_len = stun_attr_get_len(sar); if(smid_len>0 && (((size_t)smid_len)<sizeof(smid))) { const uint8_t* smid_val = stun_attr_get_value(sar); if(smid_val) { bcopy(smid_val, smid, (size_t)smid_len); mid = string_to_mobile_id(smid); if(is_allocation_valid(a) && (mid != ss->old_mobile_id)) { *err_code = 400; *reason = (const uint8_t *)"Mobility ticket cannot be used for a stable, already established allocation"; } } } else { *err_code = 400; *reason = (const uint8_t *)"Mobility ticket has wrong length"; } } } break; case STUN_ATTRIBUTE_LIFETIME: { if (stun_attr_get_len(sar) != 4) { *err_code = 400; *reason = (const uint8_t *)"Wrong Lifetime field format"; } else { const uint8_t* value = stun_attr_get_value(sar); if (!value) { *err_code = 400; *reason = (const uint8_t *)"Wrong lifetime field data"; } else { lifetime = nswap32(*((const uint32_t*)value)); if (!lifetime) to_delete = 1; } } } break; case STUN_ATTRIBUTE_ADDITIONAL_ADDRESS_FAMILY: /* deprecated, for backward compatibility with older versions of TURN-bis */ case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY: { int af_req = stun_get_requested_address_family(sar); { int is_err = 0; switch (af_req) { case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4: if(!af4c) { is_err = 1; } else { af4 = 1; } break; case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6: if(!af6c) { is_err = 1; } else { af6 = 1; } break; default: is_err = 1; } if(is_err) { *err_code = 443; *reason = (const uint8_t *)"Peer Address Family Mismatch (1)"; } } } break; default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if (*ua_num > 0) { *err_code = 420; } else if (*err_code) { ; } else if(!is_allocation_valid(a)) { if(mid && smid[0]) { turnserver_id tsid = ((0xFF00000000000000LL) & mid)>>56; if(tsid != server->id) { if(server->send_socket_to_relay) { ioa_socket_handle new_s = detach_ioa_socket(ss->client_socket); if(new_s) { if(server->send_socket_to_relay(tsid, mid, tid, new_s, message_integrity, RMT_MOBILE_SOCKET, in_buffer, can_resume)<0) { *err_code = 400; *reason = (const uint8_t *)"Wrong mobile ticket"; } else { *no_response = 1; } } else { *err_code = 500; *reason = (const uint8_t *)"Cannot create new socket"; return -1; } } else { *err_code = 500; *reason = (const uint8_t *)"Server send socket procedure is not set"; } ss->to_be_closed = 1; } else { ts_ur_super_session *orig_ss = get_session_from_mobile_map(server, mid); if(!orig_ss || orig_ss->to_be_closed || ioa_socket_tobeclosed(orig_ss->client_socket)) { *err_code = 404; *reason = (const uint8_t *)"Allocation not found"; } else if(orig_ss == ss) { *err_code = 437; *reason = (const uint8_t *)"Invalid allocation"; } else if(!(orig_ss->is_mobile)) { *err_code = 500; *reason = (const uint8_t *)"Software error: invalid mobile allocation"; } else if(orig_ss->client_socket == ss->client_socket) { *err_code = 500; *reason = (const uint8_t *)"Software error: invalid mobile client socket (orig)"; } else if(!(ss->client_socket)) { *err_code = 500; *reason = (const uint8_t *)"Software error: invalid mobile client socket (new)"; } else { get_realm_options_by_name(orig_ss->realm_options.name, &(ss->realm_options)); //Check security: int postpone_reply = 0; if(!(ss->hmackey_set)) { copy_auth_parameters(orig_ss,ss); } if(check_stun_auth(server, ss, tid, resp_constructed, err_code, reason, in_buffer, nbh, STUN_METHOD_REFRESH, &message_integrity, &postpone_reply, can_resume)<0) { if(!(*err_code)) { *err_code = 401; } } if(postpone_reply) { *no_response = 1; } else if(!(*err_code)) { //Session transfer: if (to_delete) lifetime = 0; else { lifetime = stun_adjust_allocate_lifetime(lifetime, *(server->max_allocate_lifetime), ss->max_session_time_auth); } if (af4c && refresh_relay_connection(server, orig_ss, lifetime, 0, 0, 0, err_code, AF_INET) < 0) { if (!(*err_code)) { *err_code = 437; *reason = (const uint8_t *)"Cannot refresh relay connection (internal error)"; } } else if (af6c && refresh_relay_connection(server, orig_ss, lifetime, 0, 0, 0, err_code, AF_INET6) < 0) { if (!(*err_code)) { *err_code = 437; *reason = (const uint8_t *)"Cannot refresh relay connection (internal error)"; } } else { //Transfer socket: ioa_socket_handle s = detach_ioa_socket(ss->client_socket); ss->to_be_closed = 1; if(!s) { *err_code = 500; } else { if(attach_socket_to_session(server, s, orig_ss) < 0) { if(orig_ss->client_socket != s) { IOA_CLOSE_SOCKET(s); } *err_code = 500; } else { if(ss->hmackey_set) { copy_auth_parameters(ss,orig_ss); } delete_session_from_mobile_map(ss); delete_session_from_mobile_map(orig_ss); put_session_into_mobile_map(orig_ss); //Use new buffer and redefine ss: nbh = ioa_network_buffer_allocate(server->e); dec_quota(ss); ss = orig_ss; inc_quota(ss,ss->username); ss->old_mobile_id = mid; size_t len = ioa_network_buffer_get_size(nbh); turn_report_allocation_set(&(ss->alloc), lifetime, 1); stun_init_success_response_str(STUN_METHOD_REFRESH, ioa_network_buffer_data(nbh), &len, tid); uint32_t lt = nswap32(lifetime); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_LIFETIME, (const uint8_t*) &lt, 4); ioa_network_buffer_set_size(nbh,len); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_MOBILITY_TICKET, (uint8_t*)ss->s_mobile_id,strlen(ss->s_mobile_id)); ioa_network_buffer_set_size(nbh,len); { const uint8_t *field = (const uint8_t *) get_version(server); size_t fsz = strlen(get_version(server)); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_SOFTWARE, field, fsz); ioa_network_buffer_set_size(nbh, len); } if(message_integrity) { stun_attr_add_integrity_str(server->ct,ioa_network_buffer_data(nbh),&len,ss->hmackey,ss->pwd,SHATYPE_DEFAULT); ioa_network_buffer_set_size(nbh,len); } if ((server->fingerprint) || ss->enforce_fingerprints) { if (stun_attr_add_fingerprint_str(ioa_network_buffer_data(nbh), &len) < 0) { *err_code = 500; ioa_network_buffer_delete(server->e, nbh); return -1; } ioa_network_buffer_set_size(nbh, len); } *no_response = 1; return write_client_connection(server, ss, nbh, TTL_IGNORE, TOS_IGNORE); } } } } report_turn_session_info(server,orig_ss,0); } } } else { *err_code = 437; *reason = (const uint8_t *)"Invalid allocation"; } } else { if (to_delete) lifetime = 0; else { lifetime = stun_adjust_allocate_lifetime(lifetime, *(server->max_allocate_lifetime), ss->max_session_time_auth); } if(!af4 && !af6) { af4 = af4c; af6 = af6c; } if (af4 && refresh_relay_connection(server, ss, lifetime, 0, 0, 0, err_code, AF_INET) < 0) { if (!(*err_code)) { *err_code = 437; *reason = (const uint8_t *)"Cannot refresh relay connection (internal error)"; } } else if (af6 && refresh_relay_connection(server, ss, lifetime, 0, 0, 0, err_code, AF_INET6) < 0) { if (!(*err_code)) { *err_code = 437; *reason = (const uint8_t *)"Cannot refresh relay connection (internal error)"; } } else { turn_report_allocation_set(&(ss->alloc), lifetime, 1); size_t len = ioa_network_buffer_get_size(nbh); stun_init_success_response_str(STUN_METHOD_REFRESH, ioa_network_buffer_data(nbh), &len, tid); if(ss->s_mobile_id[0]) { stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_MOBILITY_TICKET, (uint8_t*)ss->s_mobile_id,strlen(ss->s_mobile_id)); ioa_network_buffer_set_size(nbh,len); } uint32_t lt = nswap32(lifetime); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_LIFETIME, (const uint8_t*) &lt, 4); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } } } if(!no_response) { if (!(*resp_constructed)) { if (!(*err_code)) { *err_code = 437; } size_t len = ioa_network_buffer_get_size(nbh); stun_init_error_response_str(STUN_METHOD_REFRESH, ioa_network_buffer_data(nbh), &len, *err_code, *reason, tid); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } } return 0; } /* RFC 6062 ==>> */ static void tcp_deliver_delayed_buffer(unsent_buffer *ub, ioa_socket_handle s, ts_ur_super_session *ss) { if(ub && s && ub->bufs && ub->sz && ss) { size_t i = 0; do { ioa_network_buffer_handle nbh = top_unsent_buffer(ub); if(!nbh) break; uint32_t bytes = (uint32_t)ioa_network_buffer_get_size(nbh); int ret = send_data_from_ioa_socket_nbh(s, NULL, nbh, TTL_IGNORE, TOS_IGNORE, NULL); if (ret < 0) { set_ioa_socket_tobeclosed(s); } else { ++(ss->sent_packets); ss->sent_bytes += bytes; turn_report_session_usage(ss, 0); } pop_unsent_buffer(ub); } while(!ioa_socket_tobeclosed(s) && ((i++)<MAX_UNSENT_BUFFER_SIZE)); } } static void tcp_peer_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *in_buffer, void *arg, int can_resume) { if (!(event_type & IOA_EV_READ) || !arg) return; UNUSED_ARG(s); UNUSED_ARG(can_resume); tcp_connection *tc = (tcp_connection*)arg; ts_ur_super_session *ss=NULL; allocation *a=(allocation*)tc->owner; if(a) { ss=(ts_ur_super_session*)a->owner; } if((tc->state != TC_STATE_READY) || !(tc->client_s)) { add_unsent_buffer(&(tc->ub_to_client), in_buffer->nbh); in_buffer->nbh = NULL; return; } ioa_network_buffer_handle nbh = in_buffer->nbh; in_buffer->nbh = NULL; uint32_t bytes = (uint32_t)ioa_network_buffer_get_size(nbh); if (ss) { ++(ss->peer_received_packets); ss->peer_received_bytes += bytes; } int ret = send_data_from_ioa_socket_nbh(tc->client_s, NULL, nbh, TTL_IGNORE, TOS_IGNORE, NULL); if (ret < 0) { set_ioa_socket_tobeclosed(s); } else if(ss) { ++(ss->sent_packets); ss->sent_bytes += bytes; } if (ss) { turn_report_session_usage(ss, 0); } } static void tcp_client_input_handler_rfc6062data(ioa_socket_handle s, int event_type, ioa_net_data *in_buffer, void *arg, int can_resume) { if (!(event_type & IOA_EV_READ) || !arg) return; UNUSED_ARG(s); UNUSED_ARG(can_resume); tcp_connection *tc = (tcp_connection*)arg; ts_ur_super_session *ss=NULL; allocation *a=(allocation*)tc->owner; if(a) { ss=(ts_ur_super_session*)a->owner; } if(tc->state != TC_STATE_READY) return; if(!(tc->peer_s)) return; ioa_network_buffer_handle nbh = in_buffer->nbh; in_buffer->nbh = NULL; uint32_t bytes = (uint32_t)ioa_network_buffer_get_size(nbh); if(ss) { ++(ss->received_packets); ss->received_bytes += bytes; } int skip = 0; int ret = send_data_from_ioa_socket_nbh(tc->peer_s, NULL, nbh, TTL_IGNORE, TOS_IGNORE, &skip); if (ret < 0) { set_ioa_socket_tobeclosed(s); } if (!skip && ss) { ++(ss->peer_sent_packets); ss->peer_sent_bytes += bytes; } if(ss) turn_report_session_usage(ss, 0); } static void tcp_conn_bind_timeout_handler(ioa_engine_handle e, void *arg) { UNUSED_ARG(e); if(arg) { tcp_connection *tc = (tcp_connection *)arg; delete_tcp_connection(tc); } } static void tcp_peer_connection_completed_callback(int success, void *arg) { if(arg) { tcp_connection *tc = (tcp_connection *)arg; allocation *a = (allocation*)(tc->owner); ts_ur_super_session *ss = (ts_ur_super_session*)(a->owner); turn_turnserver *server=(turn_turnserver*)(ss->server); int err_code = 0; IOA_EVENT_DEL(tc->peer_conn_timeout); ioa_network_buffer_handle nbh = ioa_network_buffer_allocate(server->e); size_t len = ioa_network_buffer_get_size(nbh); if(success) { if(register_callback_on_ioa_socket(server->e, tc->peer_s, IOA_EV_READ, tcp_peer_input_handler, tc, 1)<0) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: cannot set TCP peer data input callback\n", __FUNCTION__); success=0; err_code = 500; } } if(success) { tc->state = TC_STATE_PEER_CONNECTED; stun_init_success_response_str(STUN_METHOD_CONNECT, ioa_network_buffer_data(nbh), &len, &(tc->tid)); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_CONNECTION_ID, (const uint8_t*)&(tc->id), 4); IOA_EVENT_DEL(tc->conn_bind_timeout); tc->conn_bind_timeout = set_ioa_timer(server->e, TCP_CONN_BIND_TIMEOUT, 0, tcp_conn_bind_timeout_handler, tc, 0, "tcp_conn_bind_timeout_handler"); } else { tc->state = TC_STATE_FAILED; if(!err_code) { err_code = 447; } { char ls[257]="\0"; char rs[257]="\0"; ioa_addr *laddr = get_local_addr_from_ioa_socket(ss->client_socket); if(laddr) addr_to_string(laddr,(uint8_t*)ls); addr_to_string(&(tc->peer_addr),(uint8_t*)rs); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: failure to connect from %s to %s\n", __FUNCTION__, ls,rs); } stun_init_error_response_str(STUN_METHOD_CONNECT, ioa_network_buffer_data(nbh), &len, err_code, NULL, &(tc->tid)); } ioa_network_buffer_set_size(nbh,len); if(need_stun_authentication(server, ss)) { stun_attr_add_integrity_str(server->ct,ioa_network_buffer_data(nbh),&len,ss->hmackey,ss->pwd,SHATYPE_DEFAULT); ioa_network_buffer_set_size(nbh,len); } write_client_connection(server, ss, nbh, TTL_IGNORE, TOS_IGNORE); if(!success) { delete_tcp_connection(tc); } /* test */ else if(0) { int i = 0; for(i=0;i<22;i++) { ioa_network_buffer_handle nbh_test = ioa_network_buffer_allocate(server->e); size_t len_test = ioa_network_buffer_get_size(nbh_test); uint8_t *data = ioa_network_buffer_data(nbh_test); const char* data_test="111.111.111.111.111"; len_test = strlen(data_test); bcopy(data_test,data,len_test); ioa_network_buffer_set_size(nbh_test,len_test); send_data_from_ioa_socket_nbh(tc->peer_s, NULL, nbh_test, TTL_IGNORE, TOS_IGNORE, NULL); } } } } static void tcp_peer_conn_timeout_handler(ioa_engine_handle e, void *arg) { UNUSED_ARG(e); tcp_peer_connection_completed_callback(0,arg); } static int tcp_start_connection_to_peer(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, allocation *a, ioa_addr *peer_addr, int *err_code, const uint8_t **reason) { FUNCSTART; if(!ss) { *err_code = 500; *reason = (const uint8_t *)"Server error: empty session"; FUNCEND; return -1; } if(!peer_addr) { *err_code = 500; *reason = (const uint8_t *)"Server error: empty peer addr"; FUNCEND; return -1; } if(!get_relay_socket(a,peer_addr->ss.sa_family)) { *err_code = 500; *reason = (const uint8_t *)"Server error: no relay connection created"; FUNCEND; return -1; } tcp_connection *tc = get_tcp_connection_by_peer(a, peer_addr); if(tc) { *err_code = 446; FUNCEND; return -1; } tc = create_tcp_connection(server->id, a, tid, peer_addr, err_code); if(!tc) { if(!(*err_code)) { *err_code = 500; *reason = (const uint8_t *)"Server error: TCP connection object creation failed"; } FUNCEND; return -1; } else if(*err_code) { delete_tcp_connection(tc); FUNCEND; return -1; } IOA_EVENT_DEL(tc->peer_conn_timeout); tc->peer_conn_timeout = set_ioa_timer(server->e, TCP_PEER_CONN_TIMEOUT, 0, tcp_peer_conn_timeout_handler, tc, 0, "tcp_peer_conn_timeout_handler"); ioa_socket_handle tcs = ioa_create_connecting_tcp_relay_socket(get_relay_socket(a,peer_addr->ss.sa_family), peer_addr, tcp_peer_connection_completed_callback, tc); if(!tcs) { delete_tcp_connection(tc); *err_code = 500; *reason = (const uint8_t *)"Server error: TCP relay socket for connection cannot be created"; FUNCEND; return -1; } tc->state = TC_STATE_CLIENT_TO_PEER_CONNECTING; if(tc->peer_s != tcs) { IOA_CLOSE_SOCKET(tc->peer_s); tc->peer_s = tcs; } set_ioa_socket_sub_session(tc->peer_s,tc); FUNCEND; return 0; } static void tcp_peer_accept_connection(ioa_socket_handle s, void *arg) { if(s) { if(!arg) { close_ioa_socket(s); return; } ts_ur_super_session *ss = (ts_ur_super_session*)arg; turn_turnserver *server=(turn_turnserver*)(ss->server); FUNCSTART; allocation *a = &(ss->alloc); ioa_addr *peer_addr = get_remote_addr_from_ioa_socket(s); if(!peer_addr) { close_ioa_socket(s); FUNCEND; return; } tcp_connection *tc = get_tcp_connection_by_peer(a, peer_addr); if(tc) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: peer data socket with this address already exist\n", __FUNCTION__); if(tc->peer_s != s) close_ioa_socket(s); FUNCEND; return; } if(!good_peer_addr(server, ss->realm_options.name, peer_addr)) { uint8_t saddr[256]; addr_to_string(peer_addr, saddr); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: an attempt to connect from a peer with forbidden address: %s\n", __FUNCTION__,saddr); close_ioa_socket(s); FUNCEND; return; } if(!can_accept_tcp_connection_from_peer(a,peer_addr,server->server_relay)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: peer has no permission to connect\n", __FUNCTION__); close_ioa_socket(s); FUNCEND; return; } stun_tid tid; bzero(&tid,sizeof(stun_tid)); int err_code=0; tc = create_tcp_connection(server->id, a, &tid, peer_addr, &err_code); if(!tc) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: cannot create TCP connection\n", __FUNCTION__); close_ioa_socket(s); FUNCEND; return; } tc->state = TC_STATE_PEER_CONNECTED; tc->peer_s = s; set_ioa_socket_session(s,ss); set_ioa_socket_sub_session(s,tc); if(register_callback_on_ioa_socket(server->e, s, IOA_EV_READ, tcp_peer_input_handler, tc, 1)<0) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: cannot set TCP peer data input callback\n", __FUNCTION__); IOA_CLOSE_SOCKET(tc->peer_s); tc->state = TC_STATE_UNKNOWN; FUNCEND; return; } IOA_EVENT_DEL(tc->conn_bind_timeout); tc->conn_bind_timeout = set_ioa_timer(server->e, TCP_CONN_BIND_TIMEOUT, 0, tcp_conn_bind_timeout_handler, tc, 0, "tcp_conn_bind_timeout_handler"); ioa_network_buffer_handle nbh = ioa_network_buffer_allocate(server->e); size_t len = ioa_network_buffer_get_size(nbh); stun_init_indication_str(STUN_METHOD_CONNECTION_ATTEMPT, ioa_network_buffer_data(nbh), &len); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_CONNECTION_ID, (const uint8_t*)&(tc->id), 4); stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, peer_addr); ioa_network_buffer_set_size(nbh,len); { const uint8_t *field = (const uint8_t *) get_version(server); size_t fsz = strlen(get_version(server)); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_SOFTWARE, field, fsz); ioa_network_buffer_set_size(nbh, len); } if ((server->fingerprint) || ss->enforce_fingerprints) { size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_fingerprint_str(ioa_network_buffer_data(nbh), &len); ioa_network_buffer_set_size(nbh, len); } write_client_connection(server, ss, nbh, TTL_IGNORE, TOS_IGNORE); FUNCEND; } } static int handle_turn_connect(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer) { FUNCSTART; ioa_addr peer_addr; int peer_found = 0; addr_set_any(&peer_addr); allocation* a = get_allocation_ss(ss); if(!(ss->is_tcp_relay)) { *err_code = 403; *reason = (const uint8_t *)"Connect cannot be used with UDP relay"; } else if (!is_allocation_valid(a)) { *err_code = 437; } else { stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_XOR_PEER_ADDRESS: { if(stun_attr_get_addr_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar, &peer_addr, NULL) == -1) { *err_code = 400; *reason = (const uint8_t *)"Bad Peer Address"; } else { if(!get_relay_socket(a,peer_addr.ss.sa_family)) { *err_code = 443; *reason = (const uint8_t *)"Peer Address Family Mismatch (2)"; } peer_found = 1; } break; } default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if (*ua_num > 0) { *err_code = 420; } else if (*err_code) { ; } else if (!peer_found) { *err_code = 400; *reason = (const uint8_t *)"Where is Peer Address ?"; } else { if(!good_peer_addr(server,ss->realm_options.name,&peer_addr)) { *err_code = 403; *reason = (const uint8_t *) "Forbidden IP"; } else { tcp_start_connection_to_peer(server, ss, tid, a, &peer_addr, err_code, reason); } } } FUNCEND; return 0; } static int handle_turn_connection_bind(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh, int message_integrity, int can_resume) { allocation* a = get_allocation_ss(ss); uint16_t method = STUN_METHOD_CONNECTION_BIND; if(ss->to_be_closed) { *err_code = 400; } else if (is_allocation_valid(a)) { *err_code = 400; *reason = (const uint8_t *)"Bad request: CONNECTION_BIND cannot be issued after allocation"; } else if(!is_stream_socket(get_ioa_socket_type(ss->client_socket))) { *err_code = 400; *reason = (const uint8_t *)"Bad request: CONNECTION_BIND only possible with TCP/TLS"; } else { tcp_connection_id id = 0; stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_CONNECTION_ID: { if (stun_attr_get_len(sar) != 4) { *err_code = 400; *reason = (const uint8_t *)"Wrong Connection ID field format"; } else { const uint8_t* value = stun_attr_get_value(sar); if (!value) { *err_code = 400; *reason = (const uint8_t *)"Wrong Connection ID field data"; } else { id = *((const uint32_t*)value); //AS-IS encoding, no conversion to/from network byte order } } } break; default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if (*ua_num > 0) { *err_code = 420; } else if (*err_code) { ; } else { if(server->send_socket_to_relay) { turnserver_id sid = (id & 0xFF000000)>>24; ioa_socket_handle s = ss->client_socket; if(s && !ioa_socket_tobeclosed(s)) { ioa_socket_handle new_s = detach_ioa_socket(s); if(new_s) { if(server->send_socket_to_relay(sid, id, tid, new_s, message_integrity, RMT_CB_SOCKET, in_buffer, can_resume)<0) { *err_code = 400; *reason = (const uint8_t *)"Wrong connection id"; } } else { *err_code = 500; } } else { *err_code = 500; } } else { *err_code = 500; } ss->to_be_closed = 1; } } if (!(*resp_constructed) && ss->client_socket && !ioa_socket_tobeclosed(ss->client_socket)) { if (!(*err_code)) { *err_code = 437; } size_t len = ioa_network_buffer_get_size(nbh); stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, *err_code, *reason, tid); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } return 0; } int turnserver_accept_tcp_client_data_connection(turn_turnserver *server, tcp_connection_id tcid, stun_tid *tid, ioa_socket_handle s, int message_integrity, ioa_net_data *in_buffer, int can_resume) { if(!server) return -1; FUNCSTART; tcp_connection *tc = NULL; ts_ur_super_session *ss = NULL; int err_code = 0; const uint8_t *reason = NULL; ioa_socket_handle s_to_delete = s; if(tcid && tid && s) { tc = get_tcp_connection_by_id(server->tcp_relay_connections, tcid); ioa_network_buffer_handle nbh = ioa_network_buffer_allocate(server->e); int resp_constructed = 0; if(!tc || (tc->state == TC_STATE_READY) || (tc->client_s)) { err_code = 400; } else { allocation *a = (allocation*)(tc->owner); if(!a || !(a->owner)) { err_code = 500; } else { ss = (ts_ur_super_session*)(a->owner); if(ss->to_be_closed || ioa_socket_tobeclosed(ss->client_socket)) { err_code = 404; } else { //Check security: int postpone_reply = 0; check_stun_auth(server, ss, tid, &resp_constructed, &err_code, &reason, in_buffer, nbh, STUN_METHOD_CONNECTION_BIND, &message_integrity, &postpone_reply, can_resume); if(postpone_reply) { ioa_network_buffer_delete(server->e, nbh); return 0; } else if(!err_code) { tc->state = TC_STATE_READY; tc->client_s = s; s_to_delete = NULL; set_ioa_socket_session(s,ss); set_ioa_socket_sub_session(s,tc); set_ioa_socket_app_type(s,TCP_CLIENT_DATA_SOCKET); if(register_callback_on_ioa_socket(server->e, s, IOA_EV_READ, tcp_client_input_handler_rfc6062data, tc, 1)<0) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: cannot set TCP client data input callback\n", __FUNCTION__); err_code = 500; } else { IOA_EVENT_DEL(tc->conn_bind_timeout); } } } } } if(tc) get_and_clean_tcp_connection_by_id(server->tcp_relay_connections, tcid); if(!resp_constructed) { if(!err_code) { size_t len = ioa_network_buffer_get_size(nbh); stun_init_success_response_str(STUN_METHOD_CONNECTION_BIND, ioa_network_buffer_data(nbh), &len, tid); ioa_network_buffer_set_size(nbh,len); } else { size_t len = ioa_network_buffer_get_size(nbh); stun_init_error_response_str(STUN_METHOD_CONNECTION_BIND, ioa_network_buffer_data(nbh), &len, err_code, NULL, tid); ioa_network_buffer_set_size(nbh,len); } } { size_t fsz = strlen(get_version(server)); const uint8_t *field = (const uint8_t *) get_version(server); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_SOFTWARE, field, fsz); ioa_network_buffer_set_size(nbh, len); } if(message_integrity && ss) { size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_integrity_str(server->ct,ioa_network_buffer_data(nbh),&len,ss->hmackey,ss->pwd,SHATYPE_DEFAULT); ioa_network_buffer_set_size(nbh,len); } if ((server->fingerprint) || (ss &&(ss->enforce_fingerprints))) { size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_fingerprint_str(ioa_network_buffer_data(nbh), &len); ioa_network_buffer_set_size(nbh, len); } if(server->verbose) { log_method(ss, "CONNECTION_BIND", err_code, reason); } if(ss && !err_code) { send_data_from_ioa_socket_nbh(s, NULL, nbh, TTL_IGNORE, TOS_IGNORE, NULL); tcp_deliver_delayed_buffer(&(tc->ub_to_client),s,ss); IOA_CLOSE_SOCKET(s_to_delete); FUNCEND; return 0; } else { /* Just to set the necessary structures for the packet sending: */ if(register_callback_on_ioa_socket(server->e, s, IOA_EV_READ, NULL, NULL, 1)<0) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: cannot set TCP tmp client data input callback\n", __FUNCTION__); ioa_network_buffer_delete(server->e, nbh); } else { send_data_from_ioa_socket_nbh(s, NULL, nbh, TTL_IGNORE, TOS_IGNORE, NULL); } } } IOA_CLOSE_SOCKET(s_to_delete); FUNCEND; return -1; } /* <<== RFC 6062 */ static int handle_turn_channel_bind(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh) { FUNCSTART; uint16_t chnum = 0; ioa_addr peer_addr; addr_set_any(&peer_addr); allocation* a = get_allocation_ss(ss); int addr_found = 0; if(ss->is_tcp_relay) { *err_code = 403; *reason = (const uint8_t *)"Channel bind cannot be used with TCP relay"; } else if (is_allocation_valid(a)) { stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_CHANNEL_NUMBER: { if (chnum) { chnum = 0; *err_code = 400; *reason = (const uint8_t *)"Channel number cannot be duplicated in this request"; break; } chnum = stun_attr_get_channel_number(sar); if (!chnum) { *err_code = 400; *reason = (const uint8_t *)"Channel number cannot be zero in this request"; break; } } break; case STUN_ATTRIBUTE_XOR_PEER_ADDRESS: { stun_attr_get_addr_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar, &peer_addr, NULL); if(!get_relay_socket(a,peer_addr.ss.sa_family)) { *err_code = 443; *reason = (const uint8_t *)"Peer Address Family Mismatch (3)"; } if(addr_get_port(&peer_addr) < 1) { *err_code = 400; *reason = (const uint8_t *)"Empty port number in channel bind request"; } else { addr_found = 1; } break; } default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if (*ua_num > 0) { *err_code = 420; } else if (*err_code) { ; } else if (!chnum || addr_any(&peer_addr) || !addr_found) { *err_code = 400; *reason = (const uint8_t *)"Bad channel bind request"; } else if(!STUN_VALID_CHANNEL(chnum)) { *err_code = 400; *reason = (const uint8_t *)"Bad channel number"; } else { ch_info* chn = allocation_get_ch_info(a, chnum); turn_permission_info* tinfo = NULL; if (chn) { if (!addr_eq(&peer_addr, &(chn->peer_addr))) { *err_code = 400; *reason = (const uint8_t *)"You cannot use the same channel number with different peer"; } else { tinfo = (turn_permission_info*) (chn->owner); if (!tinfo) { *err_code = 500; *reason = (const uint8_t *)"Wrong permission info"; } else { if (!addr_eq_no_port(&peer_addr, &(tinfo->addr))) { *err_code = 500; *reason = (const uint8_t *)"Wrong permission info and peer addr combination"; } else if (chn->port != addr_get_port(&peer_addr)) { *err_code = 500; *reason = (const uint8_t *)"Wrong port number"; } } } } else { chn = allocation_get_ch_info_by_peer_addr(a, &peer_addr); if(chn) { *err_code = 400; *reason = (const uint8_t *)"You cannot use the same peer with different channel number"; } else { if(!good_peer_addr(server,ss->realm_options.name,&peer_addr)) { *err_code = 403; *reason = (const uint8_t *) "Forbidden IP"; } else { chn = allocation_get_new_ch_info(a, chnum, &peer_addr); if (!chn) { *err_code = 500; *reason = (const uint8_t *) "Cannot find channel data"; } else { tinfo = (turn_permission_info*) (chn->owner); if (!tinfo) { *err_code = 500; *reason = (const uint8_t *) "Wrong turn permission info"; } } } } } if (!(*err_code) && chn && tinfo) { if (update_channel_lifetime(ss,chn) < 0) { *err_code = 500; *reason = (const uint8_t *)"Cannot update channel lifetime (internal error)"; } else { size_t len = ioa_network_buffer_get_size(nbh); stun_set_channel_bind_response_str(ioa_network_buffer_data(nbh), &len, tid, 0, NULL); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; if(!(ss->is_mobile)) { if(get_ioa_socket_type(ss->client_socket) == UDP_SOCKET || get_ioa_socket_type(ss->client_socket) == TCP_SOCKET || get_ioa_socket_type(ss->client_socket) == SCTP_SOCKET) { if(get_ioa_socket_type(get_relay_socket(&(ss->alloc),peer_addr.ss.sa_family)) == UDP_SOCKET) { chn->kernel_channel = CREATE_TURN_CHANNEL_KERNEL(chn->chnum, get_ioa_socket_address_family(ss->client_socket), peer_addr.ss.sa_family, (get_ioa_socket_type(ss->client_socket)==UDP_SOCKET ? IPPROTO_UDP : IPPROTO_TCP), &(get_remote_addr_from_ioa_socket(ss->client_socket)->ss), &(get_local_addr_from_ioa_socket(ss->client_socket)->ss), &(get_local_addr_from_ioa_socket(get_relay_socket(&(ss->alloc),peer_addr.ss.sa_family))), &(get_remote_addr_from_ioa_socket(get_relay_socket(&(ss->alloc),peer_addr.ss.sa_family))) ); } } } } } } } FUNCEND; return 0; } static int handle_turn_binding(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh, int *origin_changed, ioa_addr *response_origin, int *dest_changed, ioa_addr *response_destination, uint32_t cookie, int old_stun) { FUNCSTART; int change_ip = 0; int change_port = 0; int padding = 0; int response_port_present = 0; uint16_t response_port = 0; SOCKET_TYPE st = get_ioa_socket_type(ss->client_socket); int use_reflected_from = 0; if(!(ss->client_socket)) return -1; *origin_changed = 0; *dest_changed = 0; stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { case OLD_STUN_ATTRIBUTE_PASSWORD: SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_CHANGE_REQUEST: /* * This fix allows the client program from the Stuntman source to make STUN binding requests * to this server. * * It was provided by John Selbie, from STUNTMAN project: * * "Here's the gist of the change. Stuntman comes with a STUN client library * and client program. The client program displays the mapped IP address and * port if it gets back a successful binding response. * It also interops with JSTUN, a Java implementation of STUN. * However, the JSTUN server refuses to respond to any binding request that * doesn't have a CHANGE-REQUEST attribute in it. * ... workaround is for the client to make a request with an empty CHANGE-REQUEST * attribute (neither the ip or port bit are set)." * */ stun_attr_get_change_request_str(sar, &change_ip, &change_port); if( (!is_rfc5780(server)) && (change_ip || change_port)) { *err_code = 420; *reason = (const uint8_t *)"Unknown attribute: TURN server was configured without RFC 5780 support"; break; } if(change_ip || change_port) { if(st != UDP_SOCKET) { *err_code = 400; *reason = (const uint8_t *)"Wrong request: applicable only to UDP protocol"; } } break; case STUN_ATTRIBUTE_PADDING: if(response_port_present) { *err_code = 400; *reason = (const uint8_t *)"Wrong request format: you cannot use PADDING and RESPONSE_PORT together"; } else if((st != UDP_SOCKET) && (st != DTLS_SOCKET)) { *err_code = 400; *reason = (const uint8_t *)"Wrong request: padding applicable only to UDP and DTLS protocols"; } else { padding = 1; } break; case STUN_ATTRIBUTE_RESPONSE_PORT: if(padding) { *err_code = 400; *reason = (const uint8_t *)"Wrong request format: you cannot use PADDING and RESPONSE_PORT together"; } else if(st != UDP_SOCKET) { *err_code = 400; *reason = (const uint8_t *)"Wrong request: applicable only to UDP protocol"; } else { int rp = stun_attr_get_response_port_str(sar); if(rp>=0) { response_port_present = 1; response_port = (uint16_t)rp; } else { *err_code = 400; *reason = (const uint8_t *)"Wrong response port format"; } } break; case OLD_STUN_ATTRIBUTE_RESPONSE_ADDRESS: if(old_stun) { use_reflected_from = 1; stun_attr_get_addr_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar, response_destination, response_destination); } break; default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if (*ua_num > 0) { *err_code = 420; } else if (*err_code) { ; } else if(ss->client_socket && get_remote_addr_from_ioa_socket(ss->client_socket)) { size_t len = ioa_network_buffer_get_size(nbh); if (stun_set_binding_response_str(ioa_network_buffer_data(nbh), &len, tid, get_remote_addr_from_ioa_socket(ss->client_socket), 0, NULL, cookie, old_stun) >= 0) { addr_cpy(response_origin, get_local_addr_from_ioa_socket(ss->client_socket)); *resp_constructed = 1; if(old_stun && use_reflected_from) { stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_REFLECTED_FROM, get_remote_addr_from_ioa_socket(ss->client_socket)); } if(!is_rfc5780(server)) { if(old_stun) { stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_SOURCE_ADDRESS, response_origin); stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_CHANGED_ADDRESS, response_origin); } else { stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_RESPONSE_ORIGIN, response_origin); } } else if(ss->client_socket) { ioa_addr other_address; if(get_other_address(server,ss,&other_address) == 0) { addr_cpy(response_destination, get_remote_addr_from_ioa_socket(ss->client_socket)); if(change_ip) { *origin_changed = 1; if(change_port) { addr_cpy(response_origin,&other_address); } else { int old_port = addr_get_port(response_origin); addr_cpy(response_origin,&other_address); addr_set_port(response_origin,old_port); } } else if(change_port) { *origin_changed = 1; addr_set_port(response_origin,addr_get_port(&other_address)); } if(old_stun) { stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_SOURCE_ADDRESS, response_origin); stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_CHANGED_ADDRESS, &other_address); } else { stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_RESPONSE_ORIGIN, response_origin); stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_OTHER_ADDRESS, &other_address); } if(response_port_present) { *dest_changed = 1; addr_set_port(response_destination, (int)response_port); } if(padding) { int mtu = get_local_mtu_ioa_socket(ss->client_socket); if(mtu<68) mtu=1500; mtu = (mtu >> 2) << 2; stun_attr_add_padding_str(ioa_network_buffer_data(nbh), &len, (uint16_t)mtu); } } } } ioa_network_buffer_set_size(nbh, len); } FUNCEND; return 0; } static int handle_turn_send(turn_turnserver *server, ts_ur_super_session *ss, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer) { FUNCSTART; ioa_addr peer_addr; const uint8_t* value = NULL; int len = -1; int addr_found = 0; int set_df = 0; addr_set_any(&peer_addr); allocation* a = get_allocation_ss(ss); if(ss->is_tcp_relay) { *err_code = 403; *reason = (const uint8_t *)"Send cannot be used with TCP relay"; } else if (is_allocation_valid(a) && (in_buffer->recv_ttl != 0)) { stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_DONT_FRAGMENT: if(!(server->dont_fragment)) unknown_attrs[(*ua_num)++] = nswap16(attr_type); else set_df = 1; break; case STUN_ATTRIBUTE_XOR_PEER_ADDRESS: { if (addr_found) { *err_code = 400; *reason = (const uint8_t *)"Address duplication"; } else { stun_attr_get_addr_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar, &peer_addr, NULL); } } break; case STUN_ATTRIBUTE_DATA: { if (len >= 0) { *err_code = 400; *reason = (const uint8_t *)"Data duplication"; } else { len = stun_attr_get_len(sar); value = stun_attr_get_value(sar); } } break; default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if (*err_code) { ; } else if (*ua_num > 0) { *err_code = 420; } else if (!addr_any(&peer_addr) && len >= 0) { turn_permission_info* tinfo = NULL; if(!(server->server_relay)) tinfo = allocation_get_permission(a, &peer_addr); if (tinfo || (server->server_relay)) { set_df_on_ioa_socket(get_relay_socket_ss(ss,peer_addr.ss.sa_family), set_df); ioa_network_buffer_handle nbh = in_buffer->nbh; if(value && len>0) { uint16_t offset = (uint16_t)(value - ioa_network_buffer_data(nbh)); ioa_network_buffer_add_offset_size(nbh,offset,0,len); } else { len = 0; ioa_network_buffer_set_size(nbh,len); } ioa_network_buffer_header_init(nbh); int skip = 0; send_data_from_ioa_socket_nbh(get_relay_socket_ss(ss,peer_addr.ss.sa_family), &peer_addr, nbh, in_buffer->recv_ttl-1, in_buffer->recv_tos, &skip); if (!skip) { ++(ss->peer_sent_packets); ss->peer_sent_bytes += len; turn_report_session_usage(ss, 0); } in_buffer->nbh = NULL; } } else { *err_code = 400; *reason = (const uint8_t *)"No address found"; } } FUNCEND; return 0; } static int update_permission(ts_ur_super_session *ss, ioa_addr *peer_addr) { if (!ss || !peer_addr) return -1; allocation* a = get_allocation_ss(ss); turn_permission_info* tinfo = allocation_get_permission(a, peer_addr); if (!tinfo) { tinfo = allocation_add_permission(a, peer_addr); } if (!tinfo) return -1; if (update_turn_permission_lifetime(ss, tinfo, 0) < 0) return -1; ch_info *chn = get_turn_channel(tinfo, peer_addr); if(chn) { if (update_channel_lifetime(ss, chn) < 0) return -1; } return 0; } static int handle_turn_create_permission(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, uint16_t *unknown_attrs, uint16_t *ua_num, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh) { int ret = -1; int addr_found = 0; UNUSED_ARG(server); allocation* a = get_allocation_ss(ss); if (is_allocation_valid(a)) { { stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar && (!(*err_code)) && (*ua_num < MAX_NUMBER_OF_UNKNOWN_ATTRS)) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_XOR_PEER_ADDRESS: { ioa_addr peer_addr; addr_set_any(&peer_addr); stun_attr_get_addr_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar, &peer_addr, NULL); if(!get_relay_socket(a,peer_addr.ss.sa_family)) { *err_code = 443; *reason = (const uint8_t *)"Peer Address Family Mismatch (4)"; } else if(!good_peer_addr(server, ss->realm_options.name, &peer_addr)) { *err_code = 403; *reason = (const uint8_t *) "Forbidden IP"; } else { addr_found++; } } break; default: if(attr_type>=0x0000 && attr_type<=0x7FFF) unknown_attrs[(*ua_num)++] = nswap16(attr_type); }; sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } } if (*ua_num > 0) { *err_code = 420; } else if (*err_code) { ; } else if (!addr_found) { *err_code = 400; *reason = (const uint8_t *)"No address found"; } else { stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); while (sar) { int attr_type = stun_attr_get_type(sar); switch (attr_type) { SKIP_ATTRIBUTES; case STUN_ATTRIBUTE_XOR_PEER_ADDRESS: { ioa_addr peer_addr; addr_set_any(&peer_addr); stun_attr_get_addr_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar, &peer_addr, NULL); addr_set_port(&peer_addr, 0); if (update_permission(ss, &peer_addr) < 0) { *err_code = 500; *reason = (const uint8_t *)"Cannot update some permissions (critical server software error)"; } } break; default: ; } sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if(*err_code == 0) { size_t len = ioa_network_buffer_get_size(nbh); stun_init_success_response_str(STUN_METHOD_CREATE_PERMISSION, ioa_network_buffer_data(nbh), &len, tid); ioa_network_buffer_set_size(nbh,len); ret = 0; *resp_constructed = 1; } } } return ret; } // AUTH ==>> static int need_stun_authentication(turn_turnserver *server, ts_ur_super_session *ss) { UNUSED_ARG(ss); if(server) { switch(server->ct) { case TURN_CREDENTIALS_LONG_TERM: return 1; default: ; }; } return 0; } static int create_challenge_response(ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, ioa_network_buffer_handle nbh, uint16_t method) { size_t len = ioa_network_buffer_get_size(nbh); stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, *err_code, *reason, tid); *resp_constructed = 1; stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_NONCE, ss->nonce, (int)(NONCE_MAX_SIZE-1)); char *realm = ss->realm_options.name; stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_REALM, (uint8_t*)realm, (int)(strlen((char*)(realm)))); if(ss->server) { turn_turnserver* server = (turn_turnserver*)ss->server; if(server->oauth) { const char *server_name = server->oauth_server_name; if(!(server_name && server_name[0])) { server_name = realm; } stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_THIRD_PARTY_AUTHORIZATION, (const uint8_t*)(server_name), strlen(server_name)); } } ioa_network_buffer_set_size(nbh,len); return 0; } #if !defined(min) #define min(a,b) ((a)<=(b) ? (a) : (b)) #endif static void resume_processing_after_username_check(int success, int oauth, int max_session_time, hmackey_t hmackey, password_t pwd, turn_turnserver *server, uint64_t ctxkey, ioa_net_data *in_buffer, uint8_t *realm) { if(server && in_buffer && in_buffer->nbh) { ts_ur_super_session *ss = get_session_from_map(server,(turnsession_id)ctxkey); if(ss && ss->client_socket) { turn_turnserver *server = (turn_turnserver *)ss->server; if(success) { bcopy(hmackey,ss->hmackey,sizeof(hmackey_t)); ss->hmackey_set = 1; ss->oauth = oauth; ss->max_session_time_auth = (turn_time_t)max_session_time; bcopy(pwd,ss->pwd,sizeof(password_t)); if(realm && realm[0] && strcmp((char*)realm,ss->realm_options.name)) { dec_quota(ss); get_realm_options_by_name((char*)realm, &(ss->realm_options)); inc_quota(ss,ss->username); } } read_client_connection(server,ss,in_buffer,0,0); close_ioa_socket_after_processing_if_necessary(ss->client_socket); ioa_network_buffer_delete(server->e, in_buffer->nbh); in_buffer->nbh=NULL; } } } static int check_stun_auth(turn_turnserver *server, ts_ur_super_session *ss, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh, uint16_t method, int *message_integrity, int *postpone_reply, int can_resume) { uint8_t usname[STUN_MAX_USERNAME_SIZE+1]; uint8_t nonce[STUN_MAX_NONCE_SIZE+1]; uint8_t realm[STUN_MAX_REALM_SIZE+1]; size_t alen = 0; if(!need_stun_authentication(server, ss)) return 0; int new_nonce = 0; { int generate_new_nonce = 0; if(ss->nonce[0]==0) { generate_new_nonce = 1; new_nonce = 1; } if(*(server->stale_nonce)) { if(turn_time_before(ss->nonce_expiration_time,server->ctime)) { generate_new_nonce = 1; } } if(generate_new_nonce) { int i = 0; if(TURN_RANDOM_SIZE == 8) { for(i=0;i<(NONCE_LENGTH_32BITS>>1);i++) { uint8_t *s = ss->nonce + 8*i; uint64_t rand=(uint64_t)turn_random(); snprintf((char*)s, NONCE_MAX_SIZE-8*i, "%08lx",(unsigned long)rand); } } else { for(i=0;i<NONCE_LENGTH_32BITS;i++) { uint8_t *s = ss->nonce + 4*i; uint32_t rand=(uint32_t)turn_random(); snprintf((char*)s, NONCE_MAX_SIZE-4*i, "%04x",(unsigned int)rand); } } ss->nonce_expiration_time = server->ctime + *(server->stale_nonce); } } /* MESSAGE_INTEGRITY ATTR: */ stun_attr_ref sar = stun_attr_get_first_by_type_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), STUN_ATTRIBUTE_MESSAGE_INTEGRITY); if(!sar) { *err_code = 401; return create_challenge_response(ss,tid,resp_constructed,err_code,reason,nbh,method); } { int sarlen = stun_attr_get_len(sar); switch(sarlen) { case SHA1SIZEBYTES: break; case SHA256SIZEBYTES: case SHA384SIZEBYTES: case SHA512SIZEBYTES: default: *err_code = 401; return create_challenge_response(ss,tid,resp_constructed,err_code,reason,nbh,method); }; } { /* REALM ATTR: */ sar = stun_attr_get_first_by_type_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), STUN_ATTRIBUTE_REALM); if(!sar) { *err_code = 400; return -1; } alen = min((size_t)stun_attr_get_len(sar),sizeof(realm)-1); bcopy(stun_attr_get_value(sar),realm,alen); realm[alen]=0; if(!is_secure_string(realm,0)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: wrong realm: %s\n", __FUNCTION__, (char*)realm); realm[0]=0; *err_code = 400; return -1; } if(method == STUN_METHOD_CONNECTION_BIND) { get_realm_options_by_name((char *)realm, &(ss->realm_options)); } else if(strcmp((char*)realm, (char*)(ss->realm_options.name))) { if(!(ss->oauth)){ if(method == STUN_METHOD_ALLOCATE) { *err_code = 437; *reason = (const uint8_t*)"Allocation mismatch: wrong credentials: the realm value is incorrect"; } else { *err_code = 441; *reason = (const uint8_t*)"Wrong credentials: the realm value is incorrect"; } return -1; } else { bcopy(ss->realm_options.name,realm,sizeof(ss->realm_options.name)); } } } /* USERNAME ATTR: */ sar = stun_attr_get_first_by_type_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), STUN_ATTRIBUTE_USERNAME); if(!sar) { *err_code = 400; return -1; } alen = min((size_t)stun_attr_get_len(sar),sizeof(usname)-1); bcopy(stun_attr_get_value(sar),usname,alen); usname[alen]=0; if(!is_secure_string(usname,1)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: wrong username: %s\n", __FUNCTION__, (char*)usname); usname[0]=0; *err_code = 400; return -1; } else if(ss->username[0]) { if(strcmp((char*)ss->username,(char*)usname)) { if(ss->oauth) { ss->hmackey_set = 0; STRCPY(ss->username,usname); } else { if(method == STUN_METHOD_ALLOCATE) { *err_code = 437; *reason = (const uint8_t*)"Allocation mismatch: wrong credentials"; } else { *err_code = 441; } return -1; } } } else { STRCPY(ss->username,usname); } { /* NONCE ATTR: */ sar = stun_attr_get_first_by_type_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), STUN_ATTRIBUTE_NONCE); if(!sar) { *err_code = 400; return -1; } alen = min((size_t)stun_attr_get_len(sar),sizeof(nonce)-1); bcopy(stun_attr_get_value(sar),nonce,alen); nonce[alen]=0; /* Stale Nonce check: */ if(new_nonce) { *err_code = 438; *reason = (const uint8_t*)"Wrong nonce"; return create_challenge_response(ss,tid,resp_constructed,err_code,reason,nbh,method); } if(strcmp((char*)ss->nonce,(char*)nonce)) { *err_code = 438; *reason = (const uint8_t*)"Stale nonce"; return create_challenge_response(ss,tid,resp_constructed,err_code,reason,nbh,method); } } /* Password */ if(!(ss->hmackey_set) && (ss->pwd[0] == 0)) { if(can_resume) { (server->userkeycb)(server->id, server->ct, server->oauth, &(ss->oauth), usname, realm, resume_processing_after_username_check, in_buffer, ss->id, postpone_reply); if(*postpone_reply) { return 0; } } TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: Cannot find credentials of user <%s>\n", __FUNCTION__, (char*)usname); *err_code = 401; return create_challenge_response(ss,tid,resp_constructed,err_code,reason,nbh,method); } /* Check integrity */ if(stun_check_message_integrity_by_key_str(server->ct,ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), ss->hmackey, ss->pwd, SHATYPE_DEFAULT)<1) { if(can_resume) { (server->userkeycb)(server->id, server->ct, server->oauth, &(ss->oauth), usname, realm, resume_processing_after_username_check, in_buffer, ss->id, postpone_reply); if(*postpone_reply) { return 0; } } TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: user %s credentials are incorrect\n", __FUNCTION__, (char*)usname); *err_code = 401; return create_challenge_response(ss,tid,resp_constructed,err_code,reason,nbh,method); } *message_integrity = 1; return 0; } //<<== AUTH static void set_alternate_server(turn_server_addrs_list_t *asl, const ioa_addr *local_addr, size_t *counter, uint16_t method, stun_tid *tid, int *resp_constructed, int *err_code, const uint8_t **reason, ioa_network_buffer_handle nbh) { if(asl && asl->size && local_addr) { size_t i; /* to prevent indefinite cycle: */ for(i=0;i<asl->size;++i) { ioa_addr *addr = &(asl->addrs[i]); if(addr_eq(addr,local_addr)) return; } for(i=0;i<asl->size;++i) { if(*counter>=asl->size) *counter = 0; ioa_addr *addr = &(asl->addrs[*counter]); *counter +=1; if(addr->ss.sa_family == local_addr->ss.sa_family) { *err_code = 300; size_t len = ioa_network_buffer_get_size(nbh); stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, *err_code, *reason, tid); *resp_constructed = 1; stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_ALTERNATE_SERVER, addr); ioa_network_buffer_set_size(nbh,len); return; } } } } static int handle_turn_command(turn_turnserver *server, ts_ur_super_session *ss, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh, int *resp_constructed, int can_resume) { stun_tid tid; int err_code = 0; const uint8_t *reason = NULL; int no_response = 0; int message_integrity = 0; if(!(ss->client_socket)) return -1; uint16_t unknown_attrs[MAX_NUMBER_OF_UNKNOWN_ATTRS]; uint16_t ua_num = 0; uint16_t method = stun_get_method_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); *resp_constructed = 0; stun_tid_from_message_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), &tid); if (stun_is_request_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh))) { if((method == STUN_METHOD_BINDING) && (*(server->no_stun))) { no_response = 1; if(server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: STUN method 0x%x ignored\n", __FUNCTION__, (unsigned int)method); } } else if((method != STUN_METHOD_BINDING) && (*(server->stun_only))) { no_response = 1; if(server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: STUN method 0x%x ignored\n", __FUNCTION__, (unsigned int)method); } } else if((method != STUN_METHOD_BINDING) || (*(server->secure_stun))) { if(method == STUN_METHOD_ALLOCATE) { allocation *a = get_allocation_ss(ss); if(is_allocation_valid(a)) { if(!stun_tid_equals(&(a->tid), &tid)) { err_code = 437; reason = (const uint8_t *)"Mismatched allocation: wrong transaction ID"; } } if(!err_code) { SOCKET_TYPE cst = get_ioa_socket_type(ss->client_socket); turn_server_addrs_list_t *asl = server->alternate_servers_list; if(((cst == UDP_SOCKET)||(cst == DTLS_SOCKET)) && server->self_udp_balance && server->aux_servers_list && server->aux_servers_list->size) { asl = server->aux_servers_list; } else if(((cst == TLS_SOCKET) || (cst == DTLS_SOCKET) ||(cst == TLS_SCTP_SOCKET)) && server->tls_alternate_servers_list && server->tls_alternate_servers_list->size) { asl = server->tls_alternate_servers_list; } if(asl && asl->size) { turn_mutex_lock(&(asl->m)); set_alternate_server(asl,get_local_addr_from_ioa_socket(ss->client_socket),&(server->as_counter),method,&tid,resp_constructed,&err_code,&reason,nbh); turn_mutex_unlock(&(asl->m)); } } } /* check that the realm is the same as in the original request */ if(ss->origin_set) { stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); int origin_found = 0; int norigins = 0; while(sar && !origin_found) { if(stun_attr_get_type(sar) == STUN_ATTRIBUTE_ORIGIN) { int sarlen = stun_attr_get_len(sar); if(sarlen>0) { ++norigins; char *o = (char*)malloc(sarlen+1); bcopy(stun_attr_get_value(sar),o,sarlen); o[sarlen]=0; char *corigin = (char*)malloc(STUN_MAX_ORIGIN_SIZE+1); corigin[0]=0; if(get_canonic_origin(o,corigin,STUN_MAX_ORIGIN_SIZE)<0) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: Wrong origin format: %s\n", __FUNCTION__, o); } if(!strncmp(ss->origin,corigin,STUN_MAX_ORIGIN_SIZE)) { origin_found = 1; } free(corigin); free(o); } } sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } if(server->check_origin && *(server->check_origin)) { if(ss->origin[0]) { if(!origin_found) { err_code = 441; reason = (const uint8_t *)"The origin attribute does not match the initial session origin value"; if(server->verbose) { char smethod[129]; stun_method_str(method,smethod); log_method(ss, smethod, err_code, reason); } } } else if(norigins > 0){ err_code = 441; reason = (const uint8_t *)"The origin attribute is empty, does not match the initial session origin value"; if(server->verbose) { char smethod[129]; stun_method_str(method,smethod); log_method(ss, smethod, err_code, reason); } } } } /* get the initial origin value */ if(!err_code && !(ss->origin_set) && (method == STUN_METHOD_ALLOCATE)) { stun_attr_ref sar = stun_attr_get_first_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); int origin_found = 0; while(sar && !origin_found) { if(stun_attr_get_type(sar) == STUN_ATTRIBUTE_ORIGIN) { int sarlen = stun_attr_get_len(sar); if(sarlen>0) { char *o = (char*)malloc(sarlen+1); bcopy(stun_attr_get_value(sar),o,sarlen); o[sarlen]=0; char *corigin = (char*)malloc(STUN_MAX_ORIGIN_SIZE+1); corigin[0]=0; if(get_canonic_origin(o,corigin,STUN_MAX_ORIGIN_SIZE)<0) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: Wrong origin format: %s\n", __FUNCTION__, o); } strncpy(ss->origin,corigin,STUN_MAX_ORIGIN_SIZE); free(corigin); free(o); origin_found = get_realm_options_by_origin(ss->origin,&(ss->realm_options)); } } sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar); } ss->origin_set = 1; } if(!err_code && !(*resp_constructed) && !no_response) { if(method == STUN_METHOD_CONNECTION_BIND) { ; } else if(!(*(server->mobility)) || (method != STUN_METHOD_REFRESH) || is_allocation_valid(get_allocation_ss(ss))) { int postpone_reply = 0; check_stun_auth(server, ss, &tid, resp_constructed, &err_code, &reason, in_buffer, nbh, method, &message_integrity, &postpone_reply, can_resume); if(postpone_reply) no_response = 1; } } } if (!err_code && !(*resp_constructed) && !no_response) { switch (method){ case STUN_METHOD_ALLOCATE: { handle_turn_allocate(server, ss, &tid, resp_constructed, &err_code, &reason, unknown_attrs, &ua_num, in_buffer, nbh); if(server->verbose) { log_method(ss, "ALLOCATE", err_code, reason); } break; } case STUN_METHOD_CONNECT: handle_turn_connect(server, ss, &tid, &err_code, &reason, unknown_attrs, &ua_num, in_buffer); if(server->verbose) { log_method(ss, "CONNECT", err_code, reason); } if(!err_code) no_response = 1; break; case STUN_METHOD_CONNECTION_BIND: handle_turn_connection_bind(server, ss, &tid, resp_constructed, &err_code, &reason, unknown_attrs, &ua_num, in_buffer, nbh, message_integrity, can_resume); if(server->verbose && err_code) { log_method(ss, "CONNECTION_BIND", err_code, reason); } break; case STUN_METHOD_REFRESH: handle_turn_refresh(server, ss, &tid, resp_constructed, &err_code, &reason, unknown_attrs, &ua_num, in_buffer, nbh, message_integrity, &no_response, can_resume); if(server->verbose) { log_method(ss, "REFRESH", err_code, reason); } break; case STUN_METHOD_CHANNEL_BIND: handle_turn_channel_bind(server, ss, &tid, resp_constructed, &err_code, &reason, unknown_attrs, &ua_num, in_buffer, nbh); if(server->verbose) { log_method(ss, "CHANNEL_BIND", err_code, reason); } break; case STUN_METHOD_CREATE_PERMISSION: handle_turn_create_permission(server, ss, &tid, resp_constructed, &err_code, &reason, unknown_attrs, &ua_num, in_buffer, nbh); if(server->verbose) { log_method(ss, "CREATE_PERMISSION", err_code, reason); } break; case STUN_METHOD_BINDING: { int origin_changed=0; ioa_addr response_origin; int dest_changed=0; ioa_addr response_destination; handle_turn_binding(server, ss, &tid, resp_constructed, &err_code, &reason, unknown_attrs, &ua_num, in_buffer, nbh, &origin_changed, &response_origin, &dest_changed, &response_destination, 0, 0); if(server->verbose && server->log_binding) { log_method(ss, "BINDING", err_code, reason); } if(*resp_constructed && !err_code && (origin_changed || dest_changed)) { if (server->verbose && server->log_binding) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "RFC 5780 request successfully processed\n"); } { const uint8_t *field = (const uint8_t *) get_version(server); size_t fsz = strlen(get_version(server)); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_SOFTWARE, field, fsz); ioa_network_buffer_set_size(nbh, len); } send_turn_message_to(server, nbh, &response_origin, &response_destination); no_response = 1; } break; } default: TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unsupported STUN request received, method 0x%x\n",(unsigned int)method); }; } } else if (stun_is_indication_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh))) { no_response = 1; int postpone = 0; if (!postpone && !err_code) { switch (method){ case STUN_METHOD_BINDING: //ICE ? break; case STUN_METHOD_SEND: handle_turn_send(server, ss, &err_code, &reason, unknown_attrs, &ua_num, in_buffer); if(eve(server->verbose)) { log_method(ss, "SEND", err_code, reason); } break; case STUN_METHOD_DATA: err_code = 403; if(eve(server->verbose)) { log_method(ss, "DATA", err_code, reason); } break; default: if (server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Unsupported STUN indication received: method 0x%x\n",(unsigned int)method); } } }; } else { no_response = 1; if (server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Wrong STUN message received\n"); } } if(ss->to_be_closed || !(ss->client_socket) || ioa_socket_tobeclosed(ss->client_socket)) return 0; if (ua_num > 0) { err_code = 420; size_t len = ioa_network_buffer_get_size(nbh); stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, err_code, NULL, &tid); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_UNKNOWN_ATTRIBUTES, (const uint8_t*) unknown_attrs, (ua_num * 2)); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } if (!no_response) { if (!(*resp_constructed)) { if (!err_code) err_code = 400; size_t len = ioa_network_buffer_get_size(nbh); stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, err_code, reason, &tid); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } { const uint8_t *field = (const uint8_t *) get_version(server); size_t fsz = strlen(get_version(server)); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_SOFTWARE, field, fsz); ioa_network_buffer_set_size(nbh, len); } if(message_integrity) { size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_integrity_str(server->ct,ioa_network_buffer_data(nbh),&len,ss->hmackey,ss->pwd,SHATYPE_DEFAULT); ioa_network_buffer_set_size(nbh,len); } if(err_code) { if(server->verbose) { log_method(ss, "message", err_code, reason); } } } else { *resp_constructed = 0; } return 0; } static int handle_old_stun_command(turn_turnserver *server, ts_ur_super_session *ss, ioa_net_data *in_buffer, ioa_network_buffer_handle nbh, int *resp_constructed, uint32_t cookie) { stun_tid tid; int err_code = 0; const uint8_t *reason = NULL; int no_response = 0; uint16_t unknown_attrs[MAX_NUMBER_OF_UNKNOWN_ATTRS]; uint16_t ua_num = 0; uint16_t method = stun_get_method_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); *resp_constructed = 0; stun_tid_from_message_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), &tid); if (stun_is_request_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh))) { if(method != STUN_METHOD_BINDING) { no_response = 1; if(server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: OLD STUN method 0x%x ignored\n", __FUNCTION__, (unsigned int)method); } } if (!err_code && !(*resp_constructed) && !no_response) { int origin_changed=0; ioa_addr response_origin; int dest_changed=0; ioa_addr response_destination; handle_turn_binding(server, ss, &tid, resp_constructed, &err_code, &reason, unknown_attrs, &ua_num, in_buffer, nbh, &origin_changed, &response_origin, &dest_changed, &response_destination, cookie,1); if(server->verbose && *(server->log_binding)) { log_method(ss, "OLD BINDING", err_code, reason); } if(*resp_constructed && !err_code && (origin_changed || dest_changed)) { if (server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "RFC3489 CHANGE request successfully processed\n"); } { size_t oldsz = strlen(get_version(server)); size_t newsz = (((oldsz)>>2) + 1)<<2; uint8_t software[120]; bzero(software,sizeof(software)); if(newsz>sizeof(software)) newsz = sizeof(software); bcopy(get_version(server),software,oldsz); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_SERVER, software, newsz); ioa_network_buffer_set_size(nbh, len); } send_turn_message_to(server, nbh, &response_origin, &response_destination); no_response = 1; } } } else { no_response = 1; if (server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Wrong OLD STUN message received\n"); } } if (ua_num > 0) { err_code = 420; size_t len = ioa_network_buffer_get_size(nbh); old_stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, err_code, NULL, &tid, cookie); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_UNKNOWN_ATTRIBUTES, (const uint8_t*) unknown_attrs, (ua_num * 2)); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } if (!no_response) { if (!(*resp_constructed)) { if (!err_code) err_code = 400; size_t len = ioa_network_buffer_get_size(nbh); old_stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, err_code, reason, &tid, cookie); ioa_network_buffer_set_size(nbh,len); *resp_constructed = 1; } { size_t oldsz = strlen(get_version(server)); size_t newsz = (((oldsz)>>2) + 1)<<2; uint8_t software[120]; bzero(software,sizeof(software)); if(newsz>sizeof(software)) newsz = sizeof(software); bcopy(get_version(server),software,oldsz); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_SERVER, software, newsz); ioa_network_buffer_set_size(nbh, len); } if(err_code) { if(server->verbose) { log_method(ss, "OLD STUN message", err_code, reason); } } } else { *resp_constructed = 0; } return 0; } ////////////////////////////////////////////////////////////////// static int write_to_peerchannel(ts_ur_super_session* ss, uint16_t chnum, ioa_net_data *in_buffer) { int rc = 0; if (ss && (in_buffer->recv_ttl!=0)) { allocation* a = get_allocation_ss(ss); if (is_allocation_valid(a)) { ch_info* chn = allocation_get_ch_info(a, chnum); if (!chn) return -1; /* Channel packets are always sent with DF=0: */ set_df_on_ioa_socket(get_relay_socket_ss(ss, chn->peer_addr.ss.sa_family), 0); ioa_network_buffer_handle nbh = in_buffer->nbh; ioa_network_buffer_add_offset_size(in_buffer->nbh, STUN_CHANNEL_HEADER_LENGTH, 0, ioa_network_buffer_get_size(in_buffer->nbh)-STUN_CHANNEL_HEADER_LENGTH); ioa_network_buffer_header_init(nbh); int skip = 0; rc = send_data_from_ioa_socket_nbh(get_relay_socket_ss(ss, chn->peer_addr.ss.sa_family), &(chn->peer_addr), nbh, in_buffer->recv_ttl-1, in_buffer->recv_tos, &skip); if (!skip && rc > -1) { ++(ss->peer_sent_packets); ss->peer_sent_bytes += (uint32_t)ioa_network_buffer_get_size(in_buffer->nbh); turn_report_session_usage(ss, 0); } in_buffer->nbh = NULL; } } return rc; } static void client_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *data, void *arg, int can_resume); static void peer_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *data, void *arg, int can_resume); /////////////// Client actions ///////////////// int shutdown_client_connection(turn_turnserver *server, ts_ur_super_session *ss, int force, const char* reason) { FUNCSTART; if (!ss) return -1; turn_report_session_usage(ss, 1); dec_quota(ss); dec_bps(ss); allocation* alloc = get_allocation_ss(ss); if (!is_allocation_valid(alloc)) { force = 1; } if(!force && ss->is_mobile) { if (ss->client_socket && server->verbose) { char sraddr[129]="\0"; char sladdr[129]="\0"; addr_to_string(get_remote_addr_from_ioa_socket(ss->client_socket),(uint8_t*)sraddr); addr_to_string(get_local_addr_from_ioa_socket(ss->client_socket),(uint8_t*)sladdr); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: closed (1st stage), user <%s> realm <%s> origin <%s>, local %s, remote %s, reason: %s\n",(unsigned long long)(ss->id),(char*)ss->username,(char*)ss->realm_options.name,(char*)ss->origin, sladdr,sraddr,reason); } IOA_CLOSE_SOCKET(ss->client_socket); FUNCEND; return 0; } if (eve(server->verbose)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "closing session 0x%lx, client socket 0x%lx (socket session=0x%lx)\n", (long) ss, (long) ss->client_socket, (long)get_ioa_socket_session(ss->client_socket)); } if (server->disconnect) server->disconnect(ss); if (server->verbose) { char sraddr[129]="\0"; char sladdr[129]="\0"; addr_to_string(get_remote_addr_from_ioa_socket(ss->client_socket),(uint8_t*)sraddr); addr_to_string(get_local_addr_from_ioa_socket(ss->client_socket),(uint8_t*)sladdr); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: closed (2nd stage), user <%s> realm <%s> origin <%s>, local %s, remote %s, reason: %s\n", (unsigned long long)(ss->id), (char*)ss->username,(char*)ss->realm_options.name,(char*)ss->origin, sladdr,sraddr, reason); } IOA_CLOSE_SOCKET(ss->client_socket); { int i; for(i=0;i<ALLOC_PROTOCOLS_NUMBER;++i) { IOA_CLOSE_SOCKET(ss->alloc.relay_sessions[i].s); } } turn_server_remove_all_from_ur_map_ss(ss); FUNCEND; return 0; } static void client_to_be_allocated_timeout_handler(ioa_engine_handle e, void *arg) { if (!arg) return; UNUSED_ARG(e); ts_ur_super_session* ss = (ts_ur_super_session*) arg; turn_turnserver* server = (turn_turnserver*) (ss->server); if (!server) return; FUNCSTART; int to_close = 0; ioa_socket_handle s = ss->client_socket; if(!s || ioa_socket_tobeclosed(s)) { to_close = 1; } else if(get_ioa_socket_app_type(s) == HTTPS_CLIENT_SOCKET) { ; } else { ioa_socket_handle rs4 = ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].s; ioa_socket_handle rs6 = ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].s; if((!rs4 || ioa_socket_tobeclosed(rs4)) && (!rs6 || ioa_socket_tobeclosed(rs6))) { to_close = 1; } else if(ss->client_socket == NULL) { to_close = 1; } else if(!(ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].lifetime_ev) && !(ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].lifetime_ev)) { to_close = 1; } else if(!(ss->to_be_allocated_timeout_ev)) { to_close = 1; } } if(to_close) { IOA_EVENT_DEL(ss->to_be_allocated_timeout_ev); shutdown_client_connection(server, ss, 1, "allocation watchdog determined stale session state"); } FUNCEND; } static int write_client_connection(turn_turnserver *server, ts_ur_super_session* ss, ioa_network_buffer_handle nbh, int ttl, int tos) { FUNCSTART; if (!(ss->client_socket)) { ioa_network_buffer_delete(server->e, nbh); FUNCEND; return -1; } else { if (eve(server->verbose)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: prepare to write to s 0x%lx\n", __FUNCTION__, (long) (ss->client_socket)); } int skip = 0; int ret = send_data_from_ioa_socket_nbh(ss->client_socket, NULL, nbh, ttl, tos, &skip); if(!skip && ret>-1) { ++(ss->sent_packets); ss->sent_bytes += (uint32_t)ioa_network_buffer_get_size(nbh); turn_report_session_usage(ss, 0); } FUNCEND; return ret; } } static void client_ss_allocation_timeout_handler(ioa_engine_handle e, void *arg) { UNUSED_ARG(e); if (!arg) return; relay_endpoint_session *rsession = (relay_endpoint_session*)arg; if(!(rsession->s)) return; ts_ur_super_session* ss = get_ioa_socket_session(rsession->s); if (!ss) return; allocation* a = get_allocation_ss(ss); turn_turnserver* server = (turn_turnserver*) (ss->server); if (!server) { clear_allocation(a); return; } FUNCSTART; int family = get_ioa_socket_address_family(rsession->s); set_allocation_family_invalid(a,family); if(!get_relay_socket(a, AF_INET) && !get_relay_socket(a, AF_INET6)) { shutdown_client_connection(server, ss, 0, "allocation timeout"); } FUNCEND; } static int create_relay_connection(turn_turnserver* server, ts_ur_super_session *ss, uint32_t lifetime, int address_family, uint8_t transport, int even_port, uint64_t in_reservation_token, uint64_t *out_reservation_token, int *err_code, const uint8_t **reason, accept_cb acb) { if (server && ss && ss->client_socket && !ioa_socket_tobeclosed(ss->client_socket)) { allocation* a = get_allocation_ss(ss); relay_endpoint_session* newelem = NULL; ioa_socket_handle rtcp_s = NULL; if (in_reservation_token) { ioa_socket_handle s = NULL; if ((get_ioa_socket_from_reservation(server->e, in_reservation_token,&s) < 0)|| !s || ioa_socket_tobeclosed(s)) { IOA_CLOSE_SOCKET(s); *err_code = 404; *reason = (const uint8_t *)"Cannot find reserved socket"; return -1; } int family = get_ioa_socket_address_family(s); newelem = get_relay_session_ss(ss,family); if(newelem->s != s) { IOA_CLOSE_SOCKET(newelem->s); bzero(newelem, sizeof(relay_endpoint_session)); newelem->s = s; } addr_debug_print(server->verbose, get_local_addr_from_ioa_socket(newelem->s), "Local relay addr (RTCP)"); } else { int family = get_family(address_family,server->e,ss->client_socket); newelem = get_relay_session_ss(ss,family); IOA_CLOSE_SOCKET(newelem->s); bzero(newelem, sizeof(relay_endpoint_session)); newelem->s = NULL; int res = create_relay_ioa_sockets(server->e, ss->client_socket, address_family, transport, even_port, &(newelem->s), &rtcp_s, out_reservation_token, err_code, reason, acb, ss); if (res < 0) { if(!(*err_code)) *err_code = 508; if(!(*reason)) *reason = (const uint8_t *)"Cannot create socket"; IOA_CLOSE_SOCKET(newelem->s); IOA_CLOSE_SOCKET(rtcp_s); return -1; } } if (newelem->s == NULL) { IOA_CLOSE_SOCKET(rtcp_s); *err_code = 508; *reason = (const uint8_t *)"Cannot create relay socket"; return -1; } if (rtcp_s) { if (out_reservation_token && *out_reservation_token) { /* OK */ } else { IOA_CLOSE_SOCKET(newelem->s); IOA_CLOSE_SOCKET(rtcp_s); *err_code = 500; *reason = (const uint8_t *)"Wrong reservation tokens (internal error)"; return -1; } } /* RFC6156: do not use DF when IPv6 is involved: */ if((get_ioa_socket_address_family(newelem->s) == AF_INET6) || (get_ioa_socket_address_family(ss->client_socket) == AF_INET6)) set_do_not_use_df(newelem->s); if(get_ioa_socket_type(newelem->s) != TCP_SOCKET) { if(register_callback_on_ioa_socket(server->e, newelem->s, IOA_EV_READ,peer_input_handler, ss, 0)<0) { return -1; } } if (lifetime<1) lifetime = STUN_DEFAULT_ALLOCATE_LIFETIME; else if(lifetime>(uint32_t)*(server->max_allocate_lifetime)) lifetime = (uint32_t)*(server->max_allocate_lifetime); ioa_timer_handle ev = set_ioa_timer(server->e, lifetime, 0, client_ss_allocation_timeout_handler, newelem, 0, "client_ss_allocation_timeout_handler"); set_allocation_lifetime_ev(a, server->ctime + lifetime, ev, get_ioa_socket_address_family(newelem->s)); set_ioa_socket_session(newelem->s, ss); } return 0; } static int refresh_relay_connection(turn_turnserver* server, ts_ur_super_session *ss, uint32_t lifetime, int even_port, uint64_t in_reservation_token, uint64_t *out_reservation_token, int *err_code, int family) { UNUSED_ARG(even_port); UNUSED_ARG(in_reservation_token); UNUSED_ARG(out_reservation_token); UNUSED_ARG(err_code); allocation* a = get_allocation_ss(ss); if (server && ss && is_allocation_valid(a)) { if (lifetime < 1) { lifetime = 1; } ioa_timer_handle ev = set_ioa_timer(server->e, lifetime, 0, client_ss_allocation_timeout_handler, get_relay_session(a,family), 0, "refresh_client_ss_allocation_timeout_handler"); set_allocation_lifetime_ev(a, server->ctime + lifetime, ev, family); return 0; } else { return -1; } } static int read_client_connection(turn_turnserver *server, ts_ur_super_session *ss, ioa_net_data *in_buffer, int can_resume, int count_usage) { FUNCSTART; if (!server || !ss || !in_buffer || !(ss->client_socket) || ss->to_be_closed || ioa_socket_tobeclosed(ss->client_socket)) { FUNCEND; return -1; } int ret = (int)ioa_network_buffer_get_size(in_buffer->nbh); if (ret < 0) { FUNCEND; return -1; } if(count_usage) { ++(ss->received_packets); ss->received_bytes += (uint32_t)ioa_network_buffer_get_size(in_buffer->nbh); turn_report_session_usage(ss, 0); } if (eve(server->verbose)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: data.buffer=0x%lx, data.len=%ld\n", __FUNCTION__, (long)ioa_network_buffer_data(in_buffer->nbh), (long)ioa_network_buffer_get_size(in_buffer->nbh)); } uint16_t chnum = 0; uint32_t old_stun_cookie = 0; size_t blen = ioa_network_buffer_get_size(in_buffer->nbh); size_t orig_blen = blen; SOCKET_TYPE st = get_ioa_socket_type(ss->client_socket); SOCKET_APP_TYPE sat = get_ioa_socket_app_type(ss->client_socket); int is_padding_mandatory = is_stream_socket(st); if(sat == HTTP_CLIENT_SOCKET) { if(server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: HTTP connection input: %s\n", __FUNCTION__, (char*)ioa_network_buffer_data(in_buffer->nbh)); } handle_http_echo(ss->client_socket); } else if(sat == HTTPS_CLIENT_SOCKET) { //??? } else if (stun_is_channel_message_str(ioa_network_buffer_data(in_buffer->nbh), &blen, &chnum, is_padding_mandatory)) { if(ss->is_tcp_relay) { //Forbidden FUNCEND; return -1; } int rc = 0; if(blen<=orig_blen) { ioa_network_buffer_set_size(in_buffer->nbh,blen); rc = write_to_peerchannel(ss, chnum, in_buffer); } if (eve(server->verbose)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: wrote to peer %d bytes\n", __FUNCTION__, (int) rc); } FUNCEND; return 0; } else if (stun_is_command_message_full_check_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), 0, &(ss->enforce_fingerprints))) { ioa_network_buffer_handle nbh = ioa_network_buffer_allocate(server->e); int resp_constructed = 0; uint16_t method = stun_get_method_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh)); handle_turn_command(server, ss, in_buffer, nbh, &resp_constructed, can_resume); if((method != STUN_METHOD_BINDING) && (method != STUN_METHOD_SEND)) report_turn_session_info(server,ss,0); if(ss->to_be_closed || ioa_socket_tobeclosed(ss->client_socket)) { FUNCEND; ioa_network_buffer_delete(server->e, nbh); return 0; } if (resp_constructed) { if ((server->fingerprint) || ss->enforce_fingerprints) { size_t len = ioa_network_buffer_get_size(nbh); if (stun_attr_add_fingerprint_str(ioa_network_buffer_data(nbh), &len) < 0) { FUNCEND ; ioa_network_buffer_delete(server->e, nbh); return -1; } ioa_network_buffer_set_size(nbh, len); } int ret = write_client_connection(server, ss, nbh, TTL_IGNORE, TOS_IGNORE); FUNCEND ; return ret; } else { ioa_network_buffer_delete(server->e, nbh); return 0; } } else if (old_stun_is_command_message_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), &old_stun_cookie) && !(*(server->no_stun))) { ioa_network_buffer_handle nbh = ioa_network_buffer_allocate(server->e); int resp_constructed = 0; handle_old_stun_command(server, ss, in_buffer, nbh, &resp_constructed, old_stun_cookie); if (resp_constructed) { int ret = write_client_connection(server, ss, nbh, TTL_IGNORE, TOS_IGNORE); FUNCEND ; return ret; } else { ioa_network_buffer_delete(server->e, nbh); return 0; } } else { SOCKET_TYPE st = get_ioa_socket_type(ss->client_socket); if(is_stream_socket(st)) { if(is_http((char*)ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh))) { const char *proto = "HTTP"; if ((st == TCP_SOCKET) && ( try_acme_redirect( (char*)ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), server->acme_redirect, ss->client_socket ) == 0 ) ) { ss->to_be_closed = 1; return 0; } else if (*server->web_admin_listen_on_workers) { if(st==TLS_SOCKET) { proto = "HTTPS"; set_ioa_socket_app_type(ss->client_socket,HTTPS_CLIENT_SOCKET); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: %s (%s %s) request: %s\n", __FUNCTION__, proto, get_ioa_socket_cipher(ss->client_socket), get_ioa_socket_ssl_method(ss->client_socket), ioa_network_buffer_get_size(in_buffer->nbh)); if(server->send_https_socket) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s socket to be detached: 0x%lx, st=%d, sat=%d\n", __FUNCTION__,(long)ss->client_socket, get_ioa_socket_type(ss->client_socket), get_ioa_socket_app_type(ss->client_socket)); ioa_socket_handle new_s = detach_ioa_socket(ss->client_socket); if(new_s) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s new detached socket: 0x%lx, st=%d, sat=%d\n", __FUNCTION__,(long)new_s, get_ioa_socket_type(new_s), get_ioa_socket_app_type(new_s)); server->send_https_socket(new_s); } ss->to_be_closed = 1; } } else { set_ioa_socket_app_type(ss->client_socket,HTTP_CLIENT_SOCKET); if(server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: %s request: %s\n", __FUNCTION__, proto, ioa_network_buffer_get_size(in_buffer->nbh)); } handle_http_echo(ss->client_socket); } return 0; } else { ss->to_be_closed = 1; return 0; } } } } //Unrecognized message received, ignore it FUNCEND; return -1; } static int attach_socket_to_session(turn_turnserver* server, ioa_socket_handle s, ts_ur_super_session* ss) { int ret = -1; FUNCSTART; if(s && server && ss && !ioa_socket_tobeclosed(s)) { if(ss->client_socket != s) { IOA_CLOSE_SOCKET(ss->client_socket); ss->client_socket = s; if(register_callback_on_ioa_socket(server->e, s, IOA_EV_READ, client_input_handler, ss, 0)<0) { return -1; } set_ioa_socket_session(s, ss); } ret = 0; } FUNCEND; return ret; } int open_client_connection_session(turn_turnserver* server, struct socket_message *sm) { FUNCSTART; if (!server) return -1; if (!(sm->s)) return -1; ts_ur_super_session* ss = create_new_ss(server); ss->client_socket = sm->s; if(register_callback_on_ioa_socket(server->e, ss->client_socket, IOA_EV_READ, client_input_handler, ss, 0)<0) { return -1; } set_ioa_socket_session(ss->client_socket, ss); int at = TURN_MAX_ALLOCATE_TIMEOUT; if(*(server->stun_only)) at = TURN_MAX_ALLOCATE_TIMEOUT_STUN_ONLY; IOA_EVENT_DEL(ss->to_be_allocated_timeout_ev); ss->to_be_allocated_timeout_ev = set_ioa_timer(server->e, at, 0, client_to_be_allocated_timeout_handler, ss, 1, "client_to_be_allocated_timeout_handler"); if(sm->nd.nbh) { client_input_handler(ss->client_socket,IOA_EV_READ,&(sm->nd),ss,sm->can_resume); ioa_network_buffer_delete(server->e, sm->nd.nbh); sm->nd.nbh = NULL; } FUNCEND; return 0; } /////////////// io handlers /////////////////// static void peer_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *in_buffer, void *arg, int can_resume) { if (!(event_type & IOA_EV_READ) || !arg) return; if(in_buffer->recv_ttl==0) return; UNUSED_ARG(can_resume); if(!s || ioa_socket_tobeclosed(s)) return; ts_ur_super_session* ss = (ts_ur_super_session*) arg; if(!ss) return; if(ss->to_be_closed) return; if(!(ss->client_socket) || ioa_socket_tobeclosed(ss->client_socket)) return; turn_turnserver *server = (turn_turnserver*) (ss->server); if (!server) return; relay_endpoint_session* elem = get_relay_session_ss(ss, get_ioa_socket_address_family(s)); if (elem->s == NULL) { return; } int offset = STUN_CHANNEL_HEADER_LENGTH; int ilen = min((int)ioa_network_buffer_get_size(in_buffer->nbh), (int)(ioa_network_buffer_get_capacity_udp() - offset)); if (ilen >= 0) { ++(ss->peer_received_packets); ss->peer_received_bytes += ilen; turn_report_session_usage(ss, 0); allocation* a = get_allocation_ss(ss); if (is_allocation_valid(a)) { uint16_t chnum = 0; ioa_network_buffer_handle nbh = NULL; turn_permission_info* tinfo = allocation_get_permission(a, &(in_buffer->src_addr)); if (tinfo) { chnum = get_turn_channel_number(tinfo, &(in_buffer->src_addr)); } else if(!(server->server_relay)) { return; } if (chnum) { size_t len = (size_t)(ilen); nbh = in_buffer->nbh; ioa_network_buffer_add_offset_size(nbh, 0, STUN_CHANNEL_HEADER_LENGTH, ioa_network_buffer_get_size(nbh)+STUN_CHANNEL_HEADER_LENGTH); ioa_network_buffer_header_init(nbh); SOCKET_TYPE st = get_ioa_socket_type(ss->client_socket); int do_padding = is_stream_socket(st); stun_init_channel_message_str(chnum, ioa_network_buffer_data(nbh), &len, len, do_padding); ioa_network_buffer_set_size(nbh,len); in_buffer->nbh = NULL; if (eve(server->verbose)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: send channel 0x%x\n", __FUNCTION__, (int) (chnum)); } } else { size_t len = 0; nbh = ioa_network_buffer_allocate(server->e); stun_init_indication_str(STUN_METHOD_DATA, ioa_network_buffer_data(nbh), &len); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_DATA, ioa_network_buffer_data(in_buffer->nbh), (size_t)ilen); stun_attr_add_addr_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, &(in_buffer->src_addr)); ioa_network_buffer_set_size(nbh,len); { const uint8_t *field = (const uint8_t *) get_version(server); size_t fsz = strlen(get_version(server)); size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, STUN_ATTRIBUTE_SOFTWARE, field, fsz); ioa_network_buffer_set_size(nbh, len); } if ((server->fingerprint) || ss->enforce_fingerprints) { size_t len = ioa_network_buffer_get_size(nbh); stun_attr_add_fingerprint_str(ioa_network_buffer_data(nbh), &len); ioa_network_buffer_set_size(nbh, len); } } if (eve(server->verbose)) { uint16_t* t = (uint16_t*) ioa_network_buffer_data(nbh); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Send data: 0x%x\n", (int) (nswap16(t[0]))); } write_client_connection(server, ss, nbh, in_buffer->recv_ttl-1, in_buffer->recv_tos); } } } static void client_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *data, void *arg, int can_resume) { if (!arg) return; UNUSED_ARG(s); UNUSED_ARG(event_type); ts_ur_super_session* ss = (ts_ur_super_session*)arg; turn_turnserver *server = (turn_turnserver*)ss->server; if (!server) { return; } if (ss->client_socket != s) { return; } read_client_connection(server, ss, data, can_resume, 1); if (ss->to_be_closed) { if(server->verbose) { TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "session %018llu: client socket to be closed in client handler: ss=0x%lx\n", (unsigned long long)(ss->id), (long)ss); } set_ioa_socket_tobeclosed(s); } } /////////////////////////////////////////////////////////// void init_turn_server(turn_turnserver* server, turnserver_id id, int verbose, ioa_engine_handle e, turn_credential_type ct, int stun_port, int fingerprint, dont_fragment_option_t dont_fragment, get_user_key_cb userkeycb, check_new_allocation_quota_cb chquotacb, release_allocation_quota_cb raqcb, ioa_addr *external_ip, vintp check_origin, vintp no_tcp_relay, vintp no_udp_relay, vintp stale_nonce, vintp max_allocate_lifetime, vintp channel_lifetime, vintp permission_lifetime, vintp stun_only, vintp no_stun, vintp no_software_attribute, vintp web_admin_listen_on_workers, turn_server_addrs_list_t *alternate_servers_list, turn_server_addrs_list_t *tls_alternate_servers_list, turn_server_addrs_list_t *aux_servers_list, int self_udp_balance, vintp no_multicast_peers, vintp allow_loopback_peers, ip_range_list_t* ip_whitelist, ip_range_list_t* ip_blacklist, send_socket_to_relay_cb send_socket_to_relay, vintp secure_stun, vintp mobility, int server_relay, send_turn_session_info_cb send_turn_session_info, send_https_socket_cb send_https_socket, allocate_bps_cb allocate_bps_func, int oauth, const char* oauth_server_name, const char* acme_redirect, int keep_address_family, vintp log_binding) { if (!server) return; bzero(server,sizeof(turn_turnserver)); server->e = e; server->id = id; server->ctime = turn_time(); server->session_id_counter = 0; server->sessions_map = ur_map_create(); server->tcp_relay_connections = ur_map_create(); server->ct = ct; server->userkeycb = userkeycb; server->chquotacb = chquotacb; server->raqcb = raqcb; server->no_multicast_peers = no_multicast_peers; server->allow_loopback_peers = allow_loopback_peers; server->secure_stun = secure_stun; server->mobility = mobility; server->server_relay = server_relay; server->send_turn_session_info = send_turn_session_info; server->send_https_socket = send_https_socket; server->oauth = oauth; if(oauth) server->oauth_server_name = oauth_server_name; if(mobility) server->mobile_connections_map = ur_map_create(); server->acme_redirect = acme_redirect; TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"turn server id=%d created\n",(int)id); server->check_origin = check_origin; server->no_tcp_relay = no_tcp_relay; server->no_udp_relay = no_udp_relay; server->alternate_servers_list = alternate_servers_list; server->tls_alternate_servers_list = tls_alternate_servers_list; server->aux_servers_list = aux_servers_list; server->self_udp_balance = self_udp_balance; server->stale_nonce = stale_nonce; server->max_allocate_lifetime = max_allocate_lifetime; server->channel_lifetime = channel_lifetime; server->permission_lifetime = permission_lifetime; server->stun_only = stun_only; server->no_stun = no_stun; server->no_software_attribute = no_software_attribute; server-> web_admin_listen_on_workers = web_admin_listen_on_workers; server->dont_fragment = dont_fragment; server->fingerprint = fingerprint; if(external_ip) { addr_cpy(&(server->external_ip), external_ip); server->external_ip_set = 1; } if (stun_port < 1) stun_port = DEFAULT_STUN_PORT; server->verbose = verbose; server->ip_whitelist = ip_whitelist; server->ip_blacklist = ip_blacklist; server->send_socket_to_relay = send_socket_to_relay; server->allocate_bps_func = allocate_bps_func; server->keep_address_family = keep_address_family; set_ioa_timer(server->e, 1, 0, timer_timeout_handler, server, 1, "timer_timeout_handler"); server->log_binding = log_binding; } ioa_engine_handle turn_server_get_engine(turn_turnserver *s) { if(s) return s->e; return NULL; } void set_disconnect_cb(turn_turnserver* server, int(*disconnect)( ts_ur_super_session*)) { server->disconnect = disconnect; } //////////////////////////////////////////////////////////////////
./CrossVul/dataset_final_sorted/CWE-441/c/bad_4375_2
crossvul-cpp_data_bad_3336_0
/* * Server-side XDR for NFSv4 * * Copyright (c) 2002 The Regents of the University of Michigan. * All rights reserved. * * Kendrick Smith <kmsmith@umich.edu> * Andy Adamson <andros@umich.edu> * * 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 ``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 <linux/fs_struct.h> #include <linux/file.h> #include <linux/slab.h> #include <linux/namei.h> #include <linux/statfs.h> #include <linux/utsname.h> #include <linux/pagemap.h> #include <linux/sunrpc/svcauth_gss.h> #include "idmap.h" #include "acl.h" #include "xdr4.h" #include "vfs.h" #include "state.h" #include "cache.h" #include "netns.h" #include "pnfs.h" #ifdef CONFIG_NFSD_V4_SECURITY_LABEL #include <linux/security.h> #endif #define NFSDDBG_FACILITY NFSDDBG_XDR const u32 nfsd_suppattrs[3][3] = { {NFSD4_SUPPORTED_ATTRS_WORD0, NFSD4_SUPPORTED_ATTRS_WORD1, NFSD4_SUPPORTED_ATTRS_WORD2}, {NFSD4_1_SUPPORTED_ATTRS_WORD0, NFSD4_1_SUPPORTED_ATTRS_WORD1, NFSD4_1_SUPPORTED_ATTRS_WORD2}, {NFSD4_1_SUPPORTED_ATTRS_WORD0, NFSD4_1_SUPPORTED_ATTRS_WORD1, NFSD4_2_SUPPORTED_ATTRS_WORD2}, }; /* * As per referral draft, the fsid for a referral MUST be different from the fsid of the containing * directory in order to indicate to the client that a filesystem boundary is present * We use a fixed fsid for a referral */ #define NFS4_REFERRAL_FSID_MAJOR 0x8000000ULL #define NFS4_REFERRAL_FSID_MINOR 0x8000000ULL static __be32 check_filename(char *str, int len) { int i; if (len == 0) return nfserr_inval; if (isdotent(str, len)) return nfserr_badname; for (i = 0; i < len; i++) if (str[i] == '/') return nfserr_badname; return 0; } #define DECODE_HEAD \ __be32 *p; \ __be32 status #define DECODE_TAIL \ status = 0; \ out: \ return status; \ xdr_error: \ dprintk("NFSD: xdr error (%s:%d)\n", \ __FILE__, __LINE__); \ status = nfserr_bad_xdr; \ goto out #define READMEM(x,nbytes) do { \ x = (char *)p; \ p += XDR_QUADLEN(nbytes); \ } while (0) #define SAVEMEM(x,nbytes) do { \ if (!(x = (p==argp->tmp || p == argp->tmpp) ? \ savemem(argp, p, nbytes) : \ (char *)p)) { \ dprintk("NFSD: xdr error (%s:%d)\n", \ __FILE__, __LINE__); \ goto xdr_error; \ } \ p += XDR_QUADLEN(nbytes); \ } while (0) #define COPYMEM(x,nbytes) do { \ memcpy((x), p, nbytes); \ p += XDR_QUADLEN(nbytes); \ } while (0) /* READ_BUF, read_buf(): nbytes must be <= PAGE_SIZE */ #define READ_BUF(nbytes) do { \ if (nbytes <= (u32)((char *)argp->end - (char *)argp->p)) { \ p = argp->p; \ argp->p += XDR_QUADLEN(nbytes); \ } else if (!(p = read_buf(argp, nbytes))) { \ dprintk("NFSD: xdr error (%s:%d)\n", \ __FILE__, __LINE__); \ goto xdr_error; \ } \ } while (0) static void next_decode_page(struct nfsd4_compoundargs *argp) { argp->p = page_address(argp->pagelist[0]); argp->pagelist++; if (argp->pagelen < PAGE_SIZE) { argp->end = argp->p + (argp->pagelen>>2); argp->pagelen = 0; } else { argp->end = argp->p + (PAGE_SIZE>>2); argp->pagelen -= PAGE_SIZE; } } static __be32 *read_buf(struct nfsd4_compoundargs *argp, u32 nbytes) { /* We want more bytes than seem to be available. * Maybe we need a new page, maybe we have just run out */ unsigned int avail = (char *)argp->end - (char *)argp->p; __be32 *p; if (avail + argp->pagelen < nbytes) return NULL; if (avail + PAGE_SIZE < nbytes) /* need more than a page !! */ return NULL; /* ok, we can do it with the current plus the next page */ if (nbytes <= sizeof(argp->tmp)) p = argp->tmp; else { kfree(argp->tmpp); p = argp->tmpp = kmalloc(nbytes, GFP_KERNEL); if (!p) return NULL; } /* * The following memcpy is safe because read_buf is always * called with nbytes > avail, and the two cases above both * guarantee p points to at least nbytes bytes. */ memcpy(p, argp->p, avail); next_decode_page(argp); memcpy(((char*)p)+avail, argp->p, (nbytes - avail)); argp->p += XDR_QUADLEN(nbytes - avail); return p; } static int zero_clientid(clientid_t *clid) { return (clid->cl_boot == 0) && (clid->cl_id == 0); } /** * svcxdr_tmpalloc - allocate memory to be freed after compound processing * @argp: NFSv4 compound argument structure * @p: pointer to be freed (with kfree()) * * Marks @p to be freed when processing the compound operation * described in @argp finishes. */ static void * svcxdr_tmpalloc(struct nfsd4_compoundargs *argp, u32 len) { struct svcxdr_tmpbuf *tb; tb = kmalloc(sizeof(*tb) + len, GFP_KERNEL); if (!tb) return NULL; tb->next = argp->to_free; argp->to_free = tb; return tb->buf; } /* * For xdr strings that need to be passed to other kernel api's * as null-terminated strings. * * Note null-terminating in place usually isn't safe since the * buffer might end on a page boundary. */ static char * svcxdr_dupstr(struct nfsd4_compoundargs *argp, void *buf, u32 len) { char *p = svcxdr_tmpalloc(argp, len + 1); if (!p) return NULL; memcpy(p, buf, len); p[len] = '\0'; return p; } /** * savemem - duplicate a chunk of memory for later processing * @argp: NFSv4 compound argument structure to be freed with * @p: pointer to be duplicated * @nbytes: length to be duplicated * * Returns a pointer to a copy of @nbytes bytes of memory at @p * that are preserved until processing of the NFSv4 compound * operation described by @argp finishes. */ static char *savemem(struct nfsd4_compoundargs *argp, __be32 *p, int nbytes) { void *ret; ret = svcxdr_tmpalloc(argp, nbytes); if (!ret) return NULL; memcpy(ret, p, nbytes); return ret; } /* * We require the high 32 bits of 'seconds' to be 0, and * we ignore all 32 bits of 'nseconds'. */ static __be32 nfsd4_decode_time(struct nfsd4_compoundargs *argp, struct timespec *tv) { DECODE_HEAD; u64 sec; READ_BUF(12); p = xdr_decode_hyper(p, &sec); tv->tv_sec = sec; tv->tv_nsec = be32_to_cpup(p++); if (tv->tv_nsec >= (u32)1000000000) return nfserr_inval; DECODE_TAIL; } static __be32 nfsd4_decode_bitmap(struct nfsd4_compoundargs *argp, u32 *bmval) { u32 bmlen; DECODE_HEAD; bmval[0] = 0; bmval[1] = 0; bmval[2] = 0; READ_BUF(4); bmlen = be32_to_cpup(p++); if (bmlen > 1000) goto xdr_error; READ_BUF(bmlen << 2); if (bmlen > 0) bmval[0] = be32_to_cpup(p++); if (bmlen > 1) bmval[1] = be32_to_cpup(p++); if (bmlen > 2) bmval[2] = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_fattr(struct nfsd4_compoundargs *argp, u32 *bmval, struct iattr *iattr, struct nfs4_acl **acl, struct xdr_netobj *label, int *umask) { int expected_len, len = 0; u32 dummy32; char *buf; DECODE_HEAD; iattr->ia_valid = 0; if ((status = nfsd4_decode_bitmap(argp, bmval))) return status; if (bmval[0] & ~NFSD_WRITEABLE_ATTRS_WORD0 || bmval[1] & ~NFSD_WRITEABLE_ATTRS_WORD1 || bmval[2] & ~NFSD_WRITEABLE_ATTRS_WORD2) { if (nfsd_attrs_supported(argp->minorversion, bmval)) return nfserr_inval; return nfserr_attrnotsupp; } READ_BUF(4); expected_len = be32_to_cpup(p++); if (bmval[0] & FATTR4_WORD0_SIZE) { READ_BUF(8); len += 8; p = xdr_decode_hyper(p, &iattr->ia_size); iattr->ia_valid |= ATTR_SIZE; } if (bmval[0] & FATTR4_WORD0_ACL) { u32 nace; struct nfs4_ace *ace; READ_BUF(4); len += 4; nace = be32_to_cpup(p++); if (nace > NFS4_ACL_MAX) return nfserr_fbig; *acl = svcxdr_tmpalloc(argp, nfs4_acl_bytes(nace)); if (*acl == NULL) return nfserr_jukebox; (*acl)->naces = nace; for (ace = (*acl)->aces; ace < (*acl)->aces + nace; ace++) { READ_BUF(16); len += 16; ace->type = be32_to_cpup(p++); ace->flag = be32_to_cpup(p++); ace->access_mask = be32_to_cpup(p++); dummy32 = be32_to_cpup(p++); READ_BUF(dummy32); len += XDR_QUADLEN(dummy32) << 2; READMEM(buf, dummy32); ace->whotype = nfs4_acl_get_whotype(buf, dummy32); status = nfs_ok; if (ace->whotype != NFS4_ACL_WHO_NAMED) ; else if (ace->flag & NFS4_ACE_IDENTIFIER_GROUP) status = nfsd_map_name_to_gid(argp->rqstp, buf, dummy32, &ace->who_gid); else status = nfsd_map_name_to_uid(argp->rqstp, buf, dummy32, &ace->who_uid); if (status) return status; } } else *acl = NULL; if (bmval[1] & FATTR4_WORD1_MODE) { READ_BUF(4); len += 4; iattr->ia_mode = be32_to_cpup(p++); iattr->ia_mode &= (S_IFMT | S_IALLUGO); iattr->ia_valid |= ATTR_MODE; } if (bmval[1] & FATTR4_WORD1_OWNER) { READ_BUF(4); len += 4; dummy32 = be32_to_cpup(p++); READ_BUF(dummy32); len += (XDR_QUADLEN(dummy32) << 2); READMEM(buf, dummy32); if ((status = nfsd_map_name_to_uid(argp->rqstp, buf, dummy32, &iattr->ia_uid))) return status; iattr->ia_valid |= ATTR_UID; } if (bmval[1] & FATTR4_WORD1_OWNER_GROUP) { READ_BUF(4); len += 4; dummy32 = be32_to_cpup(p++); READ_BUF(dummy32); len += (XDR_QUADLEN(dummy32) << 2); READMEM(buf, dummy32); if ((status = nfsd_map_name_to_gid(argp->rqstp, buf, dummy32, &iattr->ia_gid))) return status; iattr->ia_valid |= ATTR_GID; } if (bmval[1] & FATTR4_WORD1_TIME_ACCESS_SET) { READ_BUF(4); len += 4; dummy32 = be32_to_cpup(p++); switch (dummy32) { case NFS4_SET_TO_CLIENT_TIME: len += 12; status = nfsd4_decode_time(argp, &iattr->ia_atime); if (status) return status; iattr->ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET); break; case NFS4_SET_TO_SERVER_TIME: iattr->ia_valid |= ATTR_ATIME; break; default: goto xdr_error; } } if (bmval[1] & FATTR4_WORD1_TIME_MODIFY_SET) { READ_BUF(4); len += 4; dummy32 = be32_to_cpup(p++); switch (dummy32) { case NFS4_SET_TO_CLIENT_TIME: len += 12; status = nfsd4_decode_time(argp, &iattr->ia_mtime); if (status) return status; iattr->ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET); break; case NFS4_SET_TO_SERVER_TIME: iattr->ia_valid |= ATTR_MTIME; break; default: goto xdr_error; } } label->len = 0; #ifdef CONFIG_NFSD_V4_SECURITY_LABEL if (bmval[2] & FATTR4_WORD2_SECURITY_LABEL) { READ_BUF(4); len += 4; dummy32 = be32_to_cpup(p++); /* lfs: we don't use it */ READ_BUF(4); len += 4; dummy32 = be32_to_cpup(p++); /* pi: we don't use it either */ READ_BUF(4); len += 4; dummy32 = be32_to_cpup(p++); READ_BUF(dummy32); if (dummy32 > NFS4_MAXLABELLEN) return nfserr_badlabel; len += (XDR_QUADLEN(dummy32) << 2); READMEM(buf, dummy32); label->len = dummy32; label->data = svcxdr_dupstr(argp, buf, dummy32); if (!label->data) return nfserr_jukebox; } #endif if (bmval[2] & FATTR4_WORD2_MODE_UMASK) { if (!umask) goto xdr_error; READ_BUF(8); len += 8; dummy32 = be32_to_cpup(p++); iattr->ia_mode = dummy32 & (S_IFMT | S_IALLUGO); dummy32 = be32_to_cpup(p++); *umask = dummy32 & S_IRWXUGO; iattr->ia_valid |= ATTR_MODE; } if (len != expected_len) goto xdr_error; DECODE_TAIL; } static __be32 nfsd4_decode_stateid(struct nfsd4_compoundargs *argp, stateid_t *sid) { DECODE_HEAD; READ_BUF(sizeof(stateid_t)); sid->si_generation = be32_to_cpup(p++); COPYMEM(&sid->si_opaque, sizeof(stateid_opaque_t)); DECODE_TAIL; } static __be32 nfsd4_decode_access(struct nfsd4_compoundargs *argp, struct nfsd4_access *access) { DECODE_HEAD; READ_BUF(4); access->ac_req_access = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_cb_sec(struct nfsd4_compoundargs *argp, struct nfsd4_cb_sec *cbs) { DECODE_HEAD; u32 dummy, uid, gid; char *machine_name; int i; int nr_secflavs; /* callback_sec_params4 */ READ_BUF(4); nr_secflavs = be32_to_cpup(p++); if (nr_secflavs) cbs->flavor = (u32)(-1); else /* Is this legal? Be generous, take it to mean AUTH_NONE: */ cbs->flavor = 0; for (i = 0; i < nr_secflavs; ++i) { READ_BUF(4); dummy = be32_to_cpup(p++); switch (dummy) { case RPC_AUTH_NULL: /* Nothing to read */ if (cbs->flavor == (u32)(-1)) cbs->flavor = RPC_AUTH_NULL; break; case RPC_AUTH_UNIX: READ_BUF(8); /* stamp */ dummy = be32_to_cpup(p++); /* machine name */ dummy = be32_to_cpup(p++); READ_BUF(dummy); SAVEMEM(machine_name, dummy); /* uid, gid */ READ_BUF(8); uid = be32_to_cpup(p++); gid = be32_to_cpup(p++); /* more gids */ READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy * 4); if (cbs->flavor == (u32)(-1)) { kuid_t kuid = make_kuid(&init_user_ns, uid); kgid_t kgid = make_kgid(&init_user_ns, gid); if (uid_valid(kuid) && gid_valid(kgid)) { cbs->uid = kuid; cbs->gid = kgid; cbs->flavor = RPC_AUTH_UNIX; } else { dprintk("RPC_AUTH_UNIX with invalid" "uid or gid ignoring!\n"); } } break; case RPC_AUTH_GSS: dprintk("RPC_AUTH_GSS callback secflavor " "not supported!\n"); READ_BUF(8); /* gcbp_service */ dummy = be32_to_cpup(p++); /* gcbp_handle_from_server */ dummy = be32_to_cpup(p++); READ_BUF(dummy); p += XDR_QUADLEN(dummy); /* gcbp_handle_from_client */ READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy); break; default: dprintk("Illegal callback secflavor\n"); return nfserr_inval; } } DECODE_TAIL; } static __be32 nfsd4_decode_backchannel_ctl(struct nfsd4_compoundargs *argp, struct nfsd4_backchannel_ctl *bc) { DECODE_HEAD; READ_BUF(4); bc->bc_cb_program = be32_to_cpup(p++); nfsd4_decode_cb_sec(argp, &bc->bc_cb_sec); DECODE_TAIL; } static __be32 nfsd4_decode_bind_conn_to_session(struct nfsd4_compoundargs *argp, struct nfsd4_bind_conn_to_session *bcts) { DECODE_HEAD; READ_BUF(NFS4_MAX_SESSIONID_LEN + 8); COPYMEM(bcts->sessionid.data, NFS4_MAX_SESSIONID_LEN); bcts->dir = be32_to_cpup(p++); /* XXX: skipping ctsa_use_conn_in_rdma_mode. Perhaps Tom Tucker * could help us figure out we should be using it. */ DECODE_TAIL; } static __be32 nfsd4_decode_close(struct nfsd4_compoundargs *argp, struct nfsd4_close *close) { DECODE_HEAD; READ_BUF(4); close->cl_seqid = be32_to_cpup(p++); return nfsd4_decode_stateid(argp, &close->cl_stateid); DECODE_TAIL; } static __be32 nfsd4_decode_commit(struct nfsd4_compoundargs *argp, struct nfsd4_commit *commit) { DECODE_HEAD; READ_BUF(12); p = xdr_decode_hyper(p, &commit->co_offset); commit->co_count = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_create(struct nfsd4_compoundargs *argp, struct nfsd4_create *create) { DECODE_HEAD; READ_BUF(4); create->cr_type = be32_to_cpup(p++); switch (create->cr_type) { case NF4LNK: READ_BUF(4); create->cr_datalen = be32_to_cpup(p++); READ_BUF(create->cr_datalen); create->cr_data = svcxdr_dupstr(argp, p, create->cr_datalen); if (!create->cr_data) return nfserr_jukebox; break; case NF4BLK: case NF4CHR: READ_BUF(8); create->cr_specdata1 = be32_to_cpup(p++); create->cr_specdata2 = be32_to_cpup(p++); break; case NF4SOCK: case NF4FIFO: case NF4DIR: default: break; } READ_BUF(4); create->cr_namelen = be32_to_cpup(p++); READ_BUF(create->cr_namelen); SAVEMEM(create->cr_name, create->cr_namelen); if ((status = check_filename(create->cr_name, create->cr_namelen))) return status; status = nfsd4_decode_fattr(argp, create->cr_bmval, &create->cr_iattr, &create->cr_acl, &create->cr_label, &current->fs->umask); if (status) goto out; DECODE_TAIL; } static inline __be32 nfsd4_decode_delegreturn(struct nfsd4_compoundargs *argp, struct nfsd4_delegreturn *dr) { return nfsd4_decode_stateid(argp, &dr->dr_stateid); } static inline __be32 nfsd4_decode_getattr(struct nfsd4_compoundargs *argp, struct nfsd4_getattr *getattr) { return nfsd4_decode_bitmap(argp, getattr->ga_bmval); } static __be32 nfsd4_decode_link(struct nfsd4_compoundargs *argp, struct nfsd4_link *link) { DECODE_HEAD; READ_BUF(4); link->li_namelen = be32_to_cpup(p++); READ_BUF(link->li_namelen); SAVEMEM(link->li_name, link->li_namelen); if ((status = check_filename(link->li_name, link->li_namelen))) return status; DECODE_TAIL; } static __be32 nfsd4_decode_lock(struct nfsd4_compoundargs *argp, struct nfsd4_lock *lock) { DECODE_HEAD; /* * type, reclaim(boolean), offset, length, new_lock_owner(boolean) */ READ_BUF(28); lock->lk_type = be32_to_cpup(p++); if ((lock->lk_type < NFS4_READ_LT) || (lock->lk_type > NFS4_WRITEW_LT)) goto xdr_error; lock->lk_reclaim = be32_to_cpup(p++); p = xdr_decode_hyper(p, &lock->lk_offset); p = xdr_decode_hyper(p, &lock->lk_length); lock->lk_is_new = be32_to_cpup(p++); if (lock->lk_is_new) { READ_BUF(4); lock->lk_new_open_seqid = be32_to_cpup(p++); status = nfsd4_decode_stateid(argp, &lock->lk_new_open_stateid); if (status) return status; READ_BUF(8 + sizeof(clientid_t)); lock->lk_new_lock_seqid = be32_to_cpup(p++); COPYMEM(&lock->lk_new_clientid, sizeof(clientid_t)); lock->lk_new_owner.len = be32_to_cpup(p++); READ_BUF(lock->lk_new_owner.len); READMEM(lock->lk_new_owner.data, lock->lk_new_owner.len); } else { status = nfsd4_decode_stateid(argp, &lock->lk_old_lock_stateid); if (status) return status; READ_BUF(4); lock->lk_old_lock_seqid = be32_to_cpup(p++); } DECODE_TAIL; } static __be32 nfsd4_decode_lockt(struct nfsd4_compoundargs *argp, struct nfsd4_lockt *lockt) { DECODE_HEAD; READ_BUF(32); lockt->lt_type = be32_to_cpup(p++); if((lockt->lt_type < NFS4_READ_LT) || (lockt->lt_type > NFS4_WRITEW_LT)) goto xdr_error; p = xdr_decode_hyper(p, &lockt->lt_offset); p = xdr_decode_hyper(p, &lockt->lt_length); COPYMEM(&lockt->lt_clientid, 8); lockt->lt_owner.len = be32_to_cpup(p++); READ_BUF(lockt->lt_owner.len); READMEM(lockt->lt_owner.data, lockt->lt_owner.len); DECODE_TAIL; } static __be32 nfsd4_decode_locku(struct nfsd4_compoundargs *argp, struct nfsd4_locku *locku) { DECODE_HEAD; READ_BUF(8); locku->lu_type = be32_to_cpup(p++); if ((locku->lu_type < NFS4_READ_LT) || (locku->lu_type > NFS4_WRITEW_LT)) goto xdr_error; locku->lu_seqid = be32_to_cpup(p++); status = nfsd4_decode_stateid(argp, &locku->lu_stateid); if (status) return status; READ_BUF(16); p = xdr_decode_hyper(p, &locku->lu_offset); p = xdr_decode_hyper(p, &locku->lu_length); DECODE_TAIL; } static __be32 nfsd4_decode_lookup(struct nfsd4_compoundargs *argp, struct nfsd4_lookup *lookup) { DECODE_HEAD; READ_BUF(4); lookup->lo_len = be32_to_cpup(p++); READ_BUF(lookup->lo_len); SAVEMEM(lookup->lo_name, lookup->lo_len); if ((status = check_filename(lookup->lo_name, lookup->lo_len))) return status; DECODE_TAIL; } static __be32 nfsd4_decode_share_access(struct nfsd4_compoundargs *argp, u32 *share_access, u32 *deleg_want, u32 *deleg_when) { __be32 *p; u32 w; READ_BUF(4); w = be32_to_cpup(p++); *share_access = w & NFS4_SHARE_ACCESS_MASK; *deleg_want = w & NFS4_SHARE_WANT_MASK; if (deleg_when) *deleg_when = w & NFS4_SHARE_WHEN_MASK; switch (w & NFS4_SHARE_ACCESS_MASK) { case NFS4_SHARE_ACCESS_READ: case NFS4_SHARE_ACCESS_WRITE: case NFS4_SHARE_ACCESS_BOTH: break; default: return nfserr_bad_xdr; } w &= ~NFS4_SHARE_ACCESS_MASK; if (!w) return nfs_ok; if (!argp->minorversion) return nfserr_bad_xdr; switch (w & NFS4_SHARE_WANT_MASK) { case NFS4_SHARE_WANT_NO_PREFERENCE: case NFS4_SHARE_WANT_READ_DELEG: case NFS4_SHARE_WANT_WRITE_DELEG: case NFS4_SHARE_WANT_ANY_DELEG: case NFS4_SHARE_WANT_NO_DELEG: case NFS4_SHARE_WANT_CANCEL: break; default: return nfserr_bad_xdr; } w &= ~NFS4_SHARE_WANT_MASK; if (!w) return nfs_ok; if (!deleg_when) /* open_downgrade */ return nfserr_inval; switch (w) { case NFS4_SHARE_SIGNAL_DELEG_WHEN_RESRC_AVAIL: case NFS4_SHARE_PUSH_DELEG_WHEN_UNCONTENDED: case (NFS4_SHARE_SIGNAL_DELEG_WHEN_RESRC_AVAIL | NFS4_SHARE_PUSH_DELEG_WHEN_UNCONTENDED): return nfs_ok; } xdr_error: return nfserr_bad_xdr; } static __be32 nfsd4_decode_share_deny(struct nfsd4_compoundargs *argp, u32 *x) { __be32 *p; READ_BUF(4); *x = be32_to_cpup(p++); /* Note: unlinke access bits, deny bits may be zero. */ if (*x & ~NFS4_SHARE_DENY_BOTH) return nfserr_bad_xdr; return nfs_ok; xdr_error: return nfserr_bad_xdr; } static __be32 nfsd4_decode_opaque(struct nfsd4_compoundargs *argp, struct xdr_netobj *o) { __be32 *p; READ_BUF(4); o->len = be32_to_cpup(p++); if (o->len == 0 || o->len > NFS4_OPAQUE_LIMIT) return nfserr_bad_xdr; READ_BUF(o->len); SAVEMEM(o->data, o->len); return nfs_ok; xdr_error: return nfserr_bad_xdr; } static __be32 nfsd4_decode_open(struct nfsd4_compoundargs *argp, struct nfsd4_open *open) { DECODE_HEAD; u32 dummy; memset(open->op_bmval, 0, sizeof(open->op_bmval)); open->op_iattr.ia_valid = 0; open->op_openowner = NULL; open->op_xdr_error = 0; /* seqid, share_access, share_deny, clientid, ownerlen */ READ_BUF(4); open->op_seqid = be32_to_cpup(p++); /* decode, yet ignore deleg_when until supported */ status = nfsd4_decode_share_access(argp, &open->op_share_access, &open->op_deleg_want, &dummy); if (status) goto xdr_error; status = nfsd4_decode_share_deny(argp, &open->op_share_deny); if (status) goto xdr_error; READ_BUF(sizeof(clientid_t)); COPYMEM(&open->op_clientid, sizeof(clientid_t)); status = nfsd4_decode_opaque(argp, &open->op_owner); if (status) goto xdr_error; READ_BUF(4); open->op_create = be32_to_cpup(p++); switch (open->op_create) { case NFS4_OPEN_NOCREATE: break; case NFS4_OPEN_CREATE: current->fs->umask = 0; READ_BUF(4); open->op_createmode = be32_to_cpup(p++); switch (open->op_createmode) { case NFS4_CREATE_UNCHECKED: case NFS4_CREATE_GUARDED: status = nfsd4_decode_fattr(argp, open->op_bmval, &open->op_iattr, &open->op_acl, &open->op_label, &current->fs->umask); if (status) goto out; break; case NFS4_CREATE_EXCLUSIVE: READ_BUF(NFS4_VERIFIER_SIZE); COPYMEM(open->op_verf.data, NFS4_VERIFIER_SIZE); break; case NFS4_CREATE_EXCLUSIVE4_1: if (argp->minorversion < 1) goto xdr_error; READ_BUF(NFS4_VERIFIER_SIZE); COPYMEM(open->op_verf.data, NFS4_VERIFIER_SIZE); status = nfsd4_decode_fattr(argp, open->op_bmval, &open->op_iattr, &open->op_acl, &open->op_label, &current->fs->umask); if (status) goto out; break; default: goto xdr_error; } break; default: goto xdr_error; } /* open_claim */ READ_BUF(4); open->op_claim_type = be32_to_cpup(p++); switch (open->op_claim_type) { case NFS4_OPEN_CLAIM_NULL: case NFS4_OPEN_CLAIM_DELEGATE_PREV: READ_BUF(4); open->op_fname.len = be32_to_cpup(p++); READ_BUF(open->op_fname.len); SAVEMEM(open->op_fname.data, open->op_fname.len); if ((status = check_filename(open->op_fname.data, open->op_fname.len))) return status; break; case NFS4_OPEN_CLAIM_PREVIOUS: READ_BUF(4); open->op_delegate_type = be32_to_cpup(p++); break; case NFS4_OPEN_CLAIM_DELEGATE_CUR: status = nfsd4_decode_stateid(argp, &open->op_delegate_stateid); if (status) return status; READ_BUF(4); open->op_fname.len = be32_to_cpup(p++); READ_BUF(open->op_fname.len); SAVEMEM(open->op_fname.data, open->op_fname.len); if ((status = check_filename(open->op_fname.data, open->op_fname.len))) return status; break; case NFS4_OPEN_CLAIM_FH: case NFS4_OPEN_CLAIM_DELEG_PREV_FH: if (argp->minorversion < 1) goto xdr_error; /* void */ break; case NFS4_OPEN_CLAIM_DELEG_CUR_FH: if (argp->minorversion < 1) goto xdr_error; status = nfsd4_decode_stateid(argp, &open->op_delegate_stateid); if (status) return status; break; default: goto xdr_error; } DECODE_TAIL; } static __be32 nfsd4_decode_open_confirm(struct nfsd4_compoundargs *argp, struct nfsd4_open_confirm *open_conf) { DECODE_HEAD; if (argp->minorversion >= 1) return nfserr_notsupp; status = nfsd4_decode_stateid(argp, &open_conf->oc_req_stateid); if (status) return status; READ_BUF(4); open_conf->oc_seqid = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_open_downgrade(struct nfsd4_compoundargs *argp, struct nfsd4_open_downgrade *open_down) { DECODE_HEAD; status = nfsd4_decode_stateid(argp, &open_down->od_stateid); if (status) return status; READ_BUF(4); open_down->od_seqid = be32_to_cpup(p++); status = nfsd4_decode_share_access(argp, &open_down->od_share_access, &open_down->od_deleg_want, NULL); if (status) return status; status = nfsd4_decode_share_deny(argp, &open_down->od_share_deny); if (status) return status; DECODE_TAIL; } static __be32 nfsd4_decode_putfh(struct nfsd4_compoundargs *argp, struct nfsd4_putfh *putfh) { DECODE_HEAD; READ_BUF(4); putfh->pf_fhlen = be32_to_cpup(p++); if (putfh->pf_fhlen > NFS4_FHSIZE) goto xdr_error; READ_BUF(putfh->pf_fhlen); SAVEMEM(putfh->pf_fhval, putfh->pf_fhlen); DECODE_TAIL; } static __be32 nfsd4_decode_putpubfh(struct nfsd4_compoundargs *argp, void *p) { if (argp->minorversion == 0) return nfs_ok; return nfserr_notsupp; } static __be32 nfsd4_decode_read(struct nfsd4_compoundargs *argp, struct nfsd4_read *read) { DECODE_HEAD; status = nfsd4_decode_stateid(argp, &read->rd_stateid); if (status) return status; READ_BUF(12); p = xdr_decode_hyper(p, &read->rd_offset); read->rd_length = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_readdir(struct nfsd4_compoundargs *argp, struct nfsd4_readdir *readdir) { DECODE_HEAD; READ_BUF(24); p = xdr_decode_hyper(p, &readdir->rd_cookie); COPYMEM(readdir->rd_verf.data, sizeof(readdir->rd_verf.data)); readdir->rd_dircount = be32_to_cpup(p++); readdir->rd_maxcount = be32_to_cpup(p++); if ((status = nfsd4_decode_bitmap(argp, readdir->rd_bmval))) goto out; DECODE_TAIL; } static __be32 nfsd4_decode_remove(struct nfsd4_compoundargs *argp, struct nfsd4_remove *remove) { DECODE_HEAD; READ_BUF(4); remove->rm_namelen = be32_to_cpup(p++); READ_BUF(remove->rm_namelen); SAVEMEM(remove->rm_name, remove->rm_namelen); if ((status = check_filename(remove->rm_name, remove->rm_namelen))) return status; DECODE_TAIL; } static __be32 nfsd4_decode_rename(struct nfsd4_compoundargs *argp, struct nfsd4_rename *rename) { DECODE_HEAD; READ_BUF(4); rename->rn_snamelen = be32_to_cpup(p++); READ_BUF(rename->rn_snamelen); SAVEMEM(rename->rn_sname, rename->rn_snamelen); READ_BUF(4); rename->rn_tnamelen = be32_to_cpup(p++); READ_BUF(rename->rn_tnamelen); SAVEMEM(rename->rn_tname, rename->rn_tnamelen); if ((status = check_filename(rename->rn_sname, rename->rn_snamelen))) return status; if ((status = check_filename(rename->rn_tname, rename->rn_tnamelen))) return status; DECODE_TAIL; } static __be32 nfsd4_decode_renew(struct nfsd4_compoundargs *argp, clientid_t *clientid) { DECODE_HEAD; if (argp->minorversion >= 1) return nfserr_notsupp; READ_BUF(sizeof(clientid_t)); COPYMEM(clientid, sizeof(clientid_t)); DECODE_TAIL; } static __be32 nfsd4_decode_secinfo(struct nfsd4_compoundargs *argp, struct nfsd4_secinfo *secinfo) { DECODE_HEAD; READ_BUF(4); secinfo->si_namelen = be32_to_cpup(p++); READ_BUF(secinfo->si_namelen); SAVEMEM(secinfo->si_name, secinfo->si_namelen); status = check_filename(secinfo->si_name, secinfo->si_namelen); if (status) return status; DECODE_TAIL; } static __be32 nfsd4_decode_secinfo_no_name(struct nfsd4_compoundargs *argp, struct nfsd4_secinfo_no_name *sin) { DECODE_HEAD; READ_BUF(4); sin->sin_style = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_setattr(struct nfsd4_compoundargs *argp, struct nfsd4_setattr *setattr) { __be32 status; status = nfsd4_decode_stateid(argp, &setattr->sa_stateid); if (status) return status; return nfsd4_decode_fattr(argp, setattr->sa_bmval, &setattr->sa_iattr, &setattr->sa_acl, &setattr->sa_label, NULL); } static __be32 nfsd4_decode_setclientid(struct nfsd4_compoundargs *argp, struct nfsd4_setclientid *setclientid) { DECODE_HEAD; if (argp->minorversion >= 1) return nfserr_notsupp; READ_BUF(NFS4_VERIFIER_SIZE); COPYMEM(setclientid->se_verf.data, NFS4_VERIFIER_SIZE); status = nfsd4_decode_opaque(argp, &setclientid->se_name); if (status) return nfserr_bad_xdr; READ_BUF(8); setclientid->se_callback_prog = be32_to_cpup(p++); setclientid->se_callback_netid_len = be32_to_cpup(p++); READ_BUF(setclientid->se_callback_netid_len); SAVEMEM(setclientid->se_callback_netid_val, setclientid->se_callback_netid_len); READ_BUF(4); setclientid->se_callback_addr_len = be32_to_cpup(p++); READ_BUF(setclientid->se_callback_addr_len); SAVEMEM(setclientid->se_callback_addr_val, setclientid->se_callback_addr_len); READ_BUF(4); setclientid->se_callback_ident = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_setclientid_confirm(struct nfsd4_compoundargs *argp, struct nfsd4_setclientid_confirm *scd_c) { DECODE_HEAD; if (argp->minorversion >= 1) return nfserr_notsupp; READ_BUF(8 + NFS4_VERIFIER_SIZE); COPYMEM(&scd_c->sc_clientid, 8); COPYMEM(&scd_c->sc_confirm, NFS4_VERIFIER_SIZE); DECODE_TAIL; } /* Also used for NVERIFY */ static __be32 nfsd4_decode_verify(struct nfsd4_compoundargs *argp, struct nfsd4_verify *verify) { DECODE_HEAD; if ((status = nfsd4_decode_bitmap(argp, verify->ve_bmval))) goto out; /* For convenience's sake, we compare raw xdr'd attributes in * nfsd4_proc_verify */ READ_BUF(4); verify->ve_attrlen = be32_to_cpup(p++); READ_BUF(verify->ve_attrlen); SAVEMEM(verify->ve_attrval, verify->ve_attrlen); DECODE_TAIL; } static __be32 nfsd4_decode_write(struct nfsd4_compoundargs *argp, struct nfsd4_write *write) { int avail; int len; DECODE_HEAD; status = nfsd4_decode_stateid(argp, &write->wr_stateid); if (status) return status; READ_BUF(16); p = xdr_decode_hyper(p, &write->wr_offset); write->wr_stable_how = be32_to_cpup(p++); if (write->wr_stable_how > NFS_FILE_SYNC) goto xdr_error; write->wr_buflen = be32_to_cpup(p++); /* Sorry .. no magic macros for this.. * * READ_BUF(write->wr_buflen); * SAVEMEM(write->wr_buf, write->wr_buflen); */ avail = (char*)argp->end - (char*)argp->p; if (avail + argp->pagelen < write->wr_buflen) { dprintk("NFSD: xdr error (%s:%d)\n", __FILE__, __LINE__); goto xdr_error; } write->wr_head.iov_base = p; write->wr_head.iov_len = avail; write->wr_pagelist = argp->pagelist; len = XDR_QUADLEN(write->wr_buflen) << 2; if (len >= avail) { int pages; len -= avail; pages = len >> PAGE_SHIFT; argp->pagelist += pages; argp->pagelen -= pages * PAGE_SIZE; len -= pages * PAGE_SIZE; argp->p = (__be32 *)page_address(argp->pagelist[0]); argp->pagelist++; argp->end = argp->p + XDR_QUADLEN(PAGE_SIZE); } argp->p += XDR_QUADLEN(len); DECODE_TAIL; } static __be32 nfsd4_decode_release_lockowner(struct nfsd4_compoundargs *argp, struct nfsd4_release_lockowner *rlockowner) { DECODE_HEAD; if (argp->minorversion >= 1) return nfserr_notsupp; READ_BUF(12); COPYMEM(&rlockowner->rl_clientid, sizeof(clientid_t)); rlockowner->rl_owner.len = be32_to_cpup(p++); READ_BUF(rlockowner->rl_owner.len); READMEM(rlockowner->rl_owner.data, rlockowner->rl_owner.len); if (argp->minorversion && !zero_clientid(&rlockowner->rl_clientid)) return nfserr_inval; DECODE_TAIL; } static __be32 nfsd4_decode_exchange_id(struct nfsd4_compoundargs *argp, struct nfsd4_exchange_id *exid) { int dummy, tmp; DECODE_HEAD; READ_BUF(NFS4_VERIFIER_SIZE); COPYMEM(exid->verifier.data, NFS4_VERIFIER_SIZE); status = nfsd4_decode_opaque(argp, &exid->clname); if (status) return nfserr_bad_xdr; READ_BUF(4); exid->flags = be32_to_cpup(p++); /* Ignore state_protect4_a */ READ_BUF(4); exid->spa_how = be32_to_cpup(p++); switch (exid->spa_how) { case SP4_NONE: break; case SP4_MACH_CRED: /* spo_must_enforce */ status = nfsd4_decode_bitmap(argp, exid->spo_must_enforce); if (status) goto out; /* spo_must_allow */ status = nfsd4_decode_bitmap(argp, exid->spo_must_allow); if (status) goto out; break; case SP4_SSV: /* ssp_ops */ READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy * 4); p += dummy; READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy * 4); p += dummy; /* ssp_hash_algs<> */ READ_BUF(4); tmp = be32_to_cpup(p++); while (tmp--) { READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy); p += XDR_QUADLEN(dummy); } /* ssp_encr_algs<> */ READ_BUF(4); tmp = be32_to_cpup(p++); while (tmp--) { READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy); p += XDR_QUADLEN(dummy); } /* ssp_window and ssp_num_gss_handles */ READ_BUF(8); dummy = be32_to_cpup(p++); dummy = be32_to_cpup(p++); break; default: goto xdr_error; } /* Ignore Implementation ID */ READ_BUF(4); /* nfs_impl_id4 array length */ dummy = be32_to_cpup(p++); if (dummy > 1) goto xdr_error; if (dummy == 1) { /* nii_domain */ READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy); p += XDR_QUADLEN(dummy); /* nii_name */ READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy); p += XDR_QUADLEN(dummy); /* nii_date */ READ_BUF(12); p += 3; } DECODE_TAIL; } static __be32 nfsd4_decode_create_session(struct nfsd4_compoundargs *argp, struct nfsd4_create_session *sess) { DECODE_HEAD; u32 dummy; READ_BUF(16); COPYMEM(&sess->clientid, 8); sess->seqid = be32_to_cpup(p++); sess->flags = be32_to_cpup(p++); /* Fore channel attrs */ READ_BUF(28); dummy = be32_to_cpup(p++); /* headerpadsz is always 0 */ sess->fore_channel.maxreq_sz = be32_to_cpup(p++); sess->fore_channel.maxresp_sz = be32_to_cpup(p++); sess->fore_channel.maxresp_cached = be32_to_cpup(p++); sess->fore_channel.maxops = be32_to_cpup(p++); sess->fore_channel.maxreqs = be32_to_cpup(p++); sess->fore_channel.nr_rdma_attrs = be32_to_cpup(p++); if (sess->fore_channel.nr_rdma_attrs == 1) { READ_BUF(4); sess->fore_channel.rdma_attrs = be32_to_cpup(p++); } else if (sess->fore_channel.nr_rdma_attrs > 1) { dprintk("Too many fore channel attr bitmaps!\n"); goto xdr_error; } /* Back channel attrs */ READ_BUF(28); dummy = be32_to_cpup(p++); /* headerpadsz is always 0 */ sess->back_channel.maxreq_sz = be32_to_cpup(p++); sess->back_channel.maxresp_sz = be32_to_cpup(p++); sess->back_channel.maxresp_cached = be32_to_cpup(p++); sess->back_channel.maxops = be32_to_cpup(p++); sess->back_channel.maxreqs = be32_to_cpup(p++); sess->back_channel.nr_rdma_attrs = be32_to_cpup(p++); if (sess->back_channel.nr_rdma_attrs == 1) { READ_BUF(4); sess->back_channel.rdma_attrs = be32_to_cpup(p++); } else if (sess->back_channel.nr_rdma_attrs > 1) { dprintk("Too many back channel attr bitmaps!\n"); goto xdr_error; } READ_BUF(4); sess->callback_prog = be32_to_cpup(p++); nfsd4_decode_cb_sec(argp, &sess->cb_sec); DECODE_TAIL; } static __be32 nfsd4_decode_destroy_session(struct nfsd4_compoundargs *argp, struct nfsd4_destroy_session *destroy_session) { DECODE_HEAD; READ_BUF(NFS4_MAX_SESSIONID_LEN); COPYMEM(destroy_session->sessionid.data, NFS4_MAX_SESSIONID_LEN); DECODE_TAIL; } static __be32 nfsd4_decode_free_stateid(struct nfsd4_compoundargs *argp, struct nfsd4_free_stateid *free_stateid) { DECODE_HEAD; READ_BUF(sizeof(stateid_t)); free_stateid->fr_stateid.si_generation = be32_to_cpup(p++); COPYMEM(&free_stateid->fr_stateid.si_opaque, sizeof(stateid_opaque_t)); DECODE_TAIL; } static __be32 nfsd4_decode_sequence(struct nfsd4_compoundargs *argp, struct nfsd4_sequence *seq) { DECODE_HEAD; READ_BUF(NFS4_MAX_SESSIONID_LEN + 16); COPYMEM(seq->sessionid.data, NFS4_MAX_SESSIONID_LEN); seq->seqid = be32_to_cpup(p++); seq->slotid = be32_to_cpup(p++); seq->maxslots = be32_to_cpup(p++); seq->cachethis = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_test_stateid(struct nfsd4_compoundargs *argp, struct nfsd4_test_stateid *test_stateid) { int i; __be32 *p, status; struct nfsd4_test_stateid_id *stateid; READ_BUF(4); test_stateid->ts_num_ids = ntohl(*p++); INIT_LIST_HEAD(&test_stateid->ts_stateid_list); for (i = 0; i < test_stateid->ts_num_ids; i++) { stateid = svcxdr_tmpalloc(argp, sizeof(*stateid)); if (!stateid) { status = nfserrno(-ENOMEM); goto out; } INIT_LIST_HEAD(&stateid->ts_id_list); list_add_tail(&stateid->ts_id_list, &test_stateid->ts_stateid_list); status = nfsd4_decode_stateid(argp, &stateid->ts_id_stateid); if (status) goto out; } status = 0; out: return status; xdr_error: dprintk("NFSD: xdr error (%s:%d)\n", __FILE__, __LINE__); status = nfserr_bad_xdr; goto out; } static __be32 nfsd4_decode_destroy_clientid(struct nfsd4_compoundargs *argp, struct nfsd4_destroy_clientid *dc) { DECODE_HEAD; READ_BUF(8); COPYMEM(&dc->clientid, 8); DECODE_TAIL; } static __be32 nfsd4_decode_reclaim_complete(struct nfsd4_compoundargs *argp, struct nfsd4_reclaim_complete *rc) { DECODE_HEAD; READ_BUF(4); rc->rca_one_fs = be32_to_cpup(p++); DECODE_TAIL; } #ifdef CONFIG_NFSD_PNFS static __be32 nfsd4_decode_getdeviceinfo(struct nfsd4_compoundargs *argp, struct nfsd4_getdeviceinfo *gdev) { DECODE_HEAD; u32 num, i; READ_BUF(sizeof(struct nfsd4_deviceid) + 3 * 4); COPYMEM(&gdev->gd_devid, sizeof(struct nfsd4_deviceid)); gdev->gd_layout_type = be32_to_cpup(p++); gdev->gd_maxcount = be32_to_cpup(p++); num = be32_to_cpup(p++); if (num) { READ_BUF(4 * num); gdev->gd_notify_types = be32_to_cpup(p++); for (i = 1; i < num; i++) { if (be32_to_cpup(p++)) { status = nfserr_inval; goto out; } } } DECODE_TAIL; } static __be32 nfsd4_decode_layoutget(struct nfsd4_compoundargs *argp, struct nfsd4_layoutget *lgp) { DECODE_HEAD; READ_BUF(36); lgp->lg_signal = be32_to_cpup(p++); lgp->lg_layout_type = be32_to_cpup(p++); lgp->lg_seg.iomode = be32_to_cpup(p++); p = xdr_decode_hyper(p, &lgp->lg_seg.offset); p = xdr_decode_hyper(p, &lgp->lg_seg.length); p = xdr_decode_hyper(p, &lgp->lg_minlength); status = nfsd4_decode_stateid(argp, &lgp->lg_sid); if (status) return status; READ_BUF(4); lgp->lg_maxcount = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_layoutcommit(struct nfsd4_compoundargs *argp, struct nfsd4_layoutcommit *lcp) { DECODE_HEAD; u32 timechange; READ_BUF(20); p = xdr_decode_hyper(p, &lcp->lc_seg.offset); p = xdr_decode_hyper(p, &lcp->lc_seg.length); lcp->lc_reclaim = be32_to_cpup(p++); status = nfsd4_decode_stateid(argp, &lcp->lc_sid); if (status) return status; READ_BUF(4); lcp->lc_newoffset = be32_to_cpup(p++); if (lcp->lc_newoffset) { READ_BUF(8); p = xdr_decode_hyper(p, &lcp->lc_last_wr); } else lcp->lc_last_wr = 0; READ_BUF(4); timechange = be32_to_cpup(p++); if (timechange) { status = nfsd4_decode_time(argp, &lcp->lc_mtime); if (status) return status; } else { lcp->lc_mtime.tv_nsec = UTIME_NOW; } READ_BUF(8); lcp->lc_layout_type = be32_to_cpup(p++); /* * Save the layout update in XDR format and let the layout driver deal * with it later. */ lcp->lc_up_len = be32_to_cpup(p++); if (lcp->lc_up_len > 0) { READ_BUF(lcp->lc_up_len); READMEM(lcp->lc_up_layout, lcp->lc_up_len); } DECODE_TAIL; } static __be32 nfsd4_decode_layoutreturn(struct nfsd4_compoundargs *argp, struct nfsd4_layoutreturn *lrp) { DECODE_HEAD; READ_BUF(16); lrp->lr_reclaim = be32_to_cpup(p++); lrp->lr_layout_type = be32_to_cpup(p++); lrp->lr_seg.iomode = be32_to_cpup(p++); lrp->lr_return_type = be32_to_cpup(p++); if (lrp->lr_return_type == RETURN_FILE) { READ_BUF(16); p = xdr_decode_hyper(p, &lrp->lr_seg.offset); p = xdr_decode_hyper(p, &lrp->lr_seg.length); status = nfsd4_decode_stateid(argp, &lrp->lr_sid); if (status) return status; READ_BUF(4); lrp->lrf_body_len = be32_to_cpup(p++); if (lrp->lrf_body_len > 0) { READ_BUF(lrp->lrf_body_len); READMEM(lrp->lrf_body, lrp->lrf_body_len); } } else { lrp->lr_seg.offset = 0; lrp->lr_seg.length = NFS4_MAX_UINT64; } DECODE_TAIL; } #endif /* CONFIG_NFSD_PNFS */ static __be32 nfsd4_decode_fallocate(struct nfsd4_compoundargs *argp, struct nfsd4_fallocate *fallocate) { DECODE_HEAD; status = nfsd4_decode_stateid(argp, &fallocate->falloc_stateid); if (status) return status; READ_BUF(16); p = xdr_decode_hyper(p, &fallocate->falloc_offset); xdr_decode_hyper(p, &fallocate->falloc_length); DECODE_TAIL; } static __be32 nfsd4_decode_clone(struct nfsd4_compoundargs *argp, struct nfsd4_clone *clone) { DECODE_HEAD; status = nfsd4_decode_stateid(argp, &clone->cl_src_stateid); if (status) return status; status = nfsd4_decode_stateid(argp, &clone->cl_dst_stateid); if (status) return status; READ_BUF(8 + 8 + 8); p = xdr_decode_hyper(p, &clone->cl_src_pos); p = xdr_decode_hyper(p, &clone->cl_dst_pos); p = xdr_decode_hyper(p, &clone->cl_count); DECODE_TAIL; } static __be32 nfsd4_decode_copy(struct nfsd4_compoundargs *argp, struct nfsd4_copy *copy) { DECODE_HEAD; unsigned int tmp; status = nfsd4_decode_stateid(argp, &copy->cp_src_stateid); if (status) return status; status = nfsd4_decode_stateid(argp, &copy->cp_dst_stateid); if (status) return status; READ_BUF(8 + 8 + 8 + 4 + 4 + 4); p = xdr_decode_hyper(p, &copy->cp_src_pos); p = xdr_decode_hyper(p, &copy->cp_dst_pos); p = xdr_decode_hyper(p, &copy->cp_count); copy->cp_consecutive = be32_to_cpup(p++); copy->cp_synchronous = be32_to_cpup(p++); tmp = be32_to_cpup(p); /* Source server list not supported */ DECODE_TAIL; } static __be32 nfsd4_decode_seek(struct nfsd4_compoundargs *argp, struct nfsd4_seek *seek) { DECODE_HEAD; status = nfsd4_decode_stateid(argp, &seek->seek_stateid); if (status) return status; READ_BUF(8 + 4); p = xdr_decode_hyper(p, &seek->seek_offset); seek->seek_whence = be32_to_cpup(p); DECODE_TAIL; } static __be32 nfsd4_decode_noop(struct nfsd4_compoundargs *argp, void *p) { return nfs_ok; } static __be32 nfsd4_decode_notsupp(struct nfsd4_compoundargs *argp, void *p) { return nfserr_notsupp; } typedef __be32(*nfsd4_dec)(struct nfsd4_compoundargs *argp, void *); static nfsd4_dec nfsd4_dec_ops[] = { [OP_ACCESS] = (nfsd4_dec)nfsd4_decode_access, [OP_CLOSE] = (nfsd4_dec)nfsd4_decode_close, [OP_COMMIT] = (nfsd4_dec)nfsd4_decode_commit, [OP_CREATE] = (nfsd4_dec)nfsd4_decode_create, [OP_DELEGPURGE] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_DELEGRETURN] = (nfsd4_dec)nfsd4_decode_delegreturn, [OP_GETATTR] = (nfsd4_dec)nfsd4_decode_getattr, [OP_GETFH] = (nfsd4_dec)nfsd4_decode_noop, [OP_LINK] = (nfsd4_dec)nfsd4_decode_link, [OP_LOCK] = (nfsd4_dec)nfsd4_decode_lock, [OP_LOCKT] = (nfsd4_dec)nfsd4_decode_lockt, [OP_LOCKU] = (nfsd4_dec)nfsd4_decode_locku, [OP_LOOKUP] = (nfsd4_dec)nfsd4_decode_lookup, [OP_LOOKUPP] = (nfsd4_dec)nfsd4_decode_noop, [OP_NVERIFY] = (nfsd4_dec)nfsd4_decode_verify, [OP_OPEN] = (nfsd4_dec)nfsd4_decode_open, [OP_OPENATTR] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_OPEN_CONFIRM] = (nfsd4_dec)nfsd4_decode_open_confirm, [OP_OPEN_DOWNGRADE] = (nfsd4_dec)nfsd4_decode_open_downgrade, [OP_PUTFH] = (nfsd4_dec)nfsd4_decode_putfh, [OP_PUTPUBFH] = (nfsd4_dec)nfsd4_decode_putpubfh, [OP_PUTROOTFH] = (nfsd4_dec)nfsd4_decode_noop, [OP_READ] = (nfsd4_dec)nfsd4_decode_read, [OP_READDIR] = (nfsd4_dec)nfsd4_decode_readdir, [OP_READLINK] = (nfsd4_dec)nfsd4_decode_noop, [OP_REMOVE] = (nfsd4_dec)nfsd4_decode_remove, [OP_RENAME] = (nfsd4_dec)nfsd4_decode_rename, [OP_RENEW] = (nfsd4_dec)nfsd4_decode_renew, [OP_RESTOREFH] = (nfsd4_dec)nfsd4_decode_noop, [OP_SAVEFH] = (nfsd4_dec)nfsd4_decode_noop, [OP_SECINFO] = (nfsd4_dec)nfsd4_decode_secinfo, [OP_SETATTR] = (nfsd4_dec)nfsd4_decode_setattr, [OP_SETCLIENTID] = (nfsd4_dec)nfsd4_decode_setclientid, [OP_SETCLIENTID_CONFIRM] = (nfsd4_dec)nfsd4_decode_setclientid_confirm, [OP_VERIFY] = (nfsd4_dec)nfsd4_decode_verify, [OP_WRITE] = (nfsd4_dec)nfsd4_decode_write, [OP_RELEASE_LOCKOWNER] = (nfsd4_dec)nfsd4_decode_release_lockowner, /* new operations for NFSv4.1 */ [OP_BACKCHANNEL_CTL] = (nfsd4_dec)nfsd4_decode_backchannel_ctl, [OP_BIND_CONN_TO_SESSION]= (nfsd4_dec)nfsd4_decode_bind_conn_to_session, [OP_EXCHANGE_ID] = (nfsd4_dec)nfsd4_decode_exchange_id, [OP_CREATE_SESSION] = (nfsd4_dec)nfsd4_decode_create_session, [OP_DESTROY_SESSION] = (nfsd4_dec)nfsd4_decode_destroy_session, [OP_FREE_STATEID] = (nfsd4_dec)nfsd4_decode_free_stateid, [OP_GET_DIR_DELEGATION] = (nfsd4_dec)nfsd4_decode_notsupp, #ifdef CONFIG_NFSD_PNFS [OP_GETDEVICEINFO] = (nfsd4_dec)nfsd4_decode_getdeviceinfo, [OP_GETDEVICELIST] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_LAYOUTCOMMIT] = (nfsd4_dec)nfsd4_decode_layoutcommit, [OP_LAYOUTGET] = (nfsd4_dec)nfsd4_decode_layoutget, [OP_LAYOUTRETURN] = (nfsd4_dec)nfsd4_decode_layoutreturn, #else [OP_GETDEVICEINFO] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_GETDEVICELIST] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_LAYOUTCOMMIT] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_LAYOUTGET] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_LAYOUTRETURN] = (nfsd4_dec)nfsd4_decode_notsupp, #endif [OP_SECINFO_NO_NAME] = (nfsd4_dec)nfsd4_decode_secinfo_no_name, [OP_SEQUENCE] = (nfsd4_dec)nfsd4_decode_sequence, [OP_SET_SSV] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_TEST_STATEID] = (nfsd4_dec)nfsd4_decode_test_stateid, [OP_WANT_DELEGATION] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_DESTROY_CLIENTID] = (nfsd4_dec)nfsd4_decode_destroy_clientid, [OP_RECLAIM_COMPLETE] = (nfsd4_dec)nfsd4_decode_reclaim_complete, /* new operations for NFSv4.2 */ [OP_ALLOCATE] = (nfsd4_dec)nfsd4_decode_fallocate, [OP_COPY] = (nfsd4_dec)nfsd4_decode_copy, [OP_COPY_NOTIFY] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_DEALLOCATE] = (nfsd4_dec)nfsd4_decode_fallocate, [OP_IO_ADVISE] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_LAYOUTERROR] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_LAYOUTSTATS] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_OFFLOAD_CANCEL] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_OFFLOAD_STATUS] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_READ_PLUS] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_SEEK] = (nfsd4_dec)nfsd4_decode_seek, [OP_WRITE_SAME] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_CLONE] = (nfsd4_dec)nfsd4_decode_clone, }; static inline bool nfsd4_opnum_in_range(struct nfsd4_compoundargs *argp, struct nfsd4_op *op) { if (op->opnum < FIRST_NFS4_OP) return false; else if (argp->minorversion == 0 && op->opnum > LAST_NFS40_OP) return false; else if (argp->minorversion == 1 && op->opnum > LAST_NFS41_OP) return false; else if (argp->minorversion == 2 && op->opnum > LAST_NFS42_OP) return false; return true; } static __be32 nfsd4_decode_compound(struct nfsd4_compoundargs *argp) { DECODE_HEAD; struct nfsd4_op *op; bool cachethis = false; int auth_slack= argp->rqstp->rq_auth_slack; int max_reply = auth_slack + 8; /* opcnt, status */ int readcount = 0; int readbytes = 0; int i; READ_BUF(4); argp->taglen = be32_to_cpup(p++); READ_BUF(argp->taglen); SAVEMEM(argp->tag, argp->taglen); READ_BUF(8); argp->minorversion = be32_to_cpup(p++); argp->opcnt = be32_to_cpup(p++); max_reply += 4 + (XDR_QUADLEN(argp->taglen) << 2); if (argp->taglen > NFSD4_MAX_TAGLEN) goto xdr_error; if (argp->opcnt > 100) goto xdr_error; if (argp->opcnt > ARRAY_SIZE(argp->iops)) { argp->ops = kzalloc(argp->opcnt * sizeof(*argp->ops), GFP_KERNEL); if (!argp->ops) { argp->ops = argp->iops; dprintk("nfsd: couldn't allocate room for COMPOUND\n"); goto xdr_error; } } if (argp->minorversion > NFSD_SUPPORTED_MINOR_VERSION) argp->opcnt = 0; for (i = 0; i < argp->opcnt; i++) { op = &argp->ops[i]; op->replay = NULL; READ_BUF(4); op->opnum = be32_to_cpup(p++); if (nfsd4_opnum_in_range(argp, op)) op->status = nfsd4_dec_ops[op->opnum](argp, &op->u); else { op->opnum = OP_ILLEGAL; op->status = nfserr_op_illegal; } /* * We'll try to cache the result in the DRC if any one * op in the compound wants to be cached: */ cachethis |= nfsd4_cache_this_op(op); if (op->opnum == OP_READ) { readcount++; readbytes += nfsd4_max_reply(argp->rqstp, op); } else max_reply += nfsd4_max_reply(argp->rqstp, op); /* * OP_LOCK and OP_LOCKT may return a conflicting lock. * (Special case because it will just skip encoding this * if it runs out of xdr buffer space, and it is the only * operation that behaves this way.) */ if (op->opnum == OP_LOCK || op->opnum == OP_LOCKT) max_reply += NFS4_OPAQUE_LIMIT; if (op->status) { argp->opcnt = i+1; break; } } /* Sessions make the DRC unnecessary: */ if (argp->minorversion) cachethis = false; svc_reserve(argp->rqstp, max_reply + readbytes); argp->rqstp->rq_cachetype = cachethis ? RC_REPLBUFF : RC_NOCACHE; if (readcount > 1 || max_reply > PAGE_SIZE - auth_slack) clear_bit(RQ_SPLICE_OK, &argp->rqstp->rq_flags); DECODE_TAIL; } static __be32 *encode_change(__be32 *p, struct kstat *stat, struct inode *inode, struct svc_export *exp) { if (exp->ex_flags & NFSEXP_V4ROOT) { *p++ = cpu_to_be32(convert_to_wallclock(exp->cd->flush_time)); *p++ = 0; } else if (IS_I_VERSION(inode)) { p = xdr_encode_hyper(p, inode->i_version); } else { *p++ = cpu_to_be32(stat->ctime.tv_sec); *p++ = cpu_to_be32(stat->ctime.tv_nsec); } return p; } static __be32 *encode_cinfo(__be32 *p, struct nfsd4_change_info *c) { *p++ = cpu_to_be32(c->atomic); if (c->change_supported) { p = xdr_encode_hyper(p, c->before_change); p = xdr_encode_hyper(p, c->after_change); } else { *p++ = cpu_to_be32(c->before_ctime_sec); *p++ = cpu_to_be32(c->before_ctime_nsec); *p++ = cpu_to_be32(c->after_ctime_sec); *p++ = cpu_to_be32(c->after_ctime_nsec); } return p; } /* Encode as an array of strings the string given with components * separated @sep, escaped with esc_enter and esc_exit. */ static __be32 nfsd4_encode_components_esc(struct xdr_stream *xdr, char sep, char *components, char esc_enter, char esc_exit) { __be32 *p; __be32 pathlen; int pathlen_offset; int strlen, count=0; char *str, *end, *next; dprintk("nfsd4_encode_components(%s)\n", components); pathlen_offset = xdr->buf->len; p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; p++; /* We will fill this in with @count later */ end = str = components; while (*end) { bool found_esc = false; /* try to parse as esc_start, ..., esc_end, sep */ if (*str == esc_enter) { for (; *end && (*end != esc_exit); end++) /* find esc_exit or end of string */; next = end + 1; if (*end && (!*next || *next == sep)) { str++; found_esc = true; } } if (!found_esc) for (; *end && (*end != sep); end++) /* find sep or end of string */; strlen = end - str; if (strlen) { p = xdr_reserve_space(xdr, strlen + 4); if (!p) return nfserr_resource; p = xdr_encode_opaque(p, str, strlen); count++; } else end++; if (found_esc) end = next; str = end; } pathlen = htonl(count); write_bytes_to_xdr_buf(xdr->buf, pathlen_offset, &pathlen, 4); return 0; } /* Encode as an array of strings the string given with components * separated @sep. */ static __be32 nfsd4_encode_components(struct xdr_stream *xdr, char sep, char *components) { return nfsd4_encode_components_esc(xdr, sep, components, 0, 0); } /* * encode a location element of a fs_locations structure */ static __be32 nfsd4_encode_fs_location4(struct xdr_stream *xdr, struct nfsd4_fs_location *location) { __be32 status; status = nfsd4_encode_components_esc(xdr, ':', location->hosts, '[', ']'); if (status) return status; status = nfsd4_encode_components(xdr, '/', location->path); if (status) return status; return 0; } /* * Encode a path in RFC3530 'pathname4' format */ static __be32 nfsd4_encode_path(struct xdr_stream *xdr, const struct path *root, const struct path *path) { struct path cur = *path; __be32 *p; struct dentry **components = NULL; unsigned int ncomponents = 0; __be32 err = nfserr_jukebox; dprintk("nfsd4_encode_components("); path_get(&cur); /* First walk the path up to the nfsd root, and store the * dentries/path components in an array. */ for (;;) { if (path_equal(&cur, root)) break; if (cur.dentry == cur.mnt->mnt_root) { if (follow_up(&cur)) continue; goto out_free; } if ((ncomponents & 15) == 0) { struct dentry **new; new = krealloc(components, sizeof(*new) * (ncomponents + 16), GFP_KERNEL); if (!new) goto out_free; components = new; } components[ncomponents++] = cur.dentry; cur.dentry = dget_parent(cur.dentry); } err = nfserr_resource; p = xdr_reserve_space(xdr, 4); if (!p) goto out_free; *p++ = cpu_to_be32(ncomponents); while (ncomponents) { struct dentry *dentry = components[ncomponents - 1]; unsigned int len; spin_lock(&dentry->d_lock); len = dentry->d_name.len; p = xdr_reserve_space(xdr, len + 4); if (!p) { spin_unlock(&dentry->d_lock); goto out_free; } p = xdr_encode_opaque(p, dentry->d_name.name, len); dprintk("/%pd", dentry); spin_unlock(&dentry->d_lock); dput(dentry); ncomponents--; } err = 0; out_free: dprintk(")\n"); while (ncomponents) dput(components[--ncomponents]); kfree(components); path_put(&cur); return err; } static __be32 nfsd4_encode_fsloc_fsroot(struct xdr_stream *xdr, struct svc_rqst *rqstp, const struct path *path) { struct svc_export *exp_ps; __be32 res; exp_ps = rqst_find_fsidzero_export(rqstp); if (IS_ERR(exp_ps)) return nfserrno(PTR_ERR(exp_ps)); res = nfsd4_encode_path(xdr, &exp_ps->ex_path, path); exp_put(exp_ps); return res; } /* * encode a fs_locations structure */ static __be32 nfsd4_encode_fs_locations(struct xdr_stream *xdr, struct svc_rqst *rqstp, struct svc_export *exp) { __be32 status; int i; __be32 *p; struct nfsd4_fs_locations *fslocs = &exp->ex_fslocs; status = nfsd4_encode_fsloc_fsroot(xdr, rqstp, &exp->ex_path); if (status) return status; p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; *p++ = cpu_to_be32(fslocs->locations_count); for (i=0; i<fslocs->locations_count; i++) { status = nfsd4_encode_fs_location4(xdr, &fslocs->locations[i]); if (status) return status; } return 0; } static u32 nfs4_file_type(umode_t mode) { switch (mode & S_IFMT) { case S_IFIFO: return NF4FIFO; case S_IFCHR: return NF4CHR; case S_IFDIR: return NF4DIR; case S_IFBLK: return NF4BLK; case S_IFLNK: return NF4LNK; case S_IFREG: return NF4REG; case S_IFSOCK: return NF4SOCK; default: return NF4BAD; }; } static inline __be32 nfsd4_encode_aclname(struct xdr_stream *xdr, struct svc_rqst *rqstp, struct nfs4_ace *ace) { if (ace->whotype != NFS4_ACL_WHO_NAMED) return nfs4_acl_write_who(xdr, ace->whotype); else if (ace->flag & NFS4_ACE_IDENTIFIER_GROUP) return nfsd4_encode_group(xdr, rqstp, ace->who_gid); else return nfsd4_encode_user(xdr, rqstp, ace->who_uid); } static inline __be32 nfsd4_encode_layout_types(struct xdr_stream *xdr, u32 layout_types) { __be32 *p; unsigned long i = hweight_long(layout_types); p = xdr_reserve_space(xdr, 4 + 4 * i); if (!p) return nfserr_resource; *p++ = cpu_to_be32(i); for (i = LAYOUT_NFSV4_1_FILES; i < LAYOUT_TYPE_MAX; ++i) if (layout_types & (1 << i)) *p++ = cpu_to_be32(i); return 0; } #define WORD0_ABSENT_FS_ATTRS (FATTR4_WORD0_FS_LOCATIONS | FATTR4_WORD0_FSID | \ FATTR4_WORD0_RDATTR_ERROR) #define WORD1_ABSENT_FS_ATTRS FATTR4_WORD1_MOUNTED_ON_FILEID #define WORD2_ABSENT_FS_ATTRS 0 #ifdef CONFIG_NFSD_V4_SECURITY_LABEL static inline __be32 nfsd4_encode_security_label(struct xdr_stream *xdr, struct svc_rqst *rqstp, void *context, int len) { __be32 *p; p = xdr_reserve_space(xdr, len + 4 + 4 + 4); if (!p) return nfserr_resource; /* * For now we use a 0 here to indicate the null translation; in * the future we may place a call to translation code here. */ *p++ = cpu_to_be32(0); /* lfs */ *p++ = cpu_to_be32(0); /* pi */ p = xdr_encode_opaque(p, context, len); return 0; } #else static inline __be32 nfsd4_encode_security_label(struct xdr_stream *xdr, struct svc_rqst *rqstp, void *context, int len) { return 0; } #endif static __be32 fattr_handle_absent_fs(u32 *bmval0, u32 *bmval1, u32 *bmval2, u32 *rdattr_err) { /* As per referral draft: */ if (*bmval0 & ~WORD0_ABSENT_FS_ATTRS || *bmval1 & ~WORD1_ABSENT_FS_ATTRS) { if (*bmval0 & FATTR4_WORD0_RDATTR_ERROR || *bmval0 & FATTR4_WORD0_FS_LOCATIONS) *rdattr_err = NFSERR_MOVED; else return nfserr_moved; } *bmval0 &= WORD0_ABSENT_FS_ATTRS; *bmval1 &= WORD1_ABSENT_FS_ATTRS; *bmval2 &= WORD2_ABSENT_FS_ATTRS; return 0; } static int get_parent_attributes(struct svc_export *exp, struct kstat *stat) { struct path path = exp->ex_path; int err; path_get(&path); while (follow_up(&path)) { if (path.dentry != path.mnt->mnt_root) break; } err = vfs_getattr(&path, stat, STATX_BASIC_STATS, AT_STATX_SYNC_AS_STAT); path_put(&path); return err; } static __be32 nfsd4_encode_bitmap(struct xdr_stream *xdr, u32 bmval0, u32 bmval1, u32 bmval2) { __be32 *p; if (bmval2) { p = xdr_reserve_space(xdr, 16); if (!p) goto out_resource; *p++ = cpu_to_be32(3); *p++ = cpu_to_be32(bmval0); *p++ = cpu_to_be32(bmval1); *p++ = cpu_to_be32(bmval2); } else if (bmval1) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; *p++ = cpu_to_be32(2); *p++ = cpu_to_be32(bmval0); *p++ = cpu_to_be32(bmval1); } else { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; *p++ = cpu_to_be32(1); *p++ = cpu_to_be32(bmval0); } return 0; out_resource: return nfserr_resource; } /* * Note: @fhp can be NULL; in this case, we might have to compose the filehandle * ourselves. */ static __be32 nfsd4_encode_fattr(struct xdr_stream *xdr, struct svc_fh *fhp, struct svc_export *exp, struct dentry *dentry, u32 *bmval, struct svc_rqst *rqstp, int ignore_crossmnt) { u32 bmval0 = bmval[0]; u32 bmval1 = bmval[1]; u32 bmval2 = bmval[2]; struct kstat stat; struct svc_fh *tempfh = NULL; struct kstatfs statfs; __be32 *p; int starting_len = xdr->buf->len; int attrlen_offset; __be32 attrlen; u32 dummy; u64 dummy64; u32 rdattr_err = 0; __be32 status; int err; struct nfs4_acl *acl = NULL; void *context = NULL; int contextlen; bool contextsupport = false; struct nfsd4_compoundres *resp = rqstp->rq_resp; u32 minorversion = resp->cstate.minorversion; struct path path = { .mnt = exp->ex_path.mnt, .dentry = dentry, }; struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id); BUG_ON(bmval1 & NFSD_WRITEONLY_ATTRS_WORD1); BUG_ON(!nfsd_attrs_supported(minorversion, bmval)); if (exp->ex_fslocs.migrated) { status = fattr_handle_absent_fs(&bmval0, &bmval1, &bmval2, &rdattr_err); if (status) goto out; } err = vfs_getattr(&path, &stat, STATX_BASIC_STATS, AT_STATX_SYNC_AS_STAT); if (err) goto out_nfserr; if ((bmval0 & (FATTR4_WORD0_FILES_AVAIL | FATTR4_WORD0_FILES_FREE | FATTR4_WORD0_FILES_TOTAL | FATTR4_WORD0_MAXNAME)) || (bmval1 & (FATTR4_WORD1_SPACE_AVAIL | FATTR4_WORD1_SPACE_FREE | FATTR4_WORD1_SPACE_TOTAL))) { err = vfs_statfs(&path, &statfs); if (err) goto out_nfserr; } if ((bmval0 & (FATTR4_WORD0_FILEHANDLE | FATTR4_WORD0_FSID)) && !fhp) { tempfh = kmalloc(sizeof(struct svc_fh), GFP_KERNEL); status = nfserr_jukebox; if (!tempfh) goto out; fh_init(tempfh, NFS4_FHSIZE); status = fh_compose(tempfh, exp, dentry, NULL); if (status) goto out; fhp = tempfh; } if (bmval0 & FATTR4_WORD0_ACL) { err = nfsd4_get_nfs4_acl(rqstp, dentry, &acl); if (err == -EOPNOTSUPP) bmval0 &= ~FATTR4_WORD0_ACL; else if (err == -EINVAL) { status = nfserr_attrnotsupp; goto out; } else if (err != 0) goto out_nfserr; } #ifdef CONFIG_NFSD_V4_SECURITY_LABEL if ((bmval2 & FATTR4_WORD2_SECURITY_LABEL) || bmval0 & FATTR4_WORD0_SUPPORTED_ATTRS) { if (exp->ex_flags & NFSEXP_SECURITY_LABEL) err = security_inode_getsecctx(d_inode(dentry), &context, &contextlen); else err = -EOPNOTSUPP; contextsupport = (err == 0); if (bmval2 & FATTR4_WORD2_SECURITY_LABEL) { if (err == -EOPNOTSUPP) bmval2 &= ~FATTR4_WORD2_SECURITY_LABEL; else if (err) goto out_nfserr; } } #endif /* CONFIG_NFSD_V4_SECURITY_LABEL */ status = nfsd4_encode_bitmap(xdr, bmval0, bmval1, bmval2); if (status) goto out; attrlen_offset = xdr->buf->len; p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; p++; /* to be backfilled later */ if (bmval0 & FATTR4_WORD0_SUPPORTED_ATTRS) { u32 supp[3]; memcpy(supp, nfsd_suppattrs[minorversion], sizeof(supp)); if (!IS_POSIXACL(dentry->d_inode)) supp[0] &= ~FATTR4_WORD0_ACL; if (!contextsupport) supp[2] &= ~FATTR4_WORD2_SECURITY_LABEL; if (!supp[2]) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; *p++ = cpu_to_be32(2); *p++ = cpu_to_be32(supp[0]); *p++ = cpu_to_be32(supp[1]); } else { p = xdr_reserve_space(xdr, 16); if (!p) goto out_resource; *p++ = cpu_to_be32(3); *p++ = cpu_to_be32(supp[0]); *p++ = cpu_to_be32(supp[1]); *p++ = cpu_to_be32(supp[2]); } } if (bmval0 & FATTR4_WORD0_TYPE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; dummy = nfs4_file_type(stat.mode); if (dummy == NF4BAD) { status = nfserr_serverfault; goto out; } *p++ = cpu_to_be32(dummy); } if (bmval0 & FATTR4_WORD0_FH_EXPIRE_TYPE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; if (exp->ex_flags & NFSEXP_NOSUBTREECHECK) *p++ = cpu_to_be32(NFS4_FH_PERSISTENT); else *p++ = cpu_to_be32(NFS4_FH_PERSISTENT| NFS4_FH_VOL_RENAME); } if (bmval0 & FATTR4_WORD0_CHANGE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = encode_change(p, &stat, d_inode(dentry), exp); } if (bmval0 & FATTR4_WORD0_SIZE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, stat.size); } if (bmval0 & FATTR4_WORD0_LINK_SUPPORT) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_SYMLINK_SUPPORT) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_NAMED_ATTR) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); } if (bmval0 & FATTR4_WORD0_FSID) { p = xdr_reserve_space(xdr, 16); if (!p) goto out_resource; if (exp->ex_fslocs.migrated) { p = xdr_encode_hyper(p, NFS4_REFERRAL_FSID_MAJOR); p = xdr_encode_hyper(p, NFS4_REFERRAL_FSID_MINOR); } else switch(fsid_source(fhp)) { case FSIDSOURCE_FSID: p = xdr_encode_hyper(p, (u64)exp->ex_fsid); p = xdr_encode_hyper(p, (u64)0); break; case FSIDSOURCE_DEV: *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(MAJOR(stat.dev)); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(MINOR(stat.dev)); break; case FSIDSOURCE_UUID: p = xdr_encode_opaque_fixed(p, exp->ex_uuid, EX_UUID_LEN); break; } } if (bmval0 & FATTR4_WORD0_UNIQUE_HANDLES) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); } if (bmval0 & FATTR4_WORD0_LEASE_TIME) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(nn->nfsd4_lease); } if (bmval0 & FATTR4_WORD0_RDATTR_ERROR) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(rdattr_err); } if (bmval0 & FATTR4_WORD0_ACL) { struct nfs4_ace *ace; if (acl == NULL) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); goto out_acl; } p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(acl->naces); for (ace = acl->aces; ace < acl->aces + acl->naces; ace++) { p = xdr_reserve_space(xdr, 4*3); if (!p) goto out_resource; *p++ = cpu_to_be32(ace->type); *p++ = cpu_to_be32(ace->flag); *p++ = cpu_to_be32(ace->access_mask & NFS4_ACE_MASK_ALL); status = nfsd4_encode_aclname(xdr, rqstp, ace); if (status) goto out; } } out_acl: if (bmval0 & FATTR4_WORD0_ACLSUPPORT) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(IS_POSIXACL(dentry->d_inode) ? ACL4_SUPPORT_ALLOW_ACL|ACL4_SUPPORT_DENY_ACL : 0); } if (bmval0 & FATTR4_WORD0_CANSETTIME) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_CASE_INSENSITIVE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); } if (bmval0 & FATTR4_WORD0_CASE_PRESERVING) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_CHOWN_RESTRICTED) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_FILEHANDLE) { p = xdr_reserve_space(xdr, fhp->fh_handle.fh_size + 4); if (!p) goto out_resource; p = xdr_encode_opaque(p, &fhp->fh_handle.fh_base, fhp->fh_handle.fh_size); } if (bmval0 & FATTR4_WORD0_FILEID) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, stat.ino); } if (bmval0 & FATTR4_WORD0_FILES_AVAIL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) statfs.f_ffree); } if (bmval0 & FATTR4_WORD0_FILES_FREE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) statfs.f_ffree); } if (bmval0 & FATTR4_WORD0_FILES_TOTAL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) statfs.f_files); } if (bmval0 & FATTR4_WORD0_FS_LOCATIONS) { status = nfsd4_encode_fs_locations(xdr, rqstp, exp); if (status) goto out; } if (bmval0 & FATTR4_WORD0_HOMOGENEOUS) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_MAXFILESIZE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, exp->ex_path.mnt->mnt_sb->s_maxbytes); } if (bmval0 & FATTR4_WORD0_MAXLINK) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(255); } if (bmval0 & FATTR4_WORD0_MAXNAME) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(statfs.f_namelen); } if (bmval0 & FATTR4_WORD0_MAXREAD) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) svc_max_payload(rqstp)); } if (bmval0 & FATTR4_WORD0_MAXWRITE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) svc_max_payload(rqstp)); } if (bmval1 & FATTR4_WORD1_MODE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(stat.mode & S_IALLUGO); } if (bmval1 & FATTR4_WORD1_NO_TRUNC) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval1 & FATTR4_WORD1_NUMLINKS) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(stat.nlink); } if (bmval1 & FATTR4_WORD1_OWNER) { status = nfsd4_encode_user(xdr, rqstp, stat.uid); if (status) goto out; } if (bmval1 & FATTR4_WORD1_OWNER_GROUP) { status = nfsd4_encode_group(xdr, rqstp, stat.gid); if (status) goto out; } if (bmval1 & FATTR4_WORD1_RAWDEV) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; *p++ = cpu_to_be32((u32) MAJOR(stat.rdev)); *p++ = cpu_to_be32((u32) MINOR(stat.rdev)); } if (bmval1 & FATTR4_WORD1_SPACE_AVAIL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)statfs.f_bavail * (u64)statfs.f_bsize; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_SPACE_FREE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)statfs.f_bfree * (u64)statfs.f_bsize; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_SPACE_TOTAL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)statfs.f_blocks * (u64)statfs.f_bsize; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_SPACE_USED) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)stat.blocks << 9; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_TIME_ACCESS) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; p = xdr_encode_hyper(p, (s64)stat.atime.tv_sec); *p++ = cpu_to_be32(stat.atime.tv_nsec); } if (bmval1 & FATTR4_WORD1_TIME_DELTA) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(1); *p++ = cpu_to_be32(0); } if (bmval1 & FATTR4_WORD1_TIME_METADATA) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; p = xdr_encode_hyper(p, (s64)stat.ctime.tv_sec); *p++ = cpu_to_be32(stat.ctime.tv_nsec); } if (bmval1 & FATTR4_WORD1_TIME_MODIFY) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; p = xdr_encode_hyper(p, (s64)stat.mtime.tv_sec); *p++ = cpu_to_be32(stat.mtime.tv_nsec); } if (bmval1 & FATTR4_WORD1_MOUNTED_ON_FILEID) { struct kstat parent_stat; u64 ino = stat.ino; p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; /* * Get parent's attributes if not ignoring crossmount * and this is the root of a cross-mounted filesystem. */ if (ignore_crossmnt == 0 && dentry == exp->ex_path.mnt->mnt_root) { err = get_parent_attributes(exp, &parent_stat); if (err) goto out_nfserr; ino = parent_stat.ino; } p = xdr_encode_hyper(p, ino); } #ifdef CONFIG_NFSD_PNFS if (bmval1 & FATTR4_WORD1_FS_LAYOUT_TYPES) { status = nfsd4_encode_layout_types(xdr, exp->ex_layout_types); if (status) goto out; } if (bmval2 & FATTR4_WORD2_LAYOUT_TYPES) { status = nfsd4_encode_layout_types(xdr, exp->ex_layout_types); if (status) goto out; } if (bmval2 & FATTR4_WORD2_LAYOUT_BLKSIZE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(stat.blksize); } #endif /* CONFIG_NFSD_PNFS */ if (bmval2 & FATTR4_WORD2_SUPPATTR_EXCLCREAT) { status = nfsd4_encode_bitmap(xdr, NFSD_SUPPATTR_EXCLCREAT_WORD0, NFSD_SUPPATTR_EXCLCREAT_WORD1, NFSD_SUPPATTR_EXCLCREAT_WORD2); if (status) goto out; } if (bmval2 & FATTR4_WORD2_SECURITY_LABEL) { status = nfsd4_encode_security_label(xdr, rqstp, context, contextlen); if (status) goto out; } attrlen = htonl(xdr->buf->len - attrlen_offset - 4); write_bytes_to_xdr_buf(xdr->buf, attrlen_offset, &attrlen, 4); status = nfs_ok; out: #ifdef CONFIG_NFSD_V4_SECURITY_LABEL if (context) security_release_secctx(context, contextlen); #endif /* CONFIG_NFSD_V4_SECURITY_LABEL */ kfree(acl); if (tempfh) { fh_put(tempfh); kfree(tempfh); } if (status) xdr_truncate_encode(xdr, starting_len); return status; out_nfserr: status = nfserrno(err); goto out; out_resource: status = nfserr_resource; goto out; } static void svcxdr_init_encode_from_buffer(struct xdr_stream *xdr, struct xdr_buf *buf, __be32 *p, int bytes) { xdr->scratch.iov_len = 0; memset(buf, 0, sizeof(struct xdr_buf)); buf->head[0].iov_base = p; buf->head[0].iov_len = 0; buf->len = 0; xdr->buf = buf; xdr->iov = buf->head; xdr->p = p; xdr->end = (void *)p + bytes; buf->buflen = bytes; } __be32 nfsd4_encode_fattr_to_buf(__be32 **p, int words, struct svc_fh *fhp, struct svc_export *exp, struct dentry *dentry, u32 *bmval, struct svc_rqst *rqstp, int ignore_crossmnt) { struct xdr_buf dummy; struct xdr_stream xdr; __be32 ret; svcxdr_init_encode_from_buffer(&xdr, &dummy, *p, words << 2); ret = nfsd4_encode_fattr(&xdr, fhp, exp, dentry, bmval, rqstp, ignore_crossmnt); *p = xdr.p; return ret; } static inline int attributes_need_mount(u32 *bmval) { if (bmval[0] & ~(FATTR4_WORD0_RDATTR_ERROR | FATTR4_WORD0_LEASE_TIME)) return 1; if (bmval[1] & ~FATTR4_WORD1_MOUNTED_ON_FILEID) return 1; return 0; } static __be32 nfsd4_encode_dirent_fattr(struct xdr_stream *xdr, struct nfsd4_readdir *cd, const char *name, int namlen) { struct svc_export *exp = cd->rd_fhp->fh_export; struct dentry *dentry; __be32 nfserr; int ignore_crossmnt = 0; dentry = lookup_one_len_unlocked(name, cd->rd_fhp->fh_dentry, namlen); if (IS_ERR(dentry)) return nfserrno(PTR_ERR(dentry)); if (d_really_is_negative(dentry)) { /* * we're not holding the i_mutex here, so there's * a window where this directory entry could have gone * away. */ dput(dentry); return nfserr_noent; } exp_get(exp); /* * In the case of a mountpoint, the client may be asking for * attributes that are only properties of the underlying filesystem * as opposed to the cross-mounted file system. In such a case, * we will not follow the cross mount and will fill the attribtutes * directly from the mountpoint dentry. */ if (nfsd_mountpoint(dentry, exp)) { int err; if (!(exp->ex_flags & NFSEXP_V4ROOT) && !attributes_need_mount(cd->rd_bmval)) { ignore_crossmnt = 1; goto out_encode; } /* * Why the heck aren't we just using nfsd_lookup?? * Different "."/".." handling? Something else? * At least, add a comment here to explain.... */ err = nfsd_cross_mnt(cd->rd_rqstp, &dentry, &exp); if (err) { nfserr = nfserrno(err); goto out_put; } nfserr = check_nfsd_access(exp, cd->rd_rqstp); if (nfserr) goto out_put; } out_encode: nfserr = nfsd4_encode_fattr(xdr, NULL, exp, dentry, cd->rd_bmval, cd->rd_rqstp, ignore_crossmnt); out_put: dput(dentry); exp_put(exp); return nfserr; } static __be32 * nfsd4_encode_rdattr_error(struct xdr_stream *xdr, __be32 nfserr) { __be32 *p; p = xdr_reserve_space(xdr, 20); if (!p) return NULL; *p++ = htonl(2); *p++ = htonl(FATTR4_WORD0_RDATTR_ERROR); /* bmval0 */ *p++ = htonl(0); /* bmval1 */ *p++ = htonl(4); /* attribute length */ *p++ = nfserr; /* no htonl */ return p; } static int nfsd4_encode_dirent(void *ccdv, const char *name, int namlen, loff_t offset, u64 ino, unsigned int d_type) { struct readdir_cd *ccd = ccdv; struct nfsd4_readdir *cd = container_of(ccd, struct nfsd4_readdir, common); struct xdr_stream *xdr = cd->xdr; int start_offset = xdr->buf->len; int cookie_offset; u32 name_and_cookie; int entry_bytes; __be32 nfserr = nfserr_toosmall; __be64 wire_offset; __be32 *p; /* In nfsv4, "." and ".." never make it onto the wire.. */ if (name && isdotent(name, namlen)) { cd->common.err = nfs_ok; return 0; } if (cd->cookie_offset) { wire_offset = cpu_to_be64(offset); write_bytes_to_xdr_buf(xdr->buf, cd->cookie_offset, &wire_offset, 8); } p = xdr_reserve_space(xdr, 4); if (!p) goto fail; *p++ = xdr_one; /* mark entry present */ cookie_offset = xdr->buf->len; p = xdr_reserve_space(xdr, 3*4 + namlen); if (!p) goto fail; p = xdr_encode_hyper(p, NFS_OFFSET_MAX); /* offset of next entry */ p = xdr_encode_array(p, name, namlen); /* name length & name */ nfserr = nfsd4_encode_dirent_fattr(xdr, cd, name, namlen); switch (nfserr) { case nfs_ok: break; case nfserr_resource: nfserr = nfserr_toosmall; goto fail; case nfserr_noent: xdr_truncate_encode(xdr, start_offset); goto skip_entry; default: /* * If the client requested the RDATTR_ERROR attribute, * we stuff the error code into this attribute * and continue. If this attribute was not requested, * then in accordance with the spec, we fail the * entire READDIR operation(!) */ if (!(cd->rd_bmval[0] & FATTR4_WORD0_RDATTR_ERROR)) goto fail; p = nfsd4_encode_rdattr_error(xdr, nfserr); if (p == NULL) { nfserr = nfserr_toosmall; goto fail; } } nfserr = nfserr_toosmall; entry_bytes = xdr->buf->len - start_offset; if (entry_bytes > cd->rd_maxcount) goto fail; cd->rd_maxcount -= entry_bytes; /* * RFC 3530 14.2.24 describes rd_dircount as only a "hint", so * let's always let through the first entry, at least: */ if (!cd->rd_dircount) goto fail; name_and_cookie = 4 + 4 * XDR_QUADLEN(namlen) + 8; if (name_and_cookie > cd->rd_dircount && cd->cookie_offset) goto fail; cd->rd_dircount -= min(cd->rd_dircount, name_and_cookie); cd->cookie_offset = cookie_offset; skip_entry: cd->common.err = nfs_ok; return 0; fail: xdr_truncate_encode(xdr, start_offset); cd->common.err = nfserr; return -EINVAL; } static __be32 nfsd4_encode_stateid(struct xdr_stream *xdr, stateid_t *sid) { __be32 *p; p = xdr_reserve_space(xdr, sizeof(stateid_t)); if (!p) return nfserr_resource; *p++ = cpu_to_be32(sid->si_generation); p = xdr_encode_opaque_fixed(p, &sid->si_opaque, sizeof(stateid_opaque_t)); return 0; } static __be32 nfsd4_encode_access(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_access *access) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, 8); if (!p) return nfserr_resource; *p++ = cpu_to_be32(access->ac_supported); *p++ = cpu_to_be32(access->ac_resp_access); } return nfserr; } static __be32 nfsd4_encode_bind_conn_to_session(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_bind_conn_to_session *bcts) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, NFS4_MAX_SESSIONID_LEN + 8); if (!p) return nfserr_resource; p = xdr_encode_opaque_fixed(p, bcts->sessionid.data, NFS4_MAX_SESSIONID_LEN); *p++ = cpu_to_be32(bcts->dir); /* Upshifting from TCP to RDMA is not supported */ *p++ = cpu_to_be32(0); } return nfserr; } static __be32 nfsd4_encode_close(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_close *close) { struct xdr_stream *xdr = &resp->xdr; if (!nfserr) nfserr = nfsd4_encode_stateid(xdr, &close->cl_stateid); return nfserr; } static __be32 nfsd4_encode_commit(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_commit *commit) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, NFS4_VERIFIER_SIZE); if (!p) return nfserr_resource; p = xdr_encode_opaque_fixed(p, commit->co_verf.data, NFS4_VERIFIER_SIZE); } return nfserr; } static __be32 nfsd4_encode_create(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_create *create) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, 20); if (!p) return nfserr_resource; encode_cinfo(p, &create->cr_cinfo); nfserr = nfsd4_encode_bitmap(xdr, create->cr_bmval[0], create->cr_bmval[1], create->cr_bmval[2]); } return nfserr; } static __be32 nfsd4_encode_getattr(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_getattr *getattr) { struct svc_fh *fhp = getattr->ga_fhp; struct xdr_stream *xdr = &resp->xdr; if (nfserr) return nfserr; nfserr = nfsd4_encode_fattr(xdr, fhp, fhp->fh_export, fhp->fh_dentry, getattr->ga_bmval, resp->rqstp, 0); return nfserr; } static __be32 nfsd4_encode_getfh(struct nfsd4_compoundres *resp, __be32 nfserr, struct svc_fh **fhpp) { struct xdr_stream *xdr = &resp->xdr; struct svc_fh *fhp = *fhpp; unsigned int len; __be32 *p; if (!nfserr) { len = fhp->fh_handle.fh_size; p = xdr_reserve_space(xdr, len + 4); if (!p) return nfserr_resource; p = xdr_encode_opaque(p, &fhp->fh_handle.fh_base, len); } return nfserr; } /* * Including all fields other than the name, a LOCK4denied structure requires * 8(clientid) + 4(namelen) + 8(offset) + 8(length) + 4(type) = 32 bytes. */ static __be32 nfsd4_encode_lock_denied(struct xdr_stream *xdr, struct nfsd4_lock_denied *ld) { struct xdr_netobj *conf = &ld->ld_owner; __be32 *p; again: p = xdr_reserve_space(xdr, 32 + XDR_LEN(conf->len)); if (!p) { /* * Don't fail to return the result just because we can't * return the conflicting open: */ if (conf->len) { kfree(conf->data); conf->len = 0; conf->data = NULL; goto again; } return nfserr_resource; } p = xdr_encode_hyper(p, ld->ld_start); p = xdr_encode_hyper(p, ld->ld_length); *p++ = cpu_to_be32(ld->ld_type); if (conf->len) { p = xdr_encode_opaque_fixed(p, &ld->ld_clientid, 8); p = xdr_encode_opaque(p, conf->data, conf->len); kfree(conf->data); } else { /* non - nfsv4 lock in conflict, no clientid nor owner */ p = xdr_encode_hyper(p, (u64)0); /* clientid */ *p++ = cpu_to_be32(0); /* length of owner name */ } return nfserr_denied; } static __be32 nfsd4_encode_lock(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_lock *lock) { struct xdr_stream *xdr = &resp->xdr; if (!nfserr) nfserr = nfsd4_encode_stateid(xdr, &lock->lk_resp_stateid); else if (nfserr == nfserr_denied) nfserr = nfsd4_encode_lock_denied(xdr, &lock->lk_denied); return nfserr; } static __be32 nfsd4_encode_lockt(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_lockt *lockt) { struct xdr_stream *xdr = &resp->xdr; if (nfserr == nfserr_denied) nfsd4_encode_lock_denied(xdr, &lockt->lt_denied); return nfserr; } static __be32 nfsd4_encode_locku(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_locku *locku) { struct xdr_stream *xdr = &resp->xdr; if (!nfserr) nfserr = nfsd4_encode_stateid(xdr, &locku->lu_stateid); return nfserr; } static __be32 nfsd4_encode_link(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_link *link) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, 20); if (!p) return nfserr_resource; p = encode_cinfo(p, &link->li_cinfo); } return nfserr; } static __be32 nfsd4_encode_open(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_open *open) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (nfserr) goto out; nfserr = nfsd4_encode_stateid(xdr, &open->op_stateid); if (nfserr) goto out; p = xdr_reserve_space(xdr, 24); if (!p) return nfserr_resource; p = encode_cinfo(p, &open->op_cinfo); *p++ = cpu_to_be32(open->op_rflags); nfserr = nfsd4_encode_bitmap(xdr, open->op_bmval[0], open->op_bmval[1], open->op_bmval[2]); if (nfserr) goto out; p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; *p++ = cpu_to_be32(open->op_delegate_type); switch (open->op_delegate_type) { case NFS4_OPEN_DELEGATE_NONE: break; case NFS4_OPEN_DELEGATE_READ: nfserr = nfsd4_encode_stateid(xdr, &open->op_delegate_stateid); if (nfserr) return nfserr; p = xdr_reserve_space(xdr, 20); if (!p) return nfserr_resource; *p++ = cpu_to_be32(open->op_recall); /* * TODO: ACE's in delegations */ *p++ = cpu_to_be32(NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); /* XXX: is NULL principal ok? */ break; case NFS4_OPEN_DELEGATE_WRITE: nfserr = nfsd4_encode_stateid(xdr, &open->op_delegate_stateid); if (nfserr) return nfserr; p = xdr_reserve_space(xdr, 32); if (!p) return nfserr_resource; *p++ = cpu_to_be32(0); /* * TODO: space_limit's in delegations */ *p++ = cpu_to_be32(NFS4_LIMIT_SIZE); *p++ = cpu_to_be32(~(u32)0); *p++ = cpu_to_be32(~(u32)0); /* * TODO: ACE's in delegations */ *p++ = cpu_to_be32(NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); /* XXX: is NULL principal ok? */ break; case NFS4_OPEN_DELEGATE_NONE_EXT: /* 4.1 */ switch (open->op_why_no_deleg) { case WND4_CONTENTION: case WND4_RESOURCE: p = xdr_reserve_space(xdr, 8); if (!p) return nfserr_resource; *p++ = cpu_to_be32(open->op_why_no_deleg); /* deleg signaling not supported yet: */ *p++ = cpu_to_be32(0); break; default: p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; *p++ = cpu_to_be32(open->op_why_no_deleg); } break; default: BUG(); } /* XXX save filehandle here */ out: return nfserr; } static __be32 nfsd4_encode_open_confirm(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_open_confirm *oc) { struct xdr_stream *xdr = &resp->xdr; if (!nfserr) nfserr = nfsd4_encode_stateid(xdr, &oc->oc_resp_stateid); return nfserr; } static __be32 nfsd4_encode_open_downgrade(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_open_downgrade *od) { struct xdr_stream *xdr = &resp->xdr; if (!nfserr) nfserr = nfsd4_encode_stateid(xdr, &od->od_stateid); return nfserr; } static __be32 nfsd4_encode_splice_read( struct nfsd4_compoundres *resp, struct nfsd4_read *read, struct file *file, unsigned long maxcount) { struct xdr_stream *xdr = &resp->xdr; struct xdr_buf *buf = xdr->buf; u32 eof; long len; int space_left; __be32 nfserr; __be32 *p = xdr->p - 2; /* Make sure there will be room for padding if needed */ if (xdr->end - xdr->p < 1) return nfserr_resource; len = maxcount; nfserr = nfsd_splice_read(read->rd_rqstp, file, read->rd_offset, &maxcount); if (nfserr) { /* * nfsd_splice_actor may have already messed with the * page length; reset it so as not to confuse * xdr_truncate_encode: */ buf->page_len = 0; return nfserr; } eof = nfsd_eof_on_read(len, maxcount, read->rd_offset, d_inode(read->rd_fhp->fh_dentry)->i_size); *(p++) = htonl(eof); *(p++) = htonl(maxcount); buf->page_len = maxcount; buf->len += maxcount; xdr->page_ptr += (buf->page_base + maxcount + PAGE_SIZE - 1) / PAGE_SIZE; /* Use rest of head for padding and remaining ops: */ buf->tail[0].iov_base = xdr->p; buf->tail[0].iov_len = 0; xdr->iov = buf->tail; if (maxcount&3) { int pad = 4 - (maxcount&3); *(xdr->p++) = 0; buf->tail[0].iov_base += maxcount&3; buf->tail[0].iov_len = pad; buf->len += pad; } space_left = min_t(int, (void *)xdr->end - (void *)xdr->p, buf->buflen - buf->len); buf->buflen = buf->len + space_left; xdr->end = (__be32 *)((void *)xdr->end + space_left); return 0; } static __be32 nfsd4_encode_readv(struct nfsd4_compoundres *resp, struct nfsd4_read *read, struct file *file, unsigned long maxcount) { struct xdr_stream *xdr = &resp->xdr; u32 eof; int v; int starting_len = xdr->buf->len - 8; long len; int thislen; __be32 nfserr; __be32 tmp; __be32 *p; u32 zzz = 0; int pad; len = maxcount; v = 0; thislen = min_t(long, len, ((void *)xdr->end - (void *)xdr->p)); p = xdr_reserve_space(xdr, (thislen+3)&~3); WARN_ON_ONCE(!p); resp->rqstp->rq_vec[v].iov_base = p; resp->rqstp->rq_vec[v].iov_len = thislen; v++; len -= thislen; while (len) { thislen = min_t(long, len, PAGE_SIZE); p = xdr_reserve_space(xdr, (thislen+3)&~3); WARN_ON_ONCE(!p); resp->rqstp->rq_vec[v].iov_base = p; resp->rqstp->rq_vec[v].iov_len = thislen; v++; len -= thislen; } read->rd_vlen = v; len = maxcount; nfserr = nfsd_readv(file, read->rd_offset, resp->rqstp->rq_vec, read->rd_vlen, &maxcount); if (nfserr) return nfserr; xdr_truncate_encode(xdr, starting_len + 8 + ((maxcount+3)&~3)); eof = nfsd_eof_on_read(len, maxcount, read->rd_offset, d_inode(read->rd_fhp->fh_dentry)->i_size); tmp = htonl(eof); write_bytes_to_xdr_buf(xdr->buf, starting_len , &tmp, 4); tmp = htonl(maxcount); write_bytes_to_xdr_buf(xdr->buf, starting_len + 4, &tmp, 4); pad = (maxcount&3) ? 4 - (maxcount&3) : 0; write_bytes_to_xdr_buf(xdr->buf, starting_len + 8 + maxcount, &zzz, pad); return 0; } static __be32 nfsd4_encode_read(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_read *read) { unsigned long maxcount; struct xdr_stream *xdr = &resp->xdr; struct file *file = read->rd_filp; int starting_len = xdr->buf->len; struct raparms *ra = NULL; __be32 *p; if (nfserr) goto out; p = xdr_reserve_space(xdr, 8); /* eof flag and byte count */ if (!p) { WARN_ON_ONCE(test_bit(RQ_SPLICE_OK, &resp->rqstp->rq_flags)); nfserr = nfserr_resource; goto out; } if (resp->xdr.buf->page_len && test_bit(RQ_SPLICE_OK, &resp->rqstp->rq_flags)) { WARN_ON_ONCE(1); nfserr = nfserr_resource; goto out; } xdr_commit_encode(xdr); maxcount = svc_max_payload(resp->rqstp); maxcount = min_t(unsigned long, maxcount, (xdr->buf->buflen - xdr->buf->len)); maxcount = min_t(unsigned long, maxcount, read->rd_length); if (read->rd_tmp_file) ra = nfsd_init_raparms(file); if (file->f_op->splice_read && test_bit(RQ_SPLICE_OK, &resp->rqstp->rq_flags)) nfserr = nfsd4_encode_splice_read(resp, read, file, maxcount); else nfserr = nfsd4_encode_readv(resp, read, file, maxcount); if (ra) nfsd_put_raparams(file, ra); if (nfserr) xdr_truncate_encode(xdr, starting_len); out: if (file) fput(file); return nfserr; } static __be32 nfsd4_encode_readlink(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_readlink *readlink) { int maxcount; __be32 wire_count; int zero = 0; struct xdr_stream *xdr = &resp->xdr; int length_offset = xdr->buf->len; __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; maxcount = PAGE_SIZE; p = xdr_reserve_space(xdr, maxcount); if (!p) return nfserr_resource; /* * XXX: By default, vfs_readlink() will truncate symlinks if they * would overflow the buffer. Is this kosher in NFSv4? If not, one * easy fix is: if vfs_readlink() precisely fills the buffer, assume * that truncation occurred, and return NFS4ERR_RESOURCE. */ nfserr = nfsd_readlink(readlink->rl_rqstp, readlink->rl_fhp, (char *)p, &maxcount); if (nfserr == nfserr_isdir) nfserr = nfserr_inval; if (nfserr) { xdr_truncate_encode(xdr, length_offset); return nfserr; } wire_count = htonl(maxcount); write_bytes_to_xdr_buf(xdr->buf, length_offset, &wire_count, 4); xdr_truncate_encode(xdr, length_offset + 4 + ALIGN(maxcount, 4)); if (maxcount & 3) write_bytes_to_xdr_buf(xdr->buf, length_offset + 4 + maxcount, &zero, 4 - (maxcount&3)); return 0; } static __be32 nfsd4_encode_readdir(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_readdir *readdir) { int maxcount; int bytes_left; loff_t offset; __be64 wire_offset; struct xdr_stream *xdr = &resp->xdr; int starting_len = xdr->buf->len; __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(xdr, NFS4_VERIFIER_SIZE); if (!p) return nfserr_resource; /* XXX: Following NFSv3, we ignore the READDIR verifier for now. */ *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); resp->xdr.buf->head[0].iov_len = ((char *)resp->xdr.p) - (char *)resp->xdr.buf->head[0].iov_base; /* * Number of bytes left for directory entries allowing for the * final 8 bytes of the readdir and a following failed op: */ bytes_left = xdr->buf->buflen - xdr->buf->len - COMPOUND_ERR_SLACK_SPACE - 8; if (bytes_left < 0) { nfserr = nfserr_resource; goto err_no_verf; } maxcount = min_t(u32, readdir->rd_maxcount, INT_MAX); /* * Note the rfc defines rd_maxcount as the size of the * READDIR4resok structure, which includes the verifier above * and the 8 bytes encoded at the end of this function: */ if (maxcount < 16) { nfserr = nfserr_toosmall; goto err_no_verf; } maxcount = min_t(int, maxcount-16, bytes_left); /* RFC 3530 14.2.24 allows us to ignore dircount when it's 0: */ if (!readdir->rd_dircount) readdir->rd_dircount = INT_MAX; readdir->xdr = xdr; readdir->rd_maxcount = maxcount; readdir->common.err = 0; readdir->cookie_offset = 0; offset = readdir->rd_cookie; nfserr = nfsd_readdir(readdir->rd_rqstp, readdir->rd_fhp, &offset, &readdir->common, nfsd4_encode_dirent); if (nfserr == nfs_ok && readdir->common.err == nfserr_toosmall && xdr->buf->len == starting_len + 8) { /* nothing encoded; which limit did we hit?: */ if (maxcount - 16 < bytes_left) /* It was the fault of rd_maxcount: */ nfserr = nfserr_toosmall; else /* We ran out of buffer space: */ nfserr = nfserr_resource; } if (nfserr) goto err_no_verf; if (readdir->cookie_offset) { wire_offset = cpu_to_be64(offset); write_bytes_to_xdr_buf(xdr->buf, readdir->cookie_offset, &wire_offset, 8); } p = xdr_reserve_space(xdr, 8); if (!p) { WARN_ON_ONCE(1); goto err_no_verf; } *p++ = 0; /* no more entries */ *p++ = htonl(readdir->common.err == nfserr_eof); return 0; err_no_verf: xdr_truncate_encode(xdr, starting_len); return nfserr; } static __be32 nfsd4_encode_remove(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_remove *remove) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, 20); if (!p) return nfserr_resource; p = encode_cinfo(p, &remove->rm_cinfo); } return nfserr; } static __be32 nfsd4_encode_rename(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_rename *rename) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, 40); if (!p) return nfserr_resource; p = encode_cinfo(p, &rename->rn_sinfo); p = encode_cinfo(p, &rename->rn_tinfo); } return nfserr; } static __be32 nfsd4_do_encode_secinfo(struct xdr_stream *xdr, __be32 nfserr, struct svc_export *exp) { u32 i, nflavs, supported; struct exp_flavor_info *flavs; struct exp_flavor_info def_flavs[2]; __be32 *p, *flavorsp; static bool report = true; if (nfserr) goto out; nfserr = nfserr_resource; if (exp->ex_nflavors) { flavs = exp->ex_flavors; nflavs = exp->ex_nflavors; } else { /* Handling of some defaults in absence of real secinfo: */ flavs = def_flavs; if (exp->ex_client->flavour->flavour == RPC_AUTH_UNIX) { nflavs = 2; flavs[0].pseudoflavor = RPC_AUTH_UNIX; flavs[1].pseudoflavor = RPC_AUTH_NULL; } else if (exp->ex_client->flavour->flavour == RPC_AUTH_GSS) { nflavs = 1; flavs[0].pseudoflavor = svcauth_gss_flavor(exp->ex_client); } else { nflavs = 1; flavs[0].pseudoflavor = exp->ex_client->flavour->flavour; } } supported = 0; p = xdr_reserve_space(xdr, 4); if (!p) goto out; flavorsp = p++; /* to be backfilled later */ for (i = 0; i < nflavs; i++) { rpc_authflavor_t pf = flavs[i].pseudoflavor; struct rpcsec_gss_info info; if (rpcauth_get_gssinfo(pf, &info) == 0) { supported++; p = xdr_reserve_space(xdr, 4 + 4 + XDR_LEN(info.oid.len) + 4 + 4); if (!p) goto out; *p++ = cpu_to_be32(RPC_AUTH_GSS); p = xdr_encode_opaque(p, info.oid.data, info.oid.len); *p++ = cpu_to_be32(info.qop); *p++ = cpu_to_be32(info.service); } else if (pf < RPC_AUTH_MAXFLAVOR) { supported++; p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = cpu_to_be32(pf); } else { if (report) pr_warn("NFS: SECINFO: security flavor %u " "is not supported\n", pf); } } if (nflavs != supported) report = false; *flavorsp = htonl(supported); nfserr = 0; out: if (exp) exp_put(exp); return nfserr; } static __be32 nfsd4_encode_secinfo(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_secinfo *secinfo) { struct xdr_stream *xdr = &resp->xdr; return nfsd4_do_encode_secinfo(xdr, nfserr, secinfo->si_exp); } static __be32 nfsd4_encode_secinfo_no_name(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_secinfo_no_name *secinfo) { struct xdr_stream *xdr = &resp->xdr; return nfsd4_do_encode_secinfo(xdr, nfserr, secinfo->sin_exp); } /* * The SETATTR encode routine is special -- it always encodes a bitmap, * regardless of the error status. */ static __be32 nfsd4_encode_setattr(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_setattr *setattr) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; p = xdr_reserve_space(xdr, 16); if (!p) return nfserr_resource; if (nfserr) { *p++ = cpu_to_be32(3); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); } else { *p++ = cpu_to_be32(3); *p++ = cpu_to_be32(setattr->sa_bmval[0]); *p++ = cpu_to_be32(setattr->sa_bmval[1]); *p++ = cpu_to_be32(setattr->sa_bmval[2]); } return nfserr; } static __be32 nfsd4_encode_setclientid(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_setclientid *scd) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, 8 + NFS4_VERIFIER_SIZE); if (!p) return nfserr_resource; p = xdr_encode_opaque_fixed(p, &scd->se_clientid, 8); p = xdr_encode_opaque_fixed(p, &scd->se_confirm, NFS4_VERIFIER_SIZE); } else if (nfserr == nfserr_clid_inuse) { p = xdr_reserve_space(xdr, 8); if (!p) return nfserr_resource; *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); } return nfserr; } static __be32 nfsd4_encode_write(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_write *write) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, 16); if (!p) return nfserr_resource; *p++ = cpu_to_be32(write->wr_bytes_written); *p++ = cpu_to_be32(write->wr_how_written); p = xdr_encode_opaque_fixed(p, write->wr_verifier.data, NFS4_VERIFIER_SIZE); } return nfserr; } static __be32 nfsd4_encode_exchange_id(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_exchange_id *exid) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; char *major_id; char *server_scope; int major_id_sz; int server_scope_sz; int status = 0; uint64_t minor_id = 0; if (nfserr) return nfserr; major_id = utsname()->nodename; major_id_sz = strlen(major_id); server_scope = utsname()->nodename; server_scope_sz = strlen(server_scope); p = xdr_reserve_space(xdr, 8 /* eir_clientid */ + 4 /* eir_sequenceid */ + 4 /* eir_flags */ + 4 /* spr_how */); if (!p) return nfserr_resource; p = xdr_encode_opaque_fixed(p, &exid->clientid, 8); *p++ = cpu_to_be32(exid->seqid); *p++ = cpu_to_be32(exid->flags); *p++ = cpu_to_be32(exid->spa_how); switch (exid->spa_how) { case SP4_NONE: break; case SP4_MACH_CRED: /* spo_must_enforce bitmap: */ status = nfsd4_encode_bitmap(xdr, exid->spo_must_enforce[0], exid->spo_must_enforce[1], exid->spo_must_enforce[2]); if (status) goto out; /* spo_must_allow bitmap: */ status = nfsd4_encode_bitmap(xdr, exid->spo_must_allow[0], exid->spo_must_allow[1], exid->spo_must_allow[2]); if (status) goto out; break; default: WARN_ON_ONCE(1); } p = xdr_reserve_space(xdr, 8 /* so_minor_id */ + 4 /* so_major_id.len */ + (XDR_QUADLEN(major_id_sz) * 4) + 4 /* eir_server_scope.len */ + (XDR_QUADLEN(server_scope_sz) * 4) + 4 /* eir_server_impl_id.count (0) */); if (!p) return nfserr_resource; /* The server_owner struct */ p = xdr_encode_hyper(p, minor_id); /* Minor id */ /* major id */ p = xdr_encode_opaque(p, major_id, major_id_sz); /* Server scope */ p = xdr_encode_opaque(p, server_scope, server_scope_sz); /* Implementation id */ *p++ = cpu_to_be32(0); /* zero length nfs_impl_id4 array */ return 0; out: return status; } static __be32 nfsd4_encode_create_session(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_create_session *sess) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(xdr, 24); if (!p) return nfserr_resource; p = xdr_encode_opaque_fixed(p, sess->sessionid.data, NFS4_MAX_SESSIONID_LEN); *p++ = cpu_to_be32(sess->seqid); *p++ = cpu_to_be32(sess->flags); p = xdr_reserve_space(xdr, 28); if (!p) return nfserr_resource; *p++ = cpu_to_be32(0); /* headerpadsz */ *p++ = cpu_to_be32(sess->fore_channel.maxreq_sz); *p++ = cpu_to_be32(sess->fore_channel.maxresp_sz); *p++ = cpu_to_be32(sess->fore_channel.maxresp_cached); *p++ = cpu_to_be32(sess->fore_channel.maxops); *p++ = cpu_to_be32(sess->fore_channel.maxreqs); *p++ = cpu_to_be32(sess->fore_channel.nr_rdma_attrs); if (sess->fore_channel.nr_rdma_attrs) { p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; *p++ = cpu_to_be32(sess->fore_channel.rdma_attrs); } p = xdr_reserve_space(xdr, 28); if (!p) return nfserr_resource; *p++ = cpu_to_be32(0); /* headerpadsz */ *p++ = cpu_to_be32(sess->back_channel.maxreq_sz); *p++ = cpu_to_be32(sess->back_channel.maxresp_sz); *p++ = cpu_to_be32(sess->back_channel.maxresp_cached); *p++ = cpu_to_be32(sess->back_channel.maxops); *p++ = cpu_to_be32(sess->back_channel.maxreqs); *p++ = cpu_to_be32(sess->back_channel.nr_rdma_attrs); if (sess->back_channel.nr_rdma_attrs) { p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; *p++ = cpu_to_be32(sess->back_channel.rdma_attrs); } return 0; } static __be32 nfsd4_encode_sequence(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_sequence *seq) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(xdr, NFS4_MAX_SESSIONID_LEN + 20); if (!p) return nfserr_resource; p = xdr_encode_opaque_fixed(p, seq->sessionid.data, NFS4_MAX_SESSIONID_LEN); *p++ = cpu_to_be32(seq->seqid); *p++ = cpu_to_be32(seq->slotid); /* Note slotid's are numbered from zero: */ *p++ = cpu_to_be32(seq->maxslots - 1); /* sr_highest_slotid */ *p++ = cpu_to_be32(seq->maxslots - 1); /* sr_target_highest_slotid */ *p++ = cpu_to_be32(seq->status_flags); resp->cstate.data_offset = xdr->buf->len; /* DRC cache data pointer */ return 0; } static __be32 nfsd4_encode_test_stateid(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_test_stateid *test_stateid) { struct xdr_stream *xdr = &resp->xdr; struct nfsd4_test_stateid_id *stateid, *next; __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(xdr, 4 + (4 * test_stateid->ts_num_ids)); if (!p) return nfserr_resource; *p++ = htonl(test_stateid->ts_num_ids); list_for_each_entry_safe(stateid, next, &test_stateid->ts_stateid_list, ts_id_list) { *p++ = stateid->ts_id_status; } return nfserr; } #ifdef CONFIG_NFSD_PNFS static __be32 nfsd4_encode_getdeviceinfo(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_getdeviceinfo *gdev) { struct xdr_stream *xdr = &resp->xdr; const struct nfsd4_layout_ops *ops = nfsd4_layout_ops[gdev->gd_layout_type]; u32 starting_len = xdr->buf->len, needed_len; __be32 *p; dprintk("%s: err %d\n", __func__, be32_to_cpu(nfserr)); if (nfserr) goto out; nfserr = nfserr_resource; p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = cpu_to_be32(gdev->gd_layout_type); /* If maxcount is 0 then just update notifications */ if (gdev->gd_maxcount != 0) { nfserr = ops->encode_getdeviceinfo(xdr, gdev); if (nfserr) { /* * We don't bother to burden the layout drivers with * enforcing gd_maxcount, just tell the client to * come back with a bigger buffer if it's not enough. */ if (xdr->buf->len + 4 > gdev->gd_maxcount) goto toosmall; goto out; } } nfserr = nfserr_resource; if (gdev->gd_notify_types) { p = xdr_reserve_space(xdr, 4 + 4); if (!p) goto out; *p++ = cpu_to_be32(1); /* bitmap length */ *p++ = cpu_to_be32(gdev->gd_notify_types); } else { p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = 0; } nfserr = 0; out: kfree(gdev->gd_device); dprintk("%s: done: %d\n", __func__, be32_to_cpu(nfserr)); return nfserr; toosmall: dprintk("%s: maxcount too small\n", __func__); needed_len = xdr->buf->len + 4 /* notifications */; xdr_truncate_encode(xdr, starting_len); p = xdr_reserve_space(xdr, 4); if (!p) { nfserr = nfserr_resource; } else { *p++ = cpu_to_be32(needed_len); nfserr = nfserr_toosmall; } goto out; } static __be32 nfsd4_encode_layoutget(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_layoutget *lgp) { struct xdr_stream *xdr = &resp->xdr; const struct nfsd4_layout_ops *ops = nfsd4_layout_ops[lgp->lg_layout_type]; __be32 *p; dprintk("%s: err %d\n", __func__, nfserr); if (nfserr) goto out; nfserr = nfserr_resource; p = xdr_reserve_space(xdr, 36 + sizeof(stateid_opaque_t)); if (!p) goto out; *p++ = cpu_to_be32(1); /* we always set return-on-close */ *p++ = cpu_to_be32(lgp->lg_sid.si_generation); p = xdr_encode_opaque_fixed(p, &lgp->lg_sid.si_opaque, sizeof(stateid_opaque_t)); *p++ = cpu_to_be32(1); /* we always return a single layout */ p = xdr_encode_hyper(p, lgp->lg_seg.offset); p = xdr_encode_hyper(p, lgp->lg_seg.length); *p++ = cpu_to_be32(lgp->lg_seg.iomode); *p++ = cpu_to_be32(lgp->lg_layout_type); nfserr = ops->encode_layoutget(xdr, lgp); out: kfree(lgp->lg_content); return nfserr; } static __be32 nfsd4_encode_layoutcommit(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_layoutcommit *lcp) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; *p++ = cpu_to_be32(lcp->lc_size_chg); if (lcp->lc_size_chg) { p = xdr_reserve_space(xdr, 8); if (!p) return nfserr_resource; p = xdr_encode_hyper(p, lcp->lc_newsize); } return nfs_ok; } static __be32 nfsd4_encode_layoutreturn(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_layoutreturn *lrp) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; *p++ = cpu_to_be32(lrp->lrs_present); if (lrp->lrs_present) return nfsd4_encode_stateid(xdr, &lrp->lr_sid); return nfs_ok; } #endif /* CONFIG_NFSD_PNFS */ static __be32 nfsd42_encode_write_res(struct nfsd4_compoundres *resp, struct nfsd42_write_res *write) { __be32 *p; p = xdr_reserve_space(&resp->xdr, 4 + 8 + 4 + NFS4_VERIFIER_SIZE); if (!p) return nfserr_resource; *p++ = cpu_to_be32(0); p = xdr_encode_hyper(p, write->wr_bytes_written); *p++ = cpu_to_be32(write->wr_stable_how); p = xdr_encode_opaque_fixed(p, write->wr_verifier.data, NFS4_VERIFIER_SIZE); return nfs_ok; } static __be32 nfsd4_encode_copy(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_copy *copy) { __be32 *p; if (!nfserr) { nfserr = nfsd42_encode_write_res(resp, &copy->cp_res); if (nfserr) return nfserr; p = xdr_reserve_space(&resp->xdr, 4 + 4); *p++ = cpu_to_be32(copy->cp_consecutive); *p++ = cpu_to_be32(copy->cp_synchronous); } return nfserr; } static __be32 nfsd4_encode_seek(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_seek *seek) { __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(&resp->xdr, 4 + 8); *p++ = cpu_to_be32(seek->seek_eof); p = xdr_encode_hyper(p, seek->seek_pos); return nfserr; } static __be32 nfsd4_encode_noop(struct nfsd4_compoundres *resp, __be32 nfserr, void *p) { return nfserr; } typedef __be32(* nfsd4_enc)(struct nfsd4_compoundres *, __be32, void *); /* * Note: nfsd4_enc_ops vector is shared for v4.0 and v4.1 * since we don't need to filter out obsolete ops as this is * done in the decoding phase. */ static nfsd4_enc nfsd4_enc_ops[] = { [OP_ACCESS] = (nfsd4_enc)nfsd4_encode_access, [OP_CLOSE] = (nfsd4_enc)nfsd4_encode_close, [OP_COMMIT] = (nfsd4_enc)nfsd4_encode_commit, [OP_CREATE] = (nfsd4_enc)nfsd4_encode_create, [OP_DELEGPURGE] = (nfsd4_enc)nfsd4_encode_noop, [OP_DELEGRETURN] = (nfsd4_enc)nfsd4_encode_noop, [OP_GETATTR] = (nfsd4_enc)nfsd4_encode_getattr, [OP_GETFH] = (nfsd4_enc)nfsd4_encode_getfh, [OP_LINK] = (nfsd4_enc)nfsd4_encode_link, [OP_LOCK] = (nfsd4_enc)nfsd4_encode_lock, [OP_LOCKT] = (nfsd4_enc)nfsd4_encode_lockt, [OP_LOCKU] = (nfsd4_enc)nfsd4_encode_locku, [OP_LOOKUP] = (nfsd4_enc)nfsd4_encode_noop, [OP_LOOKUPP] = (nfsd4_enc)nfsd4_encode_noop, [OP_NVERIFY] = (nfsd4_enc)nfsd4_encode_noop, [OP_OPEN] = (nfsd4_enc)nfsd4_encode_open, [OP_OPENATTR] = (nfsd4_enc)nfsd4_encode_noop, [OP_OPEN_CONFIRM] = (nfsd4_enc)nfsd4_encode_open_confirm, [OP_OPEN_DOWNGRADE] = (nfsd4_enc)nfsd4_encode_open_downgrade, [OP_PUTFH] = (nfsd4_enc)nfsd4_encode_noop, [OP_PUTPUBFH] = (nfsd4_enc)nfsd4_encode_noop, [OP_PUTROOTFH] = (nfsd4_enc)nfsd4_encode_noop, [OP_READ] = (nfsd4_enc)nfsd4_encode_read, [OP_READDIR] = (nfsd4_enc)nfsd4_encode_readdir, [OP_READLINK] = (nfsd4_enc)nfsd4_encode_readlink, [OP_REMOVE] = (nfsd4_enc)nfsd4_encode_remove, [OP_RENAME] = (nfsd4_enc)nfsd4_encode_rename, [OP_RENEW] = (nfsd4_enc)nfsd4_encode_noop, [OP_RESTOREFH] = (nfsd4_enc)nfsd4_encode_noop, [OP_SAVEFH] = (nfsd4_enc)nfsd4_encode_noop, [OP_SECINFO] = (nfsd4_enc)nfsd4_encode_secinfo, [OP_SETATTR] = (nfsd4_enc)nfsd4_encode_setattr, [OP_SETCLIENTID] = (nfsd4_enc)nfsd4_encode_setclientid, [OP_SETCLIENTID_CONFIRM] = (nfsd4_enc)nfsd4_encode_noop, [OP_VERIFY] = (nfsd4_enc)nfsd4_encode_noop, [OP_WRITE] = (nfsd4_enc)nfsd4_encode_write, [OP_RELEASE_LOCKOWNER] = (nfsd4_enc)nfsd4_encode_noop, /* NFSv4.1 operations */ [OP_BACKCHANNEL_CTL] = (nfsd4_enc)nfsd4_encode_noop, [OP_BIND_CONN_TO_SESSION] = (nfsd4_enc)nfsd4_encode_bind_conn_to_session, [OP_EXCHANGE_ID] = (nfsd4_enc)nfsd4_encode_exchange_id, [OP_CREATE_SESSION] = (nfsd4_enc)nfsd4_encode_create_session, [OP_DESTROY_SESSION] = (nfsd4_enc)nfsd4_encode_noop, [OP_FREE_STATEID] = (nfsd4_enc)nfsd4_encode_noop, [OP_GET_DIR_DELEGATION] = (nfsd4_enc)nfsd4_encode_noop, #ifdef CONFIG_NFSD_PNFS [OP_GETDEVICEINFO] = (nfsd4_enc)nfsd4_encode_getdeviceinfo, [OP_GETDEVICELIST] = (nfsd4_enc)nfsd4_encode_noop, [OP_LAYOUTCOMMIT] = (nfsd4_enc)nfsd4_encode_layoutcommit, [OP_LAYOUTGET] = (nfsd4_enc)nfsd4_encode_layoutget, [OP_LAYOUTRETURN] = (nfsd4_enc)nfsd4_encode_layoutreturn, #else [OP_GETDEVICEINFO] = (nfsd4_enc)nfsd4_encode_noop, [OP_GETDEVICELIST] = (nfsd4_enc)nfsd4_encode_noop, [OP_LAYOUTCOMMIT] = (nfsd4_enc)nfsd4_encode_noop, [OP_LAYOUTGET] = (nfsd4_enc)nfsd4_encode_noop, [OP_LAYOUTRETURN] = (nfsd4_enc)nfsd4_encode_noop, #endif [OP_SECINFO_NO_NAME] = (nfsd4_enc)nfsd4_encode_secinfo_no_name, [OP_SEQUENCE] = (nfsd4_enc)nfsd4_encode_sequence, [OP_SET_SSV] = (nfsd4_enc)nfsd4_encode_noop, [OP_TEST_STATEID] = (nfsd4_enc)nfsd4_encode_test_stateid, [OP_WANT_DELEGATION] = (nfsd4_enc)nfsd4_encode_noop, [OP_DESTROY_CLIENTID] = (nfsd4_enc)nfsd4_encode_noop, [OP_RECLAIM_COMPLETE] = (nfsd4_enc)nfsd4_encode_noop, /* NFSv4.2 operations */ [OP_ALLOCATE] = (nfsd4_enc)nfsd4_encode_noop, [OP_COPY] = (nfsd4_enc)nfsd4_encode_copy, [OP_COPY_NOTIFY] = (nfsd4_enc)nfsd4_encode_noop, [OP_DEALLOCATE] = (nfsd4_enc)nfsd4_encode_noop, [OP_IO_ADVISE] = (nfsd4_enc)nfsd4_encode_noop, [OP_LAYOUTERROR] = (nfsd4_enc)nfsd4_encode_noop, [OP_LAYOUTSTATS] = (nfsd4_enc)nfsd4_encode_noop, [OP_OFFLOAD_CANCEL] = (nfsd4_enc)nfsd4_encode_noop, [OP_OFFLOAD_STATUS] = (nfsd4_enc)nfsd4_encode_noop, [OP_READ_PLUS] = (nfsd4_enc)nfsd4_encode_noop, [OP_SEEK] = (nfsd4_enc)nfsd4_encode_seek, [OP_WRITE_SAME] = (nfsd4_enc)nfsd4_encode_noop, [OP_CLONE] = (nfsd4_enc)nfsd4_encode_noop, }; /* * Calculate whether we still have space to encode repsize bytes. * There are two considerations: * - For NFS versions >=4.1, the size of the reply must stay within * session limits * - For all NFS versions, we must stay within limited preallocated * buffer space. * * This is called before the operation is processed, so can only provide * an upper estimate. For some nonidempotent operations (such as * getattr), it's not necessarily a problem if that estimate is wrong, * as we can fail it after processing without significant side effects. */ __be32 nfsd4_check_resp_size(struct nfsd4_compoundres *resp, u32 respsize) { struct xdr_buf *buf = &resp->rqstp->rq_res; struct nfsd4_slot *slot = resp->cstate.slot; if (buf->len + respsize <= buf->buflen) return nfs_ok; if (!nfsd4_has_session(&resp->cstate)) return nfserr_resource; if (slot->sl_flags & NFSD4_SLOT_CACHETHIS) { WARN_ON_ONCE(1); return nfserr_rep_too_big_to_cache; } return nfserr_rep_too_big; } void nfsd4_encode_operation(struct nfsd4_compoundres *resp, struct nfsd4_op *op) { struct xdr_stream *xdr = &resp->xdr; struct nfs4_stateowner *so = resp->cstate.replay_owner; struct svc_rqst *rqstp = resp->rqstp; int post_err_offset; nfsd4_enc encoder; __be32 *p; p = xdr_reserve_space(xdr, 8); if (!p) { WARN_ON_ONCE(1); return; } *p++ = cpu_to_be32(op->opnum); post_err_offset = xdr->buf->len; if (op->opnum == OP_ILLEGAL) goto status; BUG_ON(op->opnum < 0 || op->opnum >= ARRAY_SIZE(nfsd4_enc_ops) || !nfsd4_enc_ops[op->opnum]); encoder = nfsd4_enc_ops[op->opnum]; op->status = encoder(resp, op->status, &op->u); xdr_commit_encode(xdr); /* nfsd4_check_resp_size guarantees enough room for error status */ if (!op->status) { int space_needed = 0; if (!nfsd4_last_compound_op(rqstp)) space_needed = COMPOUND_ERR_SLACK_SPACE; op->status = nfsd4_check_resp_size(resp, space_needed); } if (op->status == nfserr_resource && nfsd4_has_session(&resp->cstate)) { struct nfsd4_slot *slot = resp->cstate.slot; if (slot->sl_flags & NFSD4_SLOT_CACHETHIS) op->status = nfserr_rep_too_big_to_cache; else op->status = nfserr_rep_too_big; } if (op->status == nfserr_resource || op->status == nfserr_rep_too_big || op->status == nfserr_rep_too_big_to_cache) { /* * The operation may have already been encoded or * partially encoded. No op returns anything additional * in the case of one of these three errors, so we can * just truncate back to after the status. But it's a * bug if we had to do this on a non-idempotent op: */ warn_on_nonidempotent_op(op); xdr_truncate_encode(xdr, post_err_offset); } if (so) { int len = xdr->buf->len - post_err_offset; so->so_replay.rp_status = op->status; so->so_replay.rp_buflen = len; read_bytes_from_xdr_buf(xdr->buf, post_err_offset, so->so_replay.rp_buf, len); } status: /* Note that op->status is already in network byte order: */ write_bytes_to_xdr_buf(xdr->buf, post_err_offset - 4, &op->status, 4); } /* * Encode the reply stored in the stateowner reply cache * * XDR note: do not encode rp->rp_buflen: the buffer contains the * previously sent already encoded operation. */ void nfsd4_encode_replay(struct xdr_stream *xdr, struct nfsd4_op *op) { __be32 *p; struct nfs4_replay *rp = op->replay; BUG_ON(!rp); p = xdr_reserve_space(xdr, 8 + rp->rp_buflen); if (!p) { WARN_ON_ONCE(1); return; } *p++ = cpu_to_be32(op->opnum); *p++ = rp->rp_status; /* already xdr'ed */ p = xdr_encode_opaque_fixed(p, rp->rp_buf, rp->rp_buflen); } int nfs4svc_encode_voidres(struct svc_rqst *rqstp, __be32 *p, void *dummy) { return xdr_ressize_check(rqstp, p); } int nfsd4_release_compoundargs(void *rq, __be32 *p, void *resp) { struct svc_rqst *rqstp = rq; struct nfsd4_compoundargs *args = rqstp->rq_argp; if (args->ops != args->iops) { kfree(args->ops); args->ops = args->iops; } kfree(args->tmpp); args->tmpp = NULL; while (args->to_free) { struct svcxdr_tmpbuf *tb = args->to_free; args->to_free = tb->next; kfree(tb); } return 1; } int nfs4svc_decode_compoundargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd4_compoundargs *args) { if (rqstp->rq_arg.head[0].iov_len % 4) { /* client is nuts */ dprintk("%s: compound not properly padded! (peeraddr=%pISc xid=0x%x)", __func__, svc_addr(rqstp), be32_to_cpu(rqstp->rq_xid)); return 0; } args->p = p; args->end = rqstp->rq_arg.head[0].iov_base + rqstp->rq_arg.head[0].iov_len; args->pagelist = rqstp->rq_arg.pages; args->pagelen = rqstp->rq_arg.page_len; args->tmpp = NULL; args->to_free = NULL; args->ops = args->iops; args->rqstp = rqstp; return !nfsd4_decode_compound(args); } int nfs4svc_encode_compoundres(struct svc_rqst *rqstp, __be32 *p, struct nfsd4_compoundres *resp) { /* * All that remains is to write the tag and operation count... */ struct xdr_buf *buf = resp->xdr.buf; WARN_ON_ONCE(buf->len != buf->head[0].iov_len + buf->page_len + buf->tail[0].iov_len); rqstp->rq_next_page = resp->xdr.page_ptr + 1; p = resp->tagp; *p++ = htonl(resp->taglen); memcpy(p, resp->tag, resp->taglen); p += XDR_QUADLEN(resp->taglen); *p++ = htonl(resp->opcnt); nfsd4_sequence_done(resp); return 1; } /* * Local variables: * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-129/c/bad_3336_0
crossvul-cpp_data_good_705_0
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/avassert.h" #include "libavutil/pixfmt.h" #include "cbs.h" #include "cbs_internal.h" #include "cbs_av1.h" #include "internal.h" static int cbs_av1_read_uvlc(CodedBitstreamContext *ctx, GetBitContext *gbc, const char *name, uint32_t *write_to, uint32_t range_min, uint32_t range_max) { uint32_t zeroes, bits_value, value; int position; if (ctx->trace_enable) position = get_bits_count(gbc); zeroes = 0; while (1) { if (get_bits_left(gbc) < 1) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid uvlc code at " "%s: bitstream ended.\n", name); return AVERROR_INVALIDDATA; } if (get_bits1(gbc)) break; ++zeroes; } if (zeroes >= 32) { value = MAX_UINT_BITS(32); } else { if (get_bits_left(gbc) < zeroes) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid uvlc code at " "%s: bitstream ended.\n", name); return AVERROR_INVALIDDATA; } bits_value = get_bits_long(gbc, zeroes); value = bits_value + (UINT32_C(1) << zeroes) - 1; } if (ctx->trace_enable) { char bits[65]; int i, j, k; if (zeroes >= 32) { while (zeroes > 32) { k = FFMIN(zeroes - 32, 32); for (i = 0; i < k; i++) bits[i] = '0'; bits[i] = 0; ff_cbs_trace_syntax_element(ctx, position, name, NULL, bits, 0); zeroes -= k; position += k; } } for (i = 0; i < zeroes; i++) bits[i] = '0'; bits[i++] = '1'; if (zeroes < 32) { for (j = 0; j < zeroes; j++) bits[i++] = (bits_value >> (zeroes - j - 1) & 1) ? '1' : '0'; } bits[i] = 0; ff_cbs_trace_syntax_element(ctx, position, name, NULL, bits, value); } if (value < range_min || value > range_max) { av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: " "%"PRIu32", but must be in [%"PRIu32",%"PRIu32"].\n", name, value, range_min, range_max); return AVERROR_INVALIDDATA; } *write_to = value; return 0; } static int cbs_av1_write_uvlc(CodedBitstreamContext *ctx, PutBitContext *pbc, const char *name, uint32_t value, uint32_t range_min, uint32_t range_max) { uint32_t v; int position, zeroes; if (value < range_min || value > range_max) { av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: " "%"PRIu32", but must be in [%"PRIu32",%"PRIu32"].\n", name, value, range_min, range_max); return AVERROR_INVALIDDATA; } if (ctx->trace_enable) position = put_bits_count(pbc); if (value == 0) { zeroes = 0; put_bits(pbc, 1, 1); } else { zeroes = av_log2(value + 1); v = value - (1 << zeroes) + 1; put_bits(pbc, zeroes + 1, 1); put_bits(pbc, zeroes, v); } if (ctx->trace_enable) { char bits[65]; int i, j; i = 0; for (j = 0; j < zeroes; j++) bits[i++] = '0'; bits[i++] = '1'; for (j = 0; j < zeroes; j++) bits[i++] = (v >> (zeroes - j - 1) & 1) ? '1' : '0'; bits[i++] = 0; ff_cbs_trace_syntax_element(ctx, position, name, NULL, bits, value); } return 0; } static int cbs_av1_read_leb128(CodedBitstreamContext *ctx, GetBitContext *gbc, const char *name, uint64_t *write_to) { uint64_t value; int position, err, i; if (ctx->trace_enable) position = get_bits_count(gbc); value = 0; for (i = 0; i < 8; i++) { int subscript[2] = { 1, i }; uint32_t byte; err = ff_cbs_read_unsigned(ctx, gbc, 8, "leb128_byte[i]", subscript, &byte, 0x00, 0xff); if (err < 0) return err; value |= (uint64_t)(byte & 0x7f) << (i * 7); if (!(byte & 0x80)) break; } if (ctx->trace_enable) ff_cbs_trace_syntax_element(ctx, position, name, NULL, "", value); *write_to = value; return 0; } static int cbs_av1_write_leb128(CodedBitstreamContext *ctx, PutBitContext *pbc, const char *name, uint64_t value) { int position, err, len, i; uint8_t byte; len = (av_log2(value) + 7) / 7; if (ctx->trace_enable) position = put_bits_count(pbc); for (i = 0; i < len; i++) { int subscript[2] = { 1, i }; byte = value >> (7 * i) & 0x7f; if (i < len - 1) byte |= 0x80; err = ff_cbs_write_unsigned(ctx, pbc, 8, "leb128_byte[i]", subscript, byte, 0x00, 0xff); if (err < 0) return err; } if (ctx->trace_enable) ff_cbs_trace_syntax_element(ctx, position, name, NULL, "", value); return 0; } static int cbs_av1_read_su(CodedBitstreamContext *ctx, GetBitContext *gbc, int width, const char *name, const int *subscripts, int32_t *write_to) { int position; int32_t value; if (ctx->trace_enable) position = get_bits_count(gbc); if (get_bits_left(gbc) < width) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid signed value at " "%s: bitstream ended.\n", name); return AVERROR_INVALIDDATA; } value = get_sbits(gbc, width); if (ctx->trace_enable) { char bits[33]; int i; for (i = 0; i < width; i++) bits[i] = value & (1 << (width - i - 1)) ? '1' : '0'; bits[i] = 0; ff_cbs_trace_syntax_element(ctx, position, name, subscripts, bits, value); } *write_to = value; return 0; } static int cbs_av1_write_su(CodedBitstreamContext *ctx, PutBitContext *pbc, int width, const char *name, const int *subscripts, int32_t value) { if (put_bits_left(pbc) < width) return AVERROR(ENOSPC); if (ctx->trace_enable) { char bits[33]; int i; for (i = 0; i < width; i++) bits[i] = value & (1 << (width - i - 1)) ? '1' : '0'; bits[i] = 0; ff_cbs_trace_syntax_element(ctx, put_bits_count(pbc), name, subscripts, bits, value); } put_sbits(pbc, width, value); return 0; } static int cbs_av1_read_ns(CodedBitstreamContext *ctx, GetBitContext *gbc, uint32_t n, const char *name, const int *subscripts, uint32_t *write_to) { uint32_t w, m, v, extra_bit, value; int position; av_assert0(n > 0); if (ctx->trace_enable) position = get_bits_count(gbc); w = av_log2(n) + 1; m = (1 << w) - n; if (get_bits_left(gbc) < w) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid non-symmetric value at " "%s: bitstream ended.\n", name); return AVERROR_INVALIDDATA; } if (w - 1 > 0) v = get_bits(gbc, w - 1); else v = 0; if (v < m) { value = v; } else { extra_bit = get_bits1(gbc); value = (v << 1) - m + extra_bit; } if (ctx->trace_enable) { char bits[33]; int i; for (i = 0; i < w - 1; i++) bits[i] = (v >> i & 1) ? '1' : '0'; if (v >= m) bits[i++] = extra_bit ? '1' : '0'; bits[i] = 0; ff_cbs_trace_syntax_element(ctx, position, name, subscripts, bits, value); } *write_to = value; return 0; } static int cbs_av1_write_ns(CodedBitstreamContext *ctx, PutBitContext *pbc, uint32_t n, const char *name, const int *subscripts, uint32_t value) { uint32_t w, m, v, extra_bit; int position; if (value > n) { av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: " "%"PRIu32", but must be in [0,%"PRIu32"].\n", name, value, n); return AVERROR_INVALIDDATA; } if (ctx->trace_enable) position = put_bits_count(pbc); w = av_log2(n) + 1; m = (1 << w) - n; if (put_bits_left(pbc) < w) return AVERROR(ENOSPC); if (value < m) { v = value; put_bits(pbc, w - 1, v); } else { v = m + ((value - m) >> 1); extra_bit = (value - m) & 1; put_bits(pbc, w - 1, v); put_bits(pbc, 1, extra_bit); } if (ctx->trace_enable) { char bits[33]; int i; for (i = 0; i < w - 1; i++) bits[i] = (v >> i & 1) ? '1' : '0'; if (value >= m) bits[i++] = extra_bit ? '1' : '0'; bits[i] = 0; ff_cbs_trace_syntax_element(ctx, position, name, subscripts, bits, value); } return 0; } static int cbs_av1_read_increment(CodedBitstreamContext *ctx, GetBitContext *gbc, uint32_t range_min, uint32_t range_max, const char *name, uint32_t *write_to) { uint32_t value; int position, i; char bits[33]; av_assert0(range_min <= range_max && range_max - range_min < sizeof(bits) - 1); if (ctx->trace_enable) position = get_bits_count(gbc); for (i = 0, value = range_min; value < range_max;) { if (get_bits_left(gbc) < 1) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid increment value at " "%s: bitstream ended.\n", name); return AVERROR_INVALIDDATA; } if (get_bits1(gbc)) { bits[i++] = '1'; ++value; } else { bits[i++] = '0'; break; } } if (ctx->trace_enable) { bits[i] = 0; ff_cbs_trace_syntax_element(ctx, position, name, NULL, bits, value); } *write_to = value; return 0; } static int cbs_av1_write_increment(CodedBitstreamContext *ctx, PutBitContext *pbc, uint32_t range_min, uint32_t range_max, const char *name, uint32_t value) { int len; av_assert0(range_min <= range_max && range_max - range_min < 32); if (value < range_min || value > range_max) { av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: " "%"PRIu32", but must be in [%"PRIu32",%"PRIu32"].\n", name, value, range_min, range_max); return AVERROR_INVALIDDATA; } if (value == range_max) len = range_max - range_min; else len = value - range_min + 1; if (put_bits_left(pbc) < len) return AVERROR(ENOSPC); if (ctx->trace_enable) { char bits[33]; int i; for (i = 0; i < len; i++) { if (range_min + i == value) bits[i] = '0'; else bits[i] = '1'; } bits[i] = 0; ff_cbs_trace_syntax_element(ctx, put_bits_count(pbc), name, NULL, bits, value); } if (len > 0) put_bits(pbc, len, (1 << len) - 1 - (value != range_max)); return 0; } static int cbs_av1_read_subexp(CodedBitstreamContext *ctx, GetBitContext *gbc, uint32_t range_max, const char *name, const int *subscripts, uint32_t *write_to) { uint32_t value; int position, err; uint32_t max_len, len, range_offset, range_bits; if (ctx->trace_enable) position = get_bits_count(gbc); av_assert0(range_max > 0); max_len = av_log2(range_max - 1) - 3; err = cbs_av1_read_increment(ctx, gbc, 0, max_len, "subexp_more_bits", &len); if (err < 0) return err; if (len) { range_bits = 2 + len; range_offset = 1 << range_bits; } else { range_bits = 3; range_offset = 0; } if (len < max_len) { err = ff_cbs_read_unsigned(ctx, gbc, range_bits, "subexp_bits", NULL, &value, 0, MAX_UINT_BITS(range_bits)); if (err < 0) return err; } else { err = cbs_av1_read_ns(ctx, gbc, range_max - range_offset, "subexp_final_bits", NULL, &value); if (err < 0) return err; } value += range_offset; if (ctx->trace_enable) ff_cbs_trace_syntax_element(ctx, position, name, subscripts, "", value); *write_to = value; return err; } static int cbs_av1_write_subexp(CodedBitstreamContext *ctx, PutBitContext *pbc, uint32_t range_max, const char *name, const int *subscripts, uint32_t value) { int position, err; uint32_t max_len, len, range_offset, range_bits; if (value > range_max) { av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: " "%"PRIu32", but must be in [0,%"PRIu32"].\n", name, value, range_max); return AVERROR_INVALIDDATA; } if (ctx->trace_enable) position = put_bits_count(pbc); av_assert0(range_max > 0); max_len = av_log2(range_max - 1) - 3; if (value < 8) { range_bits = 3; range_offset = 0; len = 0; } else { range_bits = av_log2(value); len = range_bits - 2; if (len > max_len) { // The top bin is combined with the one below it. av_assert0(len == max_len + 1); --range_bits; len = max_len; } range_offset = 1 << range_bits; } err = cbs_av1_write_increment(ctx, pbc, 0, max_len, "subexp_more_bits", len); if (err < 0) return err; if (len < max_len) { err = ff_cbs_write_unsigned(ctx, pbc, range_bits, "subexp_bits", NULL, value - range_offset, 0, MAX_UINT_BITS(range_bits)); if (err < 0) return err; } else { err = cbs_av1_write_ns(ctx, pbc, range_max - range_offset, "subexp_final_bits", NULL, value - range_offset); if (err < 0) return err; } if (ctx->trace_enable) ff_cbs_trace_syntax_element(ctx, position, name, subscripts, "", value); return err; } static int cbs_av1_tile_log2(int blksize, int target) { int k; for (k = 0; (blksize << k) < target; k++); return k; } static int cbs_av1_get_relative_dist(const AV1RawSequenceHeader *seq, unsigned int a, unsigned int b) { unsigned int diff, m; if (!seq->enable_order_hint) return 0; diff = a - b; m = 1 << seq->order_hint_bits_minus_1; diff = (diff & (m - 1)) - (diff & m); return diff; } #define HEADER(name) do { \ ff_cbs_trace_header(ctx, name); \ } while (0) #define CHECK(call) do { \ err = (call); \ if (err < 0) \ return err; \ } while (0) #define FUNC_NAME(rw, codec, name) cbs_ ## codec ## _ ## rw ## _ ## name #define FUNC_AV1(rw, name) FUNC_NAME(rw, av1, name) #define FUNC(name) FUNC_AV1(READWRITE, name) #define SUBSCRIPTS(subs, ...) (subs > 0 ? ((int[subs + 1]){ subs, __VA_ARGS__ }) : NULL) #define fb(width, name) \ xf(width, name, current->name, 0, MAX_UINT_BITS(width), 0) #define fc(width, name, range_min, range_max) \ xf(width, name, current->name, range_min, range_max, 0) #define flag(name) fb(1, name) #define su(width, name) \ xsu(width, name, current->name, 0) #define fbs(width, name, subs, ...) \ xf(width, name, current->name, 0, MAX_UINT_BITS(width), subs, __VA_ARGS__) #define fcs(width, name, range_min, range_max, subs, ...) \ xf(width, name, current->name, range_min, range_max, subs, __VA_ARGS__) #define flags(name, subs, ...) \ xf(1, name, current->name, 0, 1, subs, __VA_ARGS__) #define sus(width, name, subs, ...) \ xsu(width, name, current->name, subs, __VA_ARGS__) #define fixed(width, name, value) do { \ av_unused uint32_t fixed_value = value; \ xf(width, name, fixed_value, value, value, 0); \ } while (0) #define READ #define READWRITE read #define RWContext GetBitContext #define xf(width, name, var, range_min, range_max, subs, ...) do { \ uint32_t value = range_min; \ CHECK(ff_cbs_read_unsigned(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ &value, range_min, range_max)); \ var = value; \ } while (0) #define xsu(width, name, var, subs, ...) do { \ int32_t value = 0; \ CHECK(cbs_av1_read_su(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), &value)); \ var = value; \ } while (0) #define uvlc(name, range_min, range_max) do { \ uint32_t value = range_min; \ CHECK(cbs_av1_read_uvlc(ctx, rw, #name, \ &value, range_min, range_max)); \ current->name = value; \ } while (0) #define ns(max_value, name, subs, ...) do { \ uint32_t value = 0; \ CHECK(cbs_av1_read_ns(ctx, rw, max_value, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), &value)); \ current->name = value; \ } while (0) #define increment(name, min, max) do { \ uint32_t value = 0; \ CHECK(cbs_av1_read_increment(ctx, rw, min, max, #name, &value)); \ current->name = value; \ } while (0) #define subexp(name, max, subs, ...) do { \ uint32_t value = 0; \ CHECK(cbs_av1_read_subexp(ctx, rw, max, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), &value)); \ current->name = value; \ } while (0) #define delta_q(name) do { \ uint8_t delta_coded; \ int8_t delta_q; \ xf(1, name.delta_coded, delta_coded, 0, 1, 0); \ if (delta_coded) \ xsu(1 + 6, name.delta_q, delta_q, 0); \ else \ delta_q = 0; \ current->name = delta_q; \ } while (0) #define leb128(name) do { \ uint64_t value = 0; \ CHECK(cbs_av1_read_leb128(ctx, rw, #name, &value)); \ current->name = value; \ } while (0) #define infer(name, value) do { \ current->name = value; \ } while (0) #define byte_alignment(rw) (get_bits_count(rw) % 8) #include "cbs_av1_syntax_template.c" #undef READ #undef READWRITE #undef RWContext #undef xf #undef xsu #undef uvlc #undef leb128 #undef ns #undef increment #undef subexp #undef delta_q #undef leb128 #undef infer #undef byte_alignment #define WRITE #define READWRITE write #define RWContext PutBitContext #define xf(width, name, var, range_min, range_max, subs, ...) do { \ CHECK(ff_cbs_write_unsigned(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ var, range_min, range_max)); \ } while (0) #define xsu(width, name, var, subs, ...) do { \ CHECK(cbs_av1_write_su(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), var)); \ } while (0) #define uvlc(name, range_min, range_max) do { \ CHECK(cbs_av1_write_uvlc(ctx, rw, #name, current->name, \ range_min, range_max)); \ } while (0) #define ns(max_value, name, subs, ...) do { \ CHECK(cbs_av1_write_ns(ctx, rw, max_value, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ current->name)); \ } while (0) #define increment(name, min, max) do { \ CHECK(cbs_av1_write_increment(ctx, rw, min, max, #name, \ current->name)); \ } while (0) #define subexp(name, max, subs, ...) do { \ CHECK(cbs_av1_write_subexp(ctx, rw, max, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ current->name)); \ } while (0) #define delta_q(name) do { \ xf(1, name.delta_coded, current->name != 0, 0, 1, 0); \ if (current->name) \ xsu(1 + 6, name.delta_q, current->name, 0); \ } while (0) #define leb128(name) do { \ CHECK(cbs_av1_write_leb128(ctx, rw, #name, current->name)); \ } while (0) #define infer(name, value) do { \ if (current->name != (value)) { \ av_log(ctx->log_ctx, AV_LOG_WARNING, "Warning: " \ "%s does not match inferred value: " \ "%"PRId64", but should be %"PRId64".\n", \ #name, (int64_t)current->name, (int64_t)(value)); \ } \ } while (0) #define byte_alignment(rw) (put_bits_count(rw) % 8) #include "cbs_av1_syntax_template.c" #undef READ #undef READWRITE #undef RWContext #undef xf #undef xsu #undef uvlc #undef leb128 #undef ns #undef increment #undef subexp #undef delta_q #undef infer #undef byte_alignment static int cbs_av1_split_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag, int header) { GetBitContext gbc; uint8_t *data; size_t size; uint64_t obu_length; int pos, err, trace; // Don't include this parsing in trace output. trace = ctx->trace_enable; ctx->trace_enable = 0; data = frag->data; size = frag->data_size; if (INT_MAX / 8 < size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid fragment: " "too large (%"SIZE_SPECIFIER" bytes).\n", size); err = AVERROR_INVALIDDATA; goto fail; } while (size > 0) { AV1RawOBUHeader header; uint64_t obu_size; init_get_bits(&gbc, data, 8 * size); err = cbs_av1_read_obu_header(ctx, &gbc, &header); if (err < 0) goto fail; if (get_bits_left(&gbc) < 8) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid OBU: fragment " "too short (%"SIZE_SPECIFIER" bytes).\n", size); err = AVERROR_INVALIDDATA; goto fail; } if (header.obu_has_size_field) { err = cbs_av1_read_leb128(ctx, &gbc, "obu_size", &obu_size); if (err < 0) goto fail; } else obu_size = size - 1 - header.obu_extension_flag; pos = get_bits_count(&gbc); av_assert0(pos % 8 == 0 && pos / 8 <= size); obu_length = pos / 8 + obu_size; if (size < obu_length) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid OBU length: " "%"PRIu64", but only %"SIZE_SPECIFIER" bytes remaining in fragment.\n", obu_length, size); err = AVERROR_INVALIDDATA; goto fail; } err = ff_cbs_insert_unit_data(ctx, frag, -1, header.obu_type, data, obu_length, frag->data_ref); if (err < 0) goto fail; data += obu_length; size -= obu_length; } err = 0; fail: ctx->trace_enable = trace; return err; } static void cbs_av1_free_tile_data(AV1RawTileData *td) { av_buffer_unref(&td->data_ref); } static void cbs_av1_free_metadata(AV1RawMetadata *md) { switch (md->metadata_type) { case AV1_METADATA_TYPE_ITUT_T35: av_buffer_unref(&md->metadata.itut_t35.payload_ref); break; } } static void cbs_av1_free_obu(void *unit, uint8_t *content) { AV1RawOBU *obu = (AV1RawOBU*)content; switch (obu->header.obu_type) { case AV1_OBU_TILE_GROUP: cbs_av1_free_tile_data(&obu->obu.tile_group.tile_data); break; case AV1_OBU_FRAME: cbs_av1_free_tile_data(&obu->obu.frame.tile_group.tile_data); break; case AV1_OBU_TILE_LIST: cbs_av1_free_tile_data(&obu->obu.tile_list.tile_data); break; case AV1_OBU_METADATA: cbs_av1_free_metadata(&obu->obu.metadata); break; } av_freep(&obu); } static int cbs_av1_ref_tile_data(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, GetBitContext *gbc, AV1RawTileData *td) { int pos; pos = get_bits_count(gbc); if (pos >= 8 * unit->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Bitstream ended before " "any data in tile group (%d bits read).\n", pos); return AVERROR_INVALIDDATA; } // Must be byte-aligned at this point. av_assert0(pos % 8 == 0); td->data_ref = av_buffer_ref(unit->data_ref); if (!td->data_ref) return AVERROR(ENOMEM); td->data = unit->data + pos / 8; td->data_size = unit->data_size - pos / 8; return 0; } static int cbs_av1_read_unit(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit) { CodedBitstreamAV1Context *priv = ctx->priv_data; AV1RawOBU *obu; GetBitContext gbc; int err, start_pos, end_pos; err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*obu), &cbs_av1_free_obu); if (err < 0) return err; obu = unit->content; err = init_get_bits(&gbc, unit->data, 8 * unit->data_size); if (err < 0) return err; err = cbs_av1_read_obu_header(ctx, &gbc, &obu->header); if (err < 0) return err; av_assert0(obu->header.obu_type == unit->type); if (obu->header.obu_has_size_field) { uint64_t obu_size; err = cbs_av1_read_leb128(ctx, &gbc, "obu_size", &obu_size); if (err < 0) return err; obu->obu_size = obu_size; } else { if (unit->data_size < 1 + obu->header.obu_extension_flag) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid OBU length: " "unit too short (%"SIZE_SPECIFIER").\n", unit->data_size); return AVERROR_INVALIDDATA; } obu->obu_size = unit->data_size - 1 - obu->header.obu_extension_flag; } start_pos = get_bits_count(&gbc); if (obu->header.obu_extension_flag) { priv->temporal_id = obu->header.temporal_id; priv->spatial_id = obu->header.temporal_id; if (obu->header.obu_type != AV1_OBU_SEQUENCE_HEADER && obu->header.obu_type != AV1_OBU_TEMPORAL_DELIMITER && priv->operating_point_idc) { int in_temporal_layer = (priv->operating_point_idc >> priv->temporal_id ) & 1; int in_spatial_layer = (priv->operating_point_idc >> (priv->spatial_id + 8)) & 1; if (!in_temporal_layer || !in_spatial_layer) { // Decoding will drop this OBU at this operating point. } } } else { priv->temporal_id = 0; priv->spatial_id = 0; } switch (obu->header.obu_type) { case AV1_OBU_SEQUENCE_HEADER: { err = cbs_av1_read_sequence_header_obu(ctx, &gbc, &obu->obu.sequence_header); if (err < 0) return err; av_buffer_unref(&priv->sequence_header_ref); priv->sequence_header = NULL; priv->sequence_header_ref = av_buffer_ref(unit->content_ref); if (!priv->sequence_header_ref) return AVERROR(ENOMEM); priv->sequence_header = &obu->obu.sequence_header; } break; case AV1_OBU_TEMPORAL_DELIMITER: { err = cbs_av1_read_temporal_delimiter_obu(ctx, &gbc); if (err < 0) return err; } break; case AV1_OBU_FRAME_HEADER: case AV1_OBU_REDUNDANT_FRAME_HEADER: { err = cbs_av1_read_frame_header_obu(ctx, &gbc, &obu->obu.frame_header, obu->header.obu_type == AV1_OBU_REDUNDANT_FRAME_HEADER, unit->data_ref); if (err < 0) return err; } break; case AV1_OBU_TILE_GROUP: { err = cbs_av1_read_tile_group_obu(ctx, &gbc, &obu->obu.tile_group); if (err < 0) return err; err = cbs_av1_ref_tile_data(ctx, unit, &gbc, &obu->obu.tile_group.tile_data); if (err < 0) return err; } break; case AV1_OBU_FRAME: { err = cbs_av1_read_frame_obu(ctx, &gbc, &obu->obu.frame, unit->data_ref); if (err < 0) return err; err = cbs_av1_ref_tile_data(ctx, unit, &gbc, &obu->obu.frame.tile_group.tile_data); if (err < 0) return err; } break; case AV1_OBU_TILE_LIST: { err = cbs_av1_read_tile_list_obu(ctx, &gbc, &obu->obu.tile_list); if (err < 0) return err; err = cbs_av1_ref_tile_data(ctx, unit, &gbc, &obu->obu.tile_list.tile_data); if (err < 0) return err; } break; case AV1_OBU_METADATA: { err = cbs_av1_read_metadata_obu(ctx, &gbc, &obu->obu.metadata); if (err < 0) return err; } break; case AV1_OBU_PADDING: default: return AVERROR(ENOSYS); } end_pos = get_bits_count(&gbc); av_assert0(end_pos <= unit->data_size * 8); if (obu->obu_size > 0 && obu->header.obu_type != AV1_OBU_TILE_GROUP && obu->header.obu_type != AV1_OBU_FRAME) { err = cbs_av1_read_trailing_bits(ctx, &gbc, obu->obu_size * 8 + start_pos - end_pos); if (err < 0) return err; } return 0; } static int cbs_av1_write_obu(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { CodedBitstreamAV1Context *priv = ctx->priv_data; AV1RawOBU *obu = unit->content; PutBitContext pbc_tmp; AV1RawTileData *td; size_t header_size; int err, start_pos, end_pos, data_pos; // OBUs in the normal bitstream format must contain a size field // in every OBU (in annex B it is optional, but we don't support // writing that). obu->header.obu_has_size_field = 1; err = cbs_av1_write_obu_header(ctx, pbc, &obu->header); if (err < 0) return err; if (obu->header.obu_has_size_field) { pbc_tmp = *pbc; // Add space for the size field to fill later. put_bits32(pbc, 0); put_bits32(pbc, 0); } td = NULL; start_pos = put_bits_count(pbc); switch (obu->header.obu_type) { case AV1_OBU_SEQUENCE_HEADER: { err = cbs_av1_write_sequence_header_obu(ctx, pbc, &obu->obu.sequence_header); if (err < 0) return err; av_buffer_unref(&priv->sequence_header_ref); priv->sequence_header = NULL; priv->sequence_header_ref = av_buffer_ref(unit->content_ref); if (!priv->sequence_header_ref) return AVERROR(ENOMEM); priv->sequence_header = &obu->obu.sequence_header; } break; case AV1_OBU_TEMPORAL_DELIMITER: { err = cbs_av1_write_temporal_delimiter_obu(ctx, pbc); if (err < 0) return err; } break; case AV1_OBU_FRAME_HEADER: case AV1_OBU_REDUNDANT_FRAME_HEADER: { err = cbs_av1_write_frame_header_obu(ctx, pbc, &obu->obu.frame_header, obu->header.obu_type == AV1_OBU_REDUNDANT_FRAME_HEADER, NULL); if (err < 0) return err; } break; case AV1_OBU_TILE_GROUP: { err = cbs_av1_write_tile_group_obu(ctx, pbc, &obu->obu.tile_group); if (err < 0) return err; td = &obu->obu.tile_group.tile_data; } break; case AV1_OBU_FRAME: { err = cbs_av1_write_frame_obu(ctx, pbc, &obu->obu.frame, NULL); if (err < 0) return err; td = &obu->obu.frame.tile_group.tile_data; } break; case AV1_OBU_TILE_LIST: { err = cbs_av1_write_tile_list_obu(ctx, pbc, &obu->obu.tile_list); if (err < 0) return err; td = &obu->obu.tile_list.tile_data; } break; case AV1_OBU_METADATA: { err = cbs_av1_write_metadata_obu(ctx, pbc, &obu->obu.metadata); if (err < 0) return err; } break; case AV1_OBU_PADDING: default: return AVERROR(ENOSYS); } end_pos = put_bits_count(pbc); header_size = (end_pos - start_pos + 7) / 8; if (td) { obu->obu_size = header_size + td->data_size; } else if (header_size > 0) { // Add trailing bits and recalculate. err = cbs_av1_write_trailing_bits(ctx, pbc, 8 - end_pos % 8); if (err < 0) return err; end_pos = put_bits_count(pbc); obu->obu_size = header_size = (end_pos - start_pos + 7) / 8; } else { // Empty OBU. obu->obu_size = 0; } end_pos = put_bits_count(pbc); // Must now be byte-aligned. av_assert0(end_pos % 8 == 0); flush_put_bits(pbc); start_pos /= 8; end_pos /= 8; *pbc = pbc_tmp; err = cbs_av1_write_leb128(ctx, pbc, "obu_size", obu->obu_size); if (err < 0) return err; data_pos = put_bits_count(pbc) / 8; flush_put_bits(pbc); av_assert0(data_pos <= start_pos); if (8 * obu->obu_size > put_bits_left(pbc)) return AVERROR(ENOSPC); if (obu->obu_size > 0) { memmove(priv->write_buffer + data_pos, priv->write_buffer + start_pos, header_size); skip_put_bytes(pbc, header_size); if (td) { memcpy(priv->write_buffer + data_pos + header_size, td->data, td->data_size); skip_put_bytes(pbc, td->data_size); } } return 0; } static int cbs_av1_write_unit(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit) { CodedBitstreamAV1Context *priv = ctx->priv_data; PutBitContext pbc; int err; if (!priv->write_buffer) { // Initial write buffer size is 1MB. priv->write_buffer_size = 1024 * 1024; reallocate_and_try_again: err = av_reallocp(&priv->write_buffer, priv->write_buffer_size); if (err < 0) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Unable to allocate a " "sufficiently large write buffer (last attempt " "%"SIZE_SPECIFIER" bytes).\n", priv->write_buffer_size); return err; } } init_put_bits(&pbc, priv->write_buffer, priv->write_buffer_size); err = cbs_av1_write_obu(ctx, unit, &pbc); if (err == AVERROR(ENOSPC)) { // Overflow. priv->write_buffer_size *= 2; goto reallocate_and_try_again; } if (err < 0) return err; // Overflow but we didn't notice. av_assert0(put_bits_count(&pbc) <= 8 * priv->write_buffer_size); // OBU data must be byte-aligned. av_assert0(put_bits_count(&pbc) % 8 == 0); unit->data_size = put_bits_count(&pbc) / 8; flush_put_bits(&pbc); err = ff_cbs_alloc_unit_data(ctx, unit, unit->data_size); if (err < 0) return err; memcpy(unit->data, priv->write_buffer, unit->data_size); return 0; } static int cbs_av1_assemble_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag) { size_t size, pos; int i; size = 0; for (i = 0; i < frag->nb_units; i++) size += frag->units[i].data_size; frag->data_ref = av_buffer_alloc(size + AV_INPUT_BUFFER_PADDING_SIZE); if (!frag->data_ref) return AVERROR(ENOMEM); frag->data = frag->data_ref->data; memset(frag->data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE); pos = 0; for (i = 0; i < frag->nb_units; i++) { memcpy(frag->data + pos, frag->units[i].data, frag->units[i].data_size); pos += frag->units[i].data_size; } av_assert0(pos == size); frag->data_size = size; return 0; } static void cbs_av1_close(CodedBitstreamContext *ctx) { CodedBitstreamAV1Context *priv = ctx->priv_data; av_buffer_unref(&priv->sequence_header_ref); av_buffer_unref(&priv->frame_header_ref); av_freep(&priv->write_buffer); } const CodedBitstreamType ff_cbs_type_av1 = { .codec_id = AV_CODEC_ID_AV1, .priv_data_size = sizeof(CodedBitstreamAV1Context), .split_fragment = &cbs_av1_split_fragment, .read_unit = &cbs_av1_read_unit, .write_unit = &cbs_av1_write_unit, .assemble_fragment = &cbs_av1_assemble_fragment, .close = &cbs_av1_close, };
./CrossVul/dataset_final_sorted/CWE-129/c/good_705_0
crossvul-cpp_data_bad_3335_0
/* * Server-side procedures for NFSv4. * * Copyright (c) 2002 The Regents of the University of Michigan. * All rights reserved. * * Kendrick Smith <kmsmith@umich.edu> * Andy Adamson <andros@umich.edu> * * 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 ``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 <linux/file.h> #include <linux/falloc.h> #include <linux/slab.h> #include "idmap.h" #include "cache.h" #include "xdr4.h" #include "vfs.h" #include "current_stateid.h" #include "netns.h" #include "acl.h" #include "pnfs.h" #include "trace.h" #ifdef CONFIG_NFSD_V4_SECURITY_LABEL #include <linux/security.h> static inline void nfsd4_security_inode_setsecctx(struct svc_fh *resfh, struct xdr_netobj *label, u32 *bmval) { struct inode *inode = d_inode(resfh->fh_dentry); int status; inode_lock(inode); status = security_inode_setsecctx(resfh->fh_dentry, label->data, label->len); inode_unlock(inode); if (status) /* * XXX: We should really fail the whole open, but we may * already have created a new file, so it may be too * late. For now this seems the least of evils: */ bmval[2] &= ~FATTR4_WORD2_SECURITY_LABEL; return; } #else static inline void nfsd4_security_inode_setsecctx(struct svc_fh *resfh, struct xdr_netobj *label, u32 *bmval) { } #endif #define NFSDDBG_FACILITY NFSDDBG_PROC static u32 nfsd_attrmask[] = { NFSD_WRITEABLE_ATTRS_WORD0, NFSD_WRITEABLE_ATTRS_WORD1, NFSD_WRITEABLE_ATTRS_WORD2 }; static u32 nfsd41_ex_attrmask[] = { NFSD_SUPPATTR_EXCLCREAT_WORD0, NFSD_SUPPATTR_EXCLCREAT_WORD1, NFSD_SUPPATTR_EXCLCREAT_WORD2 }; static __be32 check_attr_support(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, u32 *bmval, u32 *writable) { struct dentry *dentry = cstate->current_fh.fh_dentry; struct svc_export *exp = cstate->current_fh.fh_export; if (!nfsd_attrs_supported(cstate->minorversion, bmval)) return nfserr_attrnotsupp; if ((bmval[0] & FATTR4_WORD0_ACL) && !IS_POSIXACL(d_inode(dentry))) return nfserr_attrnotsupp; if ((bmval[2] & FATTR4_WORD2_SECURITY_LABEL) && !(exp->ex_flags & NFSEXP_SECURITY_LABEL)) return nfserr_attrnotsupp; if (writable && !bmval_is_subset(bmval, writable)) return nfserr_inval; if (writable && (bmval[2] & FATTR4_WORD2_MODE_UMASK) && (bmval[1] & FATTR4_WORD1_MODE)) return nfserr_inval; return nfs_ok; } static __be32 nfsd4_check_open_attributes(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_open *open) { __be32 status = nfs_ok; if (open->op_create == NFS4_OPEN_CREATE) { if (open->op_createmode == NFS4_CREATE_UNCHECKED || open->op_createmode == NFS4_CREATE_GUARDED) status = check_attr_support(rqstp, cstate, open->op_bmval, nfsd_attrmask); else if (open->op_createmode == NFS4_CREATE_EXCLUSIVE4_1) status = check_attr_support(rqstp, cstate, open->op_bmval, nfsd41_ex_attrmask); } return status; } static int is_create_with_attrs(struct nfsd4_open *open) { return open->op_create == NFS4_OPEN_CREATE && (open->op_createmode == NFS4_CREATE_UNCHECKED || open->op_createmode == NFS4_CREATE_GUARDED || open->op_createmode == NFS4_CREATE_EXCLUSIVE4_1); } /* * if error occurs when setting the acl, just clear the acl bit * in the returned attr bitmap. */ static void do_set_nfs4_acl(struct svc_rqst *rqstp, struct svc_fh *fhp, struct nfs4_acl *acl, u32 *bmval) { __be32 status; status = nfsd4_set_nfs4_acl(rqstp, fhp, acl); if (status) /* * We should probably fail the whole open at this point, * but we've already created the file, so it's too late; * So this seems the least of evils: */ bmval[0] &= ~FATTR4_WORD0_ACL; } static inline void fh_dup2(struct svc_fh *dst, struct svc_fh *src) { fh_put(dst); dget(src->fh_dentry); if (src->fh_export) exp_get(src->fh_export); *dst = *src; } static __be32 do_open_permission(struct svc_rqst *rqstp, struct svc_fh *current_fh, struct nfsd4_open *open, int accmode) { __be32 status; if (open->op_truncate && !(open->op_share_access & NFS4_SHARE_ACCESS_WRITE)) return nfserr_inval; accmode |= NFSD_MAY_READ_IF_EXEC; if (open->op_share_access & NFS4_SHARE_ACCESS_READ) accmode |= NFSD_MAY_READ; if (open->op_share_access & NFS4_SHARE_ACCESS_WRITE) accmode |= (NFSD_MAY_WRITE | NFSD_MAY_TRUNC); if (open->op_share_deny & NFS4_SHARE_DENY_READ) accmode |= NFSD_MAY_WRITE; status = fh_verify(rqstp, current_fh, S_IFREG, accmode); return status; } static __be32 nfsd_check_obj_isreg(struct svc_fh *fh) { umode_t mode = d_inode(fh->fh_dentry)->i_mode; if (S_ISREG(mode)) return nfs_ok; if (S_ISDIR(mode)) return nfserr_isdir; /* * Using err_symlink as our catch-all case may look odd; but * there's no other obvious error for this case in 4.0, and we * happen to know that it will cause the linux v4 client to do * the right thing on attempts to open something other than a * regular file. */ return nfserr_symlink; } static void nfsd4_set_open_owner_reply_cache(struct nfsd4_compound_state *cstate, struct nfsd4_open *open, struct svc_fh *resfh) { if (nfsd4_has_session(cstate)) return; fh_copy_shallow(&open->op_openowner->oo_owner.so_replay.rp_openfh, &resfh->fh_handle); } static __be32 do_open_lookup(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_open *open, struct svc_fh **resfh) { struct svc_fh *current_fh = &cstate->current_fh; int accmode; __be32 status; *resfh = kmalloc(sizeof(struct svc_fh), GFP_KERNEL); if (!*resfh) return nfserr_jukebox; fh_init(*resfh, NFS4_FHSIZE); open->op_truncate = 0; if (open->op_create) { /* FIXME: check session persistence and pnfs flags. * The nfsv4.1 spec requires the following semantics: * * Persistent | pNFS | Server REQUIRED | Client Allowed * Reply Cache | server | | * -------------+--------+-----------------+-------------------- * no | no | EXCLUSIVE4_1 | EXCLUSIVE4_1 * | | | (SHOULD) * | | and EXCLUSIVE4 | or EXCLUSIVE4 * | | | (SHOULD NOT) * no | yes | EXCLUSIVE4_1 | EXCLUSIVE4_1 * yes | no | GUARDED4 | GUARDED4 * yes | yes | GUARDED4 | GUARDED4 */ /* * Note: create modes (UNCHECKED,GUARDED...) are the same * in NFSv4 as in v3 except EXCLUSIVE4_1. */ status = do_nfsd_create(rqstp, current_fh, open->op_fname.data, open->op_fname.len, &open->op_iattr, *resfh, open->op_createmode, (u32 *)open->op_verf.data, &open->op_truncate, &open->op_created); if (!status && open->op_label.len) nfsd4_security_inode_setsecctx(*resfh, &open->op_label, open->op_bmval); /* * Following rfc 3530 14.2.16, and rfc 5661 18.16.4 * use the returned bitmask to indicate which attributes * we used to store the verifier: */ if (nfsd_create_is_exclusive(open->op_createmode) && status == 0) open->op_bmval[1] |= (FATTR4_WORD1_TIME_ACCESS | FATTR4_WORD1_TIME_MODIFY); } else /* * Note this may exit with the parent still locked. * We will hold the lock until nfsd4_open's final * lookup, to prevent renames or unlinks until we've had * a chance to an acquire a delegation if appropriate. */ status = nfsd_lookup(rqstp, current_fh, open->op_fname.data, open->op_fname.len, *resfh); if (status) goto out; status = nfsd_check_obj_isreg(*resfh); if (status) goto out; if (is_create_with_attrs(open) && open->op_acl != NULL) do_set_nfs4_acl(rqstp, *resfh, open->op_acl, open->op_bmval); nfsd4_set_open_owner_reply_cache(cstate, open, *resfh); accmode = NFSD_MAY_NOP; if (open->op_created || open->op_claim_type == NFS4_OPEN_CLAIM_DELEGATE_CUR) accmode |= NFSD_MAY_OWNER_OVERRIDE; status = do_open_permission(rqstp, *resfh, open, accmode); set_change_info(&open->op_cinfo, current_fh); out: return status; } static __be32 do_open_fhandle(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_open *open) { struct svc_fh *current_fh = &cstate->current_fh; __be32 status; int accmode = 0; /* We don't know the target directory, and therefore can not * set the change info */ memset(&open->op_cinfo, 0, sizeof(struct nfsd4_change_info)); nfsd4_set_open_owner_reply_cache(cstate, open, current_fh); open->op_truncate = (open->op_iattr.ia_valid & ATTR_SIZE) && (open->op_iattr.ia_size == 0); /* * In the delegation case, the client is telling us about an * open that it *already* performed locally, some time ago. We * should let it succeed now if possible. * * In the case of a CLAIM_FH open, on the other hand, the client * may be counting on us to enforce permissions (the Linux 4.1 * client uses this for normal opens, for example). */ if (open->op_claim_type == NFS4_OPEN_CLAIM_DELEG_CUR_FH) accmode = NFSD_MAY_OWNER_OVERRIDE; status = do_open_permission(rqstp, current_fh, open, accmode); return status; } static void copy_clientid(clientid_t *clid, struct nfsd4_session *session) { struct nfsd4_sessionid *sid = (struct nfsd4_sessionid *)session->se_sessionid.data; clid->cl_boot = sid->clientid.cl_boot; clid->cl_id = sid->clientid.cl_id; } static __be32 nfsd4_open(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_open *open) { __be32 status; struct svc_fh *resfh = NULL; struct net *net = SVC_NET(rqstp); struct nfsd_net *nn = net_generic(net, nfsd_net_id); dprintk("NFSD: nfsd4_open filename %.*s op_openowner %p\n", (int)open->op_fname.len, open->op_fname.data, open->op_openowner); /* This check required by spec. */ if (open->op_create && open->op_claim_type != NFS4_OPEN_CLAIM_NULL) return nfserr_inval; open->op_created = 0; /* * RFC5661 18.51.3 * Before RECLAIM_COMPLETE done, server should deny new lock */ if (nfsd4_has_session(cstate) && !test_bit(NFSD4_CLIENT_RECLAIM_COMPLETE, &cstate->session->se_client->cl_flags) && open->op_claim_type != NFS4_OPEN_CLAIM_PREVIOUS) return nfserr_grace; if (nfsd4_has_session(cstate)) copy_clientid(&open->op_clientid, cstate->session); /* check seqid for replay. set nfs4_owner */ status = nfsd4_process_open1(cstate, open, nn); if (status == nfserr_replay_me) { struct nfs4_replay *rp = &open->op_openowner->oo_owner.so_replay; fh_put(&cstate->current_fh); fh_copy_shallow(&cstate->current_fh.fh_handle, &rp->rp_openfh); status = fh_verify(rqstp, &cstate->current_fh, 0, NFSD_MAY_NOP); if (status) dprintk("nfsd4_open: replay failed" " restoring previous filehandle\n"); else status = nfserr_replay_me; } if (status) goto out; if (open->op_xdr_error) { status = open->op_xdr_error; goto out; } status = nfsd4_check_open_attributes(rqstp, cstate, open); if (status) goto out; /* Openowner is now set, so sequence id will get bumped. Now we need * these checks before we do any creates: */ status = nfserr_grace; if (opens_in_grace(net) && open->op_claim_type != NFS4_OPEN_CLAIM_PREVIOUS) goto out; status = nfserr_no_grace; if (!opens_in_grace(net) && open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS) goto out; switch (open->op_claim_type) { case NFS4_OPEN_CLAIM_DELEGATE_CUR: case NFS4_OPEN_CLAIM_NULL: status = do_open_lookup(rqstp, cstate, open, &resfh); if (status) goto out; break; case NFS4_OPEN_CLAIM_PREVIOUS: status = nfs4_check_open_reclaim(&open->op_clientid, cstate, nn); if (status) goto out; open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED; case NFS4_OPEN_CLAIM_FH: case NFS4_OPEN_CLAIM_DELEG_CUR_FH: status = do_open_fhandle(rqstp, cstate, open); if (status) goto out; resfh = &cstate->current_fh; break; case NFS4_OPEN_CLAIM_DELEG_PREV_FH: case NFS4_OPEN_CLAIM_DELEGATE_PREV: dprintk("NFSD: unsupported OPEN claim type %d\n", open->op_claim_type); status = nfserr_notsupp; goto out; default: dprintk("NFSD: Invalid OPEN claim type %d\n", open->op_claim_type); status = nfserr_inval; goto out; } /* * nfsd4_process_open2() does the actual opening of the file. If * successful, it (1) truncates the file if open->op_truncate was * set, (2) sets open->op_stateid, (3) sets open->op_delegation. */ status = nfsd4_process_open2(rqstp, resfh, open); WARN(status && open->op_created, "nfsd4_process_open2 failed to open newly-created file! status=%u\n", be32_to_cpu(status)); out: if (resfh && resfh != &cstate->current_fh) { fh_dup2(&cstate->current_fh, resfh); fh_put(resfh); kfree(resfh); } nfsd4_cleanup_open_state(cstate, open); nfsd4_bump_seqid(cstate, status); return status; } /* * OPEN is the only seqid-mutating operation whose decoding can fail * with a seqid-mutating error (specifically, decoding of user names in * the attributes). Therefore we have to do some processing to look up * the stateowner so that we can bump the seqid. */ static __be32 nfsd4_open_omfg(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_op *op) { struct nfsd4_open *open = (struct nfsd4_open *)&op->u; if (!seqid_mutating_err(ntohl(op->status))) return op->status; if (nfsd4_has_session(cstate)) return op->status; open->op_xdr_error = op->status; return nfsd4_open(rqstp, cstate, open); } /* * filehandle-manipulating ops. */ static __be32 nfsd4_getfh(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct svc_fh **getfh) { if (!cstate->current_fh.fh_dentry) return nfserr_nofilehandle; *getfh = &cstate->current_fh; return nfs_ok; } static __be32 nfsd4_putfh(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_putfh *putfh) { fh_put(&cstate->current_fh); cstate->current_fh.fh_handle.fh_size = putfh->pf_fhlen; memcpy(&cstate->current_fh.fh_handle.fh_base, putfh->pf_fhval, putfh->pf_fhlen); return fh_verify(rqstp, &cstate->current_fh, 0, NFSD_MAY_BYPASS_GSS); } static __be32 nfsd4_putrootfh(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, void *arg) { __be32 status; fh_put(&cstate->current_fh); status = exp_pseudoroot(rqstp, &cstate->current_fh); return status; } static __be32 nfsd4_restorefh(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, void *arg) { if (!cstate->save_fh.fh_dentry) return nfserr_restorefh; fh_dup2(&cstate->current_fh, &cstate->save_fh); if (HAS_STATE_ID(cstate, SAVED_STATE_ID_FLAG)) { memcpy(&cstate->current_stateid, &cstate->save_stateid, sizeof(stateid_t)); SET_STATE_ID(cstate, CURRENT_STATE_ID_FLAG); } return nfs_ok; } static __be32 nfsd4_savefh(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, void *arg) { if (!cstate->current_fh.fh_dentry) return nfserr_nofilehandle; fh_dup2(&cstate->save_fh, &cstate->current_fh); if (HAS_STATE_ID(cstate, CURRENT_STATE_ID_FLAG)) { memcpy(&cstate->save_stateid, &cstate->current_stateid, sizeof(stateid_t)); SET_STATE_ID(cstate, SAVED_STATE_ID_FLAG); } return nfs_ok; } /* * misc nfsv4 ops */ static __be32 nfsd4_access(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_access *access) { if (access->ac_req_access & ~NFS3_ACCESS_FULL) return nfserr_inval; access->ac_resp_access = access->ac_req_access; return nfsd_access(rqstp, &cstate->current_fh, &access->ac_resp_access, &access->ac_supported); } static void gen_boot_verifier(nfs4_verifier *verifier, struct net *net) { __be32 verf[2]; struct nfsd_net *nn = net_generic(net, nfsd_net_id); /* * This is opaque to client, so no need to byte-swap. Use * __force to keep sparse happy */ verf[0] = (__force __be32)nn->nfssvc_boot.tv_sec; verf[1] = (__force __be32)nn->nfssvc_boot.tv_usec; memcpy(verifier->data, verf, sizeof(verifier->data)); } static __be32 nfsd4_commit(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_commit *commit) { gen_boot_verifier(&commit->co_verf, SVC_NET(rqstp)); return nfsd_commit(rqstp, &cstate->current_fh, commit->co_offset, commit->co_count); } static __be32 nfsd4_create(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_create *create) { struct svc_fh resfh; __be32 status; dev_t rdev; fh_init(&resfh, NFS4_FHSIZE); status = fh_verify(rqstp, &cstate->current_fh, S_IFDIR, NFSD_MAY_NOP); if (status) return status; status = check_attr_support(rqstp, cstate, create->cr_bmval, nfsd_attrmask); if (status) return status; switch (create->cr_type) { case NF4LNK: status = nfsd_symlink(rqstp, &cstate->current_fh, create->cr_name, create->cr_namelen, create->cr_data, &resfh); break; case NF4BLK: rdev = MKDEV(create->cr_specdata1, create->cr_specdata2); if (MAJOR(rdev) != create->cr_specdata1 || MINOR(rdev) != create->cr_specdata2) return nfserr_inval; status = nfsd_create(rqstp, &cstate->current_fh, create->cr_name, create->cr_namelen, &create->cr_iattr, S_IFBLK, rdev, &resfh); break; case NF4CHR: rdev = MKDEV(create->cr_specdata1, create->cr_specdata2); if (MAJOR(rdev) != create->cr_specdata1 || MINOR(rdev) != create->cr_specdata2) return nfserr_inval; status = nfsd_create(rqstp, &cstate->current_fh, create->cr_name, create->cr_namelen, &create->cr_iattr,S_IFCHR, rdev, &resfh); break; case NF4SOCK: status = nfsd_create(rqstp, &cstate->current_fh, create->cr_name, create->cr_namelen, &create->cr_iattr, S_IFSOCK, 0, &resfh); break; case NF4FIFO: status = nfsd_create(rqstp, &cstate->current_fh, create->cr_name, create->cr_namelen, &create->cr_iattr, S_IFIFO, 0, &resfh); break; case NF4DIR: create->cr_iattr.ia_valid &= ~ATTR_SIZE; status = nfsd_create(rqstp, &cstate->current_fh, create->cr_name, create->cr_namelen, &create->cr_iattr, S_IFDIR, 0, &resfh); break; default: status = nfserr_badtype; } if (status) goto out; if (create->cr_label.len) nfsd4_security_inode_setsecctx(&resfh, &create->cr_label, create->cr_bmval); if (create->cr_acl != NULL) do_set_nfs4_acl(rqstp, &resfh, create->cr_acl, create->cr_bmval); fh_unlock(&cstate->current_fh); set_change_info(&create->cr_cinfo, &cstate->current_fh); fh_dup2(&cstate->current_fh, &resfh); out: fh_put(&resfh); return status; } static __be32 nfsd4_getattr(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_getattr *getattr) { __be32 status; status = fh_verify(rqstp, &cstate->current_fh, 0, NFSD_MAY_NOP); if (status) return status; if (getattr->ga_bmval[1] & NFSD_WRITEONLY_ATTRS_WORD1) return nfserr_inval; getattr->ga_bmval[0] &= nfsd_suppattrs[cstate->minorversion][0]; getattr->ga_bmval[1] &= nfsd_suppattrs[cstate->minorversion][1]; getattr->ga_bmval[2] &= nfsd_suppattrs[cstate->minorversion][2]; getattr->ga_fhp = &cstate->current_fh; return nfs_ok; } static __be32 nfsd4_link(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_link *link) { __be32 status = nfserr_nofilehandle; if (!cstate->save_fh.fh_dentry) return status; status = nfsd_link(rqstp, &cstate->current_fh, link->li_name, link->li_namelen, &cstate->save_fh); if (!status) set_change_info(&link->li_cinfo, &cstate->current_fh); return status; } static __be32 nfsd4_do_lookupp(struct svc_rqst *rqstp, struct svc_fh *fh) { struct svc_fh tmp_fh; __be32 ret; fh_init(&tmp_fh, NFS4_FHSIZE); ret = exp_pseudoroot(rqstp, &tmp_fh); if (ret) return ret; if (tmp_fh.fh_dentry == fh->fh_dentry) { fh_put(&tmp_fh); return nfserr_noent; } fh_put(&tmp_fh); return nfsd_lookup(rqstp, fh, "..", 2, fh); } static __be32 nfsd4_lookupp(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, void *arg) { return nfsd4_do_lookupp(rqstp, &cstate->current_fh); } static __be32 nfsd4_lookup(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_lookup *lookup) { return nfsd_lookup(rqstp, &cstate->current_fh, lookup->lo_name, lookup->lo_len, &cstate->current_fh); } static __be32 nfsd4_read(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_read *read) { __be32 status; read->rd_filp = NULL; if (read->rd_offset >= OFFSET_MAX) return nfserr_inval; /* * If we do a zero copy read, then a client will see read data * that reflects the state of the file *after* performing the * following compound. * * To ensure proper ordering, we therefore turn off zero copy if * the client wants us to do more in this compound: */ if (!nfsd4_last_compound_op(rqstp)) clear_bit(RQ_SPLICE_OK, &rqstp->rq_flags); /* check stateid */ status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->current_fh, &read->rd_stateid, RD_STATE, &read->rd_filp, &read->rd_tmp_file); if (status) { dprintk("NFSD: nfsd4_read: couldn't process stateid!\n"); goto out; } status = nfs_ok; out: read->rd_rqstp = rqstp; read->rd_fhp = &cstate->current_fh; return status; } static __be32 nfsd4_readdir(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_readdir *readdir) { u64 cookie = readdir->rd_cookie; static const nfs4_verifier zeroverf; /* no need to check permission - this will be done in nfsd_readdir() */ if (readdir->rd_bmval[1] & NFSD_WRITEONLY_ATTRS_WORD1) return nfserr_inval; readdir->rd_bmval[0] &= nfsd_suppattrs[cstate->minorversion][0]; readdir->rd_bmval[1] &= nfsd_suppattrs[cstate->minorversion][1]; readdir->rd_bmval[2] &= nfsd_suppattrs[cstate->minorversion][2]; if ((cookie == 1) || (cookie == 2) || (cookie == 0 && memcmp(readdir->rd_verf.data, zeroverf.data, NFS4_VERIFIER_SIZE))) return nfserr_bad_cookie; readdir->rd_rqstp = rqstp; readdir->rd_fhp = &cstate->current_fh; return nfs_ok; } static __be32 nfsd4_readlink(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_readlink *readlink) { readlink->rl_rqstp = rqstp; readlink->rl_fhp = &cstate->current_fh; return nfs_ok; } static __be32 nfsd4_remove(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_remove *remove) { __be32 status; if (opens_in_grace(SVC_NET(rqstp))) return nfserr_grace; status = nfsd_unlink(rqstp, &cstate->current_fh, 0, remove->rm_name, remove->rm_namelen); if (!status) { fh_unlock(&cstate->current_fh); set_change_info(&remove->rm_cinfo, &cstate->current_fh); } return status; } static __be32 nfsd4_rename(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_rename *rename) { __be32 status = nfserr_nofilehandle; if (!cstate->save_fh.fh_dentry) return status; if (opens_in_grace(SVC_NET(rqstp)) && !(cstate->save_fh.fh_export->ex_flags & NFSEXP_NOSUBTREECHECK)) return nfserr_grace; status = nfsd_rename(rqstp, &cstate->save_fh, rename->rn_sname, rename->rn_snamelen, &cstate->current_fh, rename->rn_tname, rename->rn_tnamelen); if (status) return status; set_change_info(&rename->rn_sinfo, &cstate->current_fh); set_change_info(&rename->rn_tinfo, &cstate->save_fh); return nfs_ok; } static __be32 nfsd4_secinfo(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_secinfo *secinfo) { struct svc_export *exp; struct dentry *dentry; __be32 err; err = fh_verify(rqstp, &cstate->current_fh, S_IFDIR, NFSD_MAY_EXEC); if (err) return err; err = nfsd_lookup_dentry(rqstp, &cstate->current_fh, secinfo->si_name, secinfo->si_namelen, &exp, &dentry); if (err) return err; fh_unlock(&cstate->current_fh); if (d_really_is_negative(dentry)) { exp_put(exp); err = nfserr_noent; } else secinfo->si_exp = exp; dput(dentry); if (cstate->minorversion) /* See rfc 5661 section 2.6.3.1.1.8 */ fh_put(&cstate->current_fh); return err; } static __be32 nfsd4_secinfo_no_name(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_secinfo_no_name *sin) { __be32 err; switch (sin->sin_style) { case NFS4_SECINFO_STYLE4_CURRENT_FH: break; case NFS4_SECINFO_STYLE4_PARENT: err = nfsd4_do_lookupp(rqstp, &cstate->current_fh); if (err) return err; break; default: return nfserr_inval; } sin->sin_exp = exp_get(cstate->current_fh.fh_export); fh_put(&cstate->current_fh); return nfs_ok; } static __be32 nfsd4_setattr(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_setattr *setattr) { __be32 status = nfs_ok; int err; if (setattr->sa_iattr.ia_valid & ATTR_SIZE) { status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->current_fh, &setattr->sa_stateid, WR_STATE, NULL, NULL); if (status) { dprintk("NFSD: nfsd4_setattr: couldn't process stateid!\n"); return status; } } err = fh_want_write(&cstate->current_fh); if (err) return nfserrno(err); status = nfs_ok; status = check_attr_support(rqstp, cstate, setattr->sa_bmval, nfsd_attrmask); if (status) goto out; if (setattr->sa_acl != NULL) status = nfsd4_set_nfs4_acl(rqstp, &cstate->current_fh, setattr->sa_acl); if (status) goto out; if (setattr->sa_label.len) status = nfsd4_set_nfs4_label(rqstp, &cstate->current_fh, &setattr->sa_label); if (status) goto out; status = nfsd_setattr(rqstp, &cstate->current_fh, &setattr->sa_iattr, 0, (time_t)0); out: fh_drop_write(&cstate->current_fh); return status; } static int fill_in_write_vector(struct kvec *vec, struct nfsd4_write *write) { int i = 1; int buflen = write->wr_buflen; vec[0].iov_base = write->wr_head.iov_base; vec[0].iov_len = min_t(int, buflen, write->wr_head.iov_len); buflen -= vec[0].iov_len; while (buflen) { vec[i].iov_base = page_address(write->wr_pagelist[i - 1]); vec[i].iov_len = min_t(int, PAGE_SIZE, buflen); buflen -= vec[i].iov_len; i++; } return i; } static __be32 nfsd4_write(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_write *write) { stateid_t *stateid = &write->wr_stateid; struct file *filp = NULL; __be32 status = nfs_ok; unsigned long cnt; int nvecs; if (write->wr_offset >= OFFSET_MAX) return nfserr_inval; status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->current_fh, stateid, WR_STATE, &filp, NULL); if (status) { dprintk("NFSD: nfsd4_write: couldn't process stateid!\n"); return status; } cnt = write->wr_buflen; write->wr_how_written = write->wr_stable_how; gen_boot_verifier(&write->wr_verifier, SVC_NET(rqstp)); nvecs = fill_in_write_vector(rqstp->rq_vec, write); WARN_ON_ONCE(nvecs > ARRAY_SIZE(rqstp->rq_vec)); status = nfsd_vfs_write(rqstp, &cstate->current_fh, filp, write->wr_offset, rqstp->rq_vec, nvecs, &cnt, write->wr_how_written); fput(filp); write->wr_bytes_written = cnt; return status; } static __be32 nfsd4_verify_copy(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, stateid_t *src_stateid, struct file **src, stateid_t *dst_stateid, struct file **dst) { __be32 status; status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->save_fh, src_stateid, RD_STATE, src, NULL); if (status) { dprintk("NFSD: %s: couldn't process src stateid!\n", __func__); goto out; } status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->current_fh, dst_stateid, WR_STATE, dst, NULL); if (status) { dprintk("NFSD: %s: couldn't process dst stateid!\n", __func__); goto out_put_src; } /* fix up for NFS-specific error code */ if (!S_ISREG(file_inode(*src)->i_mode) || !S_ISREG(file_inode(*dst)->i_mode)) { status = nfserr_wrong_type; goto out_put_dst; } out: return status; out_put_dst: fput(*dst); out_put_src: fput(*src); goto out; } static __be32 nfsd4_clone(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_clone *clone) { struct file *src, *dst; __be32 status; status = nfsd4_verify_copy(rqstp, cstate, &clone->cl_src_stateid, &src, &clone->cl_dst_stateid, &dst); if (status) goto out; status = nfsd4_clone_file_range(src, clone->cl_src_pos, dst, clone->cl_dst_pos, clone->cl_count); fput(dst); fput(src); out: return status; } static __be32 nfsd4_copy(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_copy *copy) { struct file *src, *dst; __be32 status; ssize_t bytes; status = nfsd4_verify_copy(rqstp, cstate, &copy->cp_src_stateid, &src, &copy->cp_dst_stateid, &dst); if (status) goto out; bytes = nfsd_copy_file_range(src, copy->cp_src_pos, dst, copy->cp_dst_pos, copy->cp_count); if (bytes < 0) status = nfserrno(bytes); else { copy->cp_res.wr_bytes_written = bytes; copy->cp_res.wr_stable_how = NFS_UNSTABLE; copy->cp_consecutive = 1; copy->cp_synchronous = 1; gen_boot_verifier(&copy->cp_res.wr_verifier, SVC_NET(rqstp)); status = nfs_ok; } fput(src); fput(dst); out: return status; } static __be32 nfsd4_fallocate(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_fallocate *fallocate, int flags) { __be32 status = nfserr_notsupp; struct file *file; status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->current_fh, &fallocate->falloc_stateid, WR_STATE, &file, NULL); if (status != nfs_ok) { dprintk("NFSD: nfsd4_fallocate: couldn't process stateid!\n"); return status; } status = nfsd4_vfs_fallocate(rqstp, &cstate->current_fh, file, fallocate->falloc_offset, fallocate->falloc_length, flags); fput(file); return status; } static __be32 nfsd4_allocate(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_fallocate *fallocate) { return nfsd4_fallocate(rqstp, cstate, fallocate, 0); } static __be32 nfsd4_deallocate(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_fallocate *fallocate) { return nfsd4_fallocate(rqstp, cstate, fallocate, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE); } static __be32 nfsd4_seek(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_seek *seek) { int whence; __be32 status; struct file *file; status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->current_fh, &seek->seek_stateid, RD_STATE, &file, NULL); if (status) { dprintk("NFSD: nfsd4_seek: couldn't process stateid!\n"); return status; } switch (seek->seek_whence) { case NFS4_CONTENT_DATA: whence = SEEK_DATA; break; case NFS4_CONTENT_HOLE: whence = SEEK_HOLE; break; default: status = nfserr_union_notsupp; goto out; } /* * Note: This call does change file->f_pos, but nothing in NFSD * should ever file->f_pos. */ seek->seek_pos = vfs_llseek(file, seek->seek_offset, whence); if (seek->seek_pos < 0) status = nfserrno(seek->seek_pos); else if (seek->seek_pos >= i_size_read(file_inode(file))) seek->seek_eof = true; out: fput(file); return status; } /* This routine never returns NFS_OK! If there are no other errors, it * will return NFSERR_SAME or NFSERR_NOT_SAME depending on whether the * attributes matched. VERIFY is implemented by mapping NFSERR_SAME * to NFS_OK after the call; NVERIFY by mapping NFSERR_NOT_SAME to NFS_OK. */ static __be32 _nfsd4_verify(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_verify *verify) { __be32 *buf, *p; int count; __be32 status; status = fh_verify(rqstp, &cstate->current_fh, 0, NFSD_MAY_NOP); if (status) return status; status = check_attr_support(rqstp, cstate, verify->ve_bmval, NULL); if (status) return status; if ((verify->ve_bmval[0] & FATTR4_WORD0_RDATTR_ERROR) || (verify->ve_bmval[1] & NFSD_WRITEONLY_ATTRS_WORD1)) return nfserr_inval; if (verify->ve_attrlen & 3) return nfserr_inval; /* count in words: * bitmap_len(1) + bitmap(2) + attr_len(1) = 4 */ count = 4 + (verify->ve_attrlen >> 2); buf = kmalloc(count << 2, GFP_KERNEL); if (!buf) return nfserr_jukebox; p = buf; status = nfsd4_encode_fattr_to_buf(&p, count, &cstate->current_fh, cstate->current_fh.fh_export, cstate->current_fh.fh_dentry, verify->ve_bmval, rqstp, 0); /* * If nfsd4_encode_fattr() ran out of space, assume that's because * the attributes are longer (hence different) than those given: */ if (status == nfserr_resource) status = nfserr_not_same; if (status) goto out_kfree; /* skip bitmap */ p = buf + 1 + ntohl(buf[0]); status = nfserr_not_same; if (ntohl(*p++) != verify->ve_attrlen) goto out_kfree; if (!memcmp(p, verify->ve_attrval, verify->ve_attrlen)) status = nfserr_same; out_kfree: kfree(buf); return status; } static __be32 nfsd4_nverify(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_verify *verify) { __be32 status; status = _nfsd4_verify(rqstp, cstate, verify); return status == nfserr_not_same ? nfs_ok : status; } static __be32 nfsd4_verify(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_verify *verify) { __be32 status; status = _nfsd4_verify(rqstp, cstate, verify); return status == nfserr_same ? nfs_ok : status; } #ifdef CONFIG_NFSD_PNFS static const struct nfsd4_layout_ops * nfsd4_layout_verify(struct svc_export *exp, unsigned int layout_type) { if (!exp->ex_layout_types) { dprintk("%s: export does not support pNFS\n", __func__); return NULL; } if (!(exp->ex_layout_types & (1 << layout_type))) { dprintk("%s: layout type %d not supported\n", __func__, layout_type); return NULL; } return nfsd4_layout_ops[layout_type]; } static __be32 nfsd4_getdeviceinfo(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_getdeviceinfo *gdp) { const struct nfsd4_layout_ops *ops; struct nfsd4_deviceid_map *map; struct svc_export *exp; __be32 nfserr; dprintk("%s: layout_type %u dev_id [0x%llx:0x%x] maxcnt %u\n", __func__, gdp->gd_layout_type, gdp->gd_devid.fsid_idx, gdp->gd_devid.generation, gdp->gd_maxcount); map = nfsd4_find_devid_map(gdp->gd_devid.fsid_idx); if (!map) { dprintk("%s: couldn't find device ID to export mapping!\n", __func__); return nfserr_noent; } exp = rqst_exp_find(rqstp, map->fsid_type, map->fsid); if (IS_ERR(exp)) { dprintk("%s: could not find device id\n", __func__); return nfserr_noent; } nfserr = nfserr_layoutunavailable; ops = nfsd4_layout_verify(exp, gdp->gd_layout_type); if (!ops) goto out; nfserr = nfs_ok; if (gdp->gd_maxcount != 0) { nfserr = ops->proc_getdeviceinfo(exp->ex_path.mnt->mnt_sb, rqstp, cstate->session->se_client, gdp); } gdp->gd_notify_types &= ops->notify_types; out: exp_put(exp); return nfserr; } static __be32 nfsd4_layoutget(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_layoutget *lgp) { struct svc_fh *current_fh = &cstate->current_fh; const struct nfsd4_layout_ops *ops; struct nfs4_layout_stateid *ls; __be32 nfserr; int accmode; switch (lgp->lg_seg.iomode) { case IOMODE_READ: accmode = NFSD_MAY_READ; break; case IOMODE_RW: accmode = NFSD_MAY_READ | NFSD_MAY_WRITE; break; default: dprintk("%s: invalid iomode %d\n", __func__, lgp->lg_seg.iomode); nfserr = nfserr_badiomode; goto out; } nfserr = fh_verify(rqstp, current_fh, 0, accmode); if (nfserr) goto out; nfserr = nfserr_layoutunavailable; ops = nfsd4_layout_verify(current_fh->fh_export, lgp->lg_layout_type); if (!ops) goto out; /* * Verify minlength and range as per RFC5661: * o If loga_length is less than loga_minlength, * the metadata server MUST return NFS4ERR_INVAL. * o If the sum of loga_offset and loga_minlength exceeds * NFS4_UINT64_MAX, and loga_minlength is not * NFS4_UINT64_MAX, the error NFS4ERR_INVAL MUST result. * o If the sum of loga_offset and loga_length exceeds * NFS4_UINT64_MAX, and loga_length is not NFS4_UINT64_MAX, * the error NFS4ERR_INVAL MUST result. */ nfserr = nfserr_inval; if (lgp->lg_seg.length < lgp->lg_minlength || (lgp->lg_minlength != NFS4_MAX_UINT64 && lgp->lg_minlength > NFS4_MAX_UINT64 - lgp->lg_seg.offset) || (lgp->lg_seg.length != NFS4_MAX_UINT64 && lgp->lg_seg.length > NFS4_MAX_UINT64 - lgp->lg_seg.offset)) goto out; if (lgp->lg_seg.length == 0) goto out; nfserr = nfsd4_preprocess_layout_stateid(rqstp, cstate, &lgp->lg_sid, true, lgp->lg_layout_type, &ls); if (nfserr) { trace_layout_get_lookup_fail(&lgp->lg_sid); goto out; } nfserr = nfserr_recallconflict; if (atomic_read(&ls->ls_stid.sc_file->fi_lo_recalls)) goto out_put_stid; nfserr = ops->proc_layoutget(d_inode(current_fh->fh_dentry), current_fh, lgp); if (nfserr) goto out_put_stid; nfserr = nfsd4_insert_layout(lgp, ls); out_put_stid: mutex_unlock(&ls->ls_mutex); nfs4_put_stid(&ls->ls_stid); out: return nfserr; } static __be32 nfsd4_layoutcommit(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_layoutcommit *lcp) { const struct nfsd4_layout_seg *seg = &lcp->lc_seg; struct svc_fh *current_fh = &cstate->current_fh; const struct nfsd4_layout_ops *ops; loff_t new_size = lcp->lc_last_wr + 1; struct inode *inode; struct nfs4_layout_stateid *ls; __be32 nfserr; nfserr = fh_verify(rqstp, current_fh, 0, NFSD_MAY_WRITE); if (nfserr) goto out; nfserr = nfserr_layoutunavailable; ops = nfsd4_layout_verify(current_fh->fh_export, lcp->lc_layout_type); if (!ops) goto out; inode = d_inode(current_fh->fh_dentry); nfserr = nfserr_inval; if (new_size <= seg->offset) { dprintk("pnfsd: last write before layout segment\n"); goto out; } if (new_size > seg->offset + seg->length) { dprintk("pnfsd: last write beyond layout segment\n"); goto out; } if (!lcp->lc_newoffset && new_size > i_size_read(inode)) { dprintk("pnfsd: layoutcommit beyond EOF\n"); goto out; } nfserr = nfsd4_preprocess_layout_stateid(rqstp, cstate, &lcp->lc_sid, false, lcp->lc_layout_type, &ls); if (nfserr) { trace_layout_commit_lookup_fail(&lcp->lc_sid); /* fixup error code as per RFC5661 */ if (nfserr == nfserr_bad_stateid) nfserr = nfserr_badlayout; goto out; } /* LAYOUTCOMMIT does not require any serialization */ mutex_unlock(&ls->ls_mutex); if (new_size > i_size_read(inode)) { lcp->lc_size_chg = 1; lcp->lc_newsize = new_size; } else { lcp->lc_size_chg = 0; } nfserr = ops->proc_layoutcommit(inode, lcp); nfs4_put_stid(&ls->ls_stid); out: return nfserr; } static __be32 nfsd4_layoutreturn(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_layoutreturn *lrp) { struct svc_fh *current_fh = &cstate->current_fh; __be32 nfserr; nfserr = fh_verify(rqstp, current_fh, 0, NFSD_MAY_NOP); if (nfserr) goto out; nfserr = nfserr_layoutunavailable; if (!nfsd4_layout_verify(current_fh->fh_export, lrp->lr_layout_type)) goto out; switch (lrp->lr_seg.iomode) { case IOMODE_READ: case IOMODE_RW: case IOMODE_ANY: break; default: dprintk("%s: invalid iomode %d\n", __func__, lrp->lr_seg.iomode); nfserr = nfserr_inval; goto out; } switch (lrp->lr_return_type) { case RETURN_FILE: nfserr = nfsd4_return_file_layouts(rqstp, cstate, lrp); break; case RETURN_FSID: case RETURN_ALL: nfserr = nfsd4_return_client_layouts(rqstp, cstate, lrp); break; default: dprintk("%s: invalid return_type %d\n", __func__, lrp->lr_return_type); nfserr = nfserr_inval; break; } out: return nfserr; } #endif /* CONFIG_NFSD_PNFS */ /* * NULL call. */ static __be32 nfsd4_proc_null(struct svc_rqst *rqstp, void *argp, void *resp) { return nfs_ok; } static inline void nfsd4_increment_op_stats(u32 opnum) { if (opnum >= FIRST_NFS4_OP && opnum <= LAST_NFS4_OP) nfsdstats.nfs4_opcount[opnum]++; } typedef __be32(*nfsd4op_func)(struct svc_rqst *, struct nfsd4_compound_state *, void *); typedef u32(*nfsd4op_rsize)(struct svc_rqst *, struct nfsd4_op *op); typedef void(*stateid_setter)(struct nfsd4_compound_state *, void *); typedef void(*stateid_getter)(struct nfsd4_compound_state *, void *); enum nfsd4_op_flags { ALLOWED_WITHOUT_FH = 1 << 0, /* No current filehandle required */ ALLOWED_ON_ABSENT_FS = 1 << 1, /* ops processed on absent fs */ ALLOWED_AS_FIRST_OP = 1 << 2, /* ops reqired first in compound */ /* For rfc 5661 section 2.6.3.1.1: */ OP_HANDLES_WRONGSEC = 1 << 3, OP_IS_PUTFH_LIKE = 1 << 4, /* * These are the ops whose result size we estimate before * encoding, to avoid performing an op then not being able to * respond or cache a response. This includes writes and setattrs * as well as the operations usually called "nonidempotent": */ OP_MODIFIES_SOMETHING = 1 << 5, /* * Cache compounds containing these ops in the xid-based drc: * We use the DRC for compounds containing non-idempotent * operations, *except* those that are 4.1-specific (since * sessions provide their own EOS), and except for stateful * operations other than setclientid and setclientid_confirm * (since sequence numbers provide EOS for open, lock, etc in * the v4.0 case). */ OP_CACHEME = 1 << 6, /* * These are ops which clear current state id. */ OP_CLEAR_STATEID = 1 << 7, }; struct nfsd4_operation { nfsd4op_func op_func; u32 op_flags; char *op_name; /* Try to get response size before operation */ nfsd4op_rsize op_rsize_bop; stateid_getter op_get_currentstateid; stateid_setter op_set_currentstateid; }; static struct nfsd4_operation nfsd4_ops[]; static const char *nfsd4_op_name(unsigned opnum); /* * Enforce NFSv4.1 COMPOUND ordering rules: * * Also note, enforced elsewhere: * - SEQUENCE other than as first op results in * NFS4ERR_SEQUENCE_POS. (Enforced in nfsd4_sequence().) * - BIND_CONN_TO_SESSION must be the only op in its compound. * (Enforced in nfsd4_bind_conn_to_session().) * - DESTROY_SESSION must be the final operation in a compound, if * sessionid's in SEQUENCE and DESTROY_SESSION are the same. * (Enforced in nfsd4_destroy_session().) */ static __be32 nfs41_check_op_ordering(struct nfsd4_compoundargs *args) { struct nfsd4_op *op = &args->ops[0]; /* These ordering requirements don't apply to NFSv4.0: */ if (args->minorversion == 0) return nfs_ok; /* This is weird, but OK, not our problem: */ if (args->opcnt == 0) return nfs_ok; if (op->status == nfserr_op_illegal) return nfs_ok; if (!(nfsd4_ops[op->opnum].op_flags & ALLOWED_AS_FIRST_OP)) return nfserr_op_not_in_session; if (op->opnum == OP_SEQUENCE) return nfs_ok; if (args->opcnt != 1) return nfserr_not_only_op; return nfs_ok; } static inline struct nfsd4_operation *OPDESC(struct nfsd4_op *op) { return &nfsd4_ops[op->opnum]; } bool nfsd4_cache_this_op(struct nfsd4_op *op) { if (op->opnum == OP_ILLEGAL) return false; return OPDESC(op)->op_flags & OP_CACHEME; } static bool need_wrongsec_check(struct svc_rqst *rqstp) { struct nfsd4_compoundres *resp = rqstp->rq_resp; struct nfsd4_compoundargs *argp = rqstp->rq_argp; struct nfsd4_op *this = &argp->ops[resp->opcnt - 1]; struct nfsd4_op *next = &argp->ops[resp->opcnt]; struct nfsd4_operation *thisd; struct nfsd4_operation *nextd; thisd = OPDESC(this); /* * Most ops check wronsec on our own; only the putfh-like ops * have special rules. */ if (!(thisd->op_flags & OP_IS_PUTFH_LIKE)) return false; /* * rfc 5661 2.6.3.1.1.6: don't bother erroring out a * put-filehandle operation if we're not going to use the * result: */ if (argp->opcnt == resp->opcnt) return false; if (next->opnum == OP_ILLEGAL) return false; nextd = OPDESC(next); /* * Rest of 2.6.3.1.1: certain operations will return WRONGSEC * errors themselves as necessary; others should check for them * now: */ return !(nextd->op_flags & OP_HANDLES_WRONGSEC); } static void svcxdr_init_encode(struct svc_rqst *rqstp, struct nfsd4_compoundres *resp) { struct xdr_stream *xdr = &resp->xdr; struct xdr_buf *buf = &rqstp->rq_res; struct kvec *head = buf->head; xdr->buf = buf; xdr->iov = head; xdr->p = head->iov_base + head->iov_len; xdr->end = head->iov_base + PAGE_SIZE - rqstp->rq_auth_slack; /* Tail and page_len should be zero at this point: */ buf->len = buf->head[0].iov_len; xdr->scratch.iov_len = 0; xdr->page_ptr = buf->pages - 1; buf->buflen = PAGE_SIZE * (1 + rqstp->rq_page_end - buf->pages) - rqstp->rq_auth_slack; } /* * COMPOUND call. */ static __be32 nfsd4_proc_compound(struct svc_rqst *rqstp, struct nfsd4_compoundargs *args, struct nfsd4_compoundres *resp) { struct nfsd4_op *op; struct nfsd4_operation *opdesc; struct nfsd4_compound_state *cstate = &resp->cstate; struct svc_fh *current_fh = &cstate->current_fh; struct svc_fh *save_fh = &cstate->save_fh; __be32 status; svcxdr_init_encode(rqstp, resp); resp->tagp = resp->xdr.p; /* reserve space for: taglen, tag, and opcnt */ xdr_reserve_space(&resp->xdr, 8 + args->taglen); resp->taglen = args->taglen; resp->tag = args->tag; resp->rqstp = rqstp; cstate->minorversion = args->minorversion; fh_init(current_fh, NFS4_FHSIZE); fh_init(save_fh, NFS4_FHSIZE); /* * Don't use the deferral mechanism for NFSv4; compounds make it * too hard to avoid non-idempotency problems. */ clear_bit(RQ_USEDEFERRAL, &rqstp->rq_flags); /* * According to RFC3010, this takes precedence over all other errors. */ status = nfserr_minor_vers_mismatch; if (nfsd_minorversion(args->minorversion, NFSD_TEST) <= 0) goto out; status = nfs41_check_op_ordering(args); if (status) { op = &args->ops[0]; op->status = status; goto encode_op; } while (!status && resp->opcnt < args->opcnt) { op = &args->ops[resp->opcnt++]; dprintk("nfsv4 compound op #%d/%d: %d (%s)\n", resp->opcnt, args->opcnt, op->opnum, nfsd4_op_name(op->opnum)); /* * The XDR decode routines may have pre-set op->status; * for example, if there is a miscellaneous XDR error * it will be set to nfserr_bad_xdr. */ if (op->status) { if (op->opnum == OP_OPEN) op->status = nfsd4_open_omfg(rqstp, cstate, op); goto encode_op; } opdesc = OPDESC(op); if (!current_fh->fh_dentry) { if (!(opdesc->op_flags & ALLOWED_WITHOUT_FH)) { op->status = nfserr_nofilehandle; goto encode_op; } } else if (current_fh->fh_export->ex_fslocs.migrated && !(opdesc->op_flags & ALLOWED_ON_ABSENT_FS)) { op->status = nfserr_moved; goto encode_op; } fh_clear_wcc(current_fh); /* If op is non-idempotent */ if (opdesc->op_flags & OP_MODIFIES_SOMETHING) { /* * Don't execute this op if we couldn't encode a * succesful reply: */ u32 plen = opdesc->op_rsize_bop(rqstp, op); /* * Plus if there's another operation, make sure * we'll have space to at least encode an error: */ if (resp->opcnt < args->opcnt) plen += COMPOUND_ERR_SLACK_SPACE; op->status = nfsd4_check_resp_size(resp, plen); } if (op->status) goto encode_op; if (opdesc->op_get_currentstateid) opdesc->op_get_currentstateid(cstate, &op->u); op->status = opdesc->op_func(rqstp, cstate, &op->u); if (!op->status) { if (opdesc->op_set_currentstateid) opdesc->op_set_currentstateid(cstate, &op->u); if (opdesc->op_flags & OP_CLEAR_STATEID) clear_current_stateid(cstate); if (need_wrongsec_check(rqstp)) op->status = check_nfsd_access(current_fh->fh_export, rqstp); } encode_op: /* Only from SEQUENCE */ if (cstate->status == nfserr_replay_cache) { dprintk("%s NFS4.1 replay from cache\n", __func__); status = op->status; goto out; } if (op->status == nfserr_replay_me) { op->replay = &cstate->replay_owner->so_replay; nfsd4_encode_replay(&resp->xdr, op); status = op->status = op->replay->rp_status; } else { nfsd4_encode_operation(resp, op); status = op->status; } dprintk("nfsv4 compound op %p opcnt %d #%d: %d: status %d\n", args->ops, args->opcnt, resp->opcnt, op->opnum, be32_to_cpu(status)); nfsd4_cstate_clear_replay(cstate); nfsd4_increment_op_stats(op->opnum); } cstate->status = status; fh_put(current_fh); fh_put(save_fh); BUG_ON(cstate->replay_owner); out: /* Reset deferral mechanism for RPC deferrals */ set_bit(RQ_USEDEFERRAL, &rqstp->rq_flags); dprintk("nfsv4 compound returned %d\n", ntohl(status)); return status; } #define op_encode_hdr_size (2) #define op_encode_stateid_maxsz (XDR_QUADLEN(NFS4_STATEID_SIZE)) #define op_encode_verifier_maxsz (XDR_QUADLEN(NFS4_VERIFIER_SIZE)) #define op_encode_change_info_maxsz (5) #define nfs4_fattr_bitmap_maxsz (4) /* We'll fall back on returning no lockowner if run out of space: */ #define op_encode_lockowner_maxsz (0) #define op_encode_lock_denied_maxsz (8 + op_encode_lockowner_maxsz) #define nfs4_owner_maxsz (1 + XDR_QUADLEN(IDMAP_NAMESZ)) #define op_encode_ace_maxsz (3 + nfs4_owner_maxsz) #define op_encode_delegation_maxsz (1 + op_encode_stateid_maxsz + 1 + \ op_encode_ace_maxsz) #define op_encode_channel_attrs_maxsz (6 + 1 + 1) static inline u32 nfsd4_only_status_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size) * sizeof(__be32); } static inline u32 nfsd4_status_stateid_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_stateid_maxsz)* sizeof(__be32); } static inline u32 nfsd4_access_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { /* ac_supported, ac_resp_access */ return (op_encode_hdr_size + 2)* sizeof(__be32); } static inline u32 nfsd4_commit_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_verifier_maxsz) * sizeof(__be32); } static inline u32 nfsd4_create_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_change_info_maxsz + nfs4_fattr_bitmap_maxsz) * sizeof(__be32); } /* * Note since this is an idempotent operation we won't insist on failing * the op prematurely if the estimate is too large. We may turn off splice * reads unnecessarily. */ static inline u32 nfsd4_getattr_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { u32 *bmap = op->u.getattr.ga_bmval; u32 bmap0 = bmap[0], bmap1 = bmap[1], bmap2 = bmap[2]; u32 ret = 0; if (bmap0 & FATTR4_WORD0_ACL) return svc_max_payload(rqstp); if (bmap0 & FATTR4_WORD0_FS_LOCATIONS) return svc_max_payload(rqstp); if (bmap1 & FATTR4_WORD1_OWNER) { ret += IDMAP_NAMESZ + 4; bmap1 &= ~FATTR4_WORD1_OWNER; } if (bmap1 & FATTR4_WORD1_OWNER_GROUP) { ret += IDMAP_NAMESZ + 4; bmap1 &= ~FATTR4_WORD1_OWNER_GROUP; } if (bmap0 & FATTR4_WORD0_FILEHANDLE) { ret += NFS4_FHSIZE + 4; bmap0 &= ~FATTR4_WORD0_FILEHANDLE; } if (bmap2 & FATTR4_WORD2_SECURITY_LABEL) { ret += NFS4_MAXLABELLEN + 12; bmap2 &= ~FATTR4_WORD2_SECURITY_LABEL; } /* * Largest of remaining attributes are 16 bytes (e.g., * supported_attributes) */ ret += 16 * (hweight32(bmap0) + hweight32(bmap1) + hweight32(bmap2)); /* bitmask, length */ ret += 20; return ret; } static inline u32 nfsd4_getfh_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1) * sizeof(__be32) + NFS4_FHSIZE; } static inline u32 nfsd4_link_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_change_info_maxsz) * sizeof(__be32); } static inline u32 nfsd4_lock_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_lock_denied_maxsz) * sizeof(__be32); } static inline u32 nfsd4_open_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_stateid_maxsz + op_encode_change_info_maxsz + 1 + nfs4_fattr_bitmap_maxsz + op_encode_delegation_maxsz) * sizeof(__be32); } static inline u32 nfsd4_read_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { u32 maxcount = 0, rlen = 0; maxcount = svc_max_payload(rqstp); rlen = min(op->u.read.rd_length, maxcount); return (op_encode_hdr_size + 2 + XDR_QUADLEN(rlen)) * sizeof(__be32); } static inline u32 nfsd4_readdir_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { u32 maxcount = 0, rlen = 0; maxcount = svc_max_payload(rqstp); rlen = min(op->u.readdir.rd_maxcount, maxcount); return (op_encode_hdr_size + op_encode_verifier_maxsz + XDR_QUADLEN(rlen)) * sizeof(__be32); } static inline u32 nfsd4_readlink_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1) * sizeof(__be32) + PAGE_SIZE; } static inline u32 nfsd4_remove_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_change_info_maxsz) * sizeof(__be32); } static inline u32 nfsd4_rename_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_change_info_maxsz + op_encode_change_info_maxsz) * sizeof(__be32); } static inline u32 nfsd4_sequence_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + 5) * sizeof(__be32); } static inline u32 nfsd4_test_stateid_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1 + op->u.test_stateid.ts_num_ids) * sizeof(__be32); } static inline u32 nfsd4_setattr_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + nfs4_fattr_bitmap_maxsz) * sizeof(__be32); } static inline u32 nfsd4_secinfo_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + RPC_AUTH_MAXFLAVOR * (4 + XDR_QUADLEN(GSS_OID_MAX_LEN))) * sizeof(__be32); } static inline u32 nfsd4_setclientid_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 2 + XDR_QUADLEN(NFS4_VERIFIER_SIZE)) * sizeof(__be32); } static inline u32 nfsd4_write_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 2 + op_encode_verifier_maxsz) * sizeof(__be32); } static inline u32 nfsd4_exchange_id_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 2 + 1 + /* eir_clientid, eir_sequenceid */\ 1 + 1 + /* eir_flags, spr_how */\ 4 + /* spo_must_enforce & _allow with bitmap */\ 2 + /*eir_server_owner.so_minor_id */\ /* eir_server_owner.so_major_id<> */\ XDR_QUADLEN(NFS4_OPAQUE_LIMIT) + 1 +\ /* eir_server_scope<> */\ XDR_QUADLEN(NFS4_OPAQUE_LIMIT) + 1 +\ 1 + /* eir_server_impl_id array length */\ 0 /* ignored eir_server_impl_id contents */) * sizeof(__be32); } static inline u32 nfsd4_bind_conn_to_session_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + \ XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + /* bctsr_sessid */\ 2 /* bctsr_dir, use_conn_in_rdma_mode */) * sizeof(__be32); } static inline u32 nfsd4_create_session_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + \ XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + /* sessionid */\ 2 + /* csr_sequence, csr_flags */\ op_encode_channel_attrs_maxsz + \ op_encode_channel_attrs_maxsz) * sizeof(__be32); } static inline u32 nfsd4_copy_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1 /* wr_callback */ + op_encode_stateid_maxsz /* wr_callback */ + 2 /* wr_count */ + 1 /* wr_committed */ + op_encode_verifier_maxsz + 1 /* cr_consecutive */ + 1 /* cr_synchronous */) * sizeof(__be32); } #ifdef CONFIG_NFSD_PNFS static inline u32 nfsd4_getdeviceinfo_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { u32 maxcount = 0, rlen = 0; maxcount = svc_max_payload(rqstp); rlen = min(op->u.getdeviceinfo.gd_maxcount, maxcount); return (op_encode_hdr_size + 1 /* gd_layout_type*/ + XDR_QUADLEN(rlen) + 2 /* gd_notify_types */) * sizeof(__be32); } /* * At this stage we don't really know what layout driver will handle the request, * so we need to define an arbitrary upper bound here. */ #define MAX_LAYOUT_SIZE 128 static inline u32 nfsd4_layoutget_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1 /* logr_return_on_close */ + op_encode_stateid_maxsz + 1 /* nr of layouts */ + MAX_LAYOUT_SIZE) * sizeof(__be32); } static inline u32 nfsd4_layoutcommit_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1 /* locr_newsize */ + 2 /* ns_size */) * sizeof(__be32); } static inline u32 nfsd4_layoutreturn_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1 /* lrs_stateid */ + op_encode_stateid_maxsz) * sizeof(__be32); } #endif /* CONFIG_NFSD_PNFS */ static inline u32 nfsd4_seek_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 3) * sizeof(__be32); } static struct nfsd4_operation nfsd4_ops[] = { [OP_ACCESS] = { .op_func = (nfsd4op_func)nfsd4_access, .op_name = "OP_ACCESS", .op_rsize_bop = (nfsd4op_rsize)nfsd4_access_rsize, }, [OP_CLOSE] = { .op_func = (nfsd4op_func)nfsd4_close, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_CLOSE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_status_stateid_rsize, .op_get_currentstateid = (stateid_getter)nfsd4_get_closestateid, .op_set_currentstateid = (stateid_setter)nfsd4_set_closestateid, }, [OP_COMMIT] = { .op_func = (nfsd4op_func)nfsd4_commit, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_COMMIT", .op_rsize_bop = (nfsd4op_rsize)nfsd4_commit_rsize, }, [OP_CREATE] = { .op_func = (nfsd4op_func)nfsd4_create, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME | OP_CLEAR_STATEID, .op_name = "OP_CREATE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_create_rsize, }, [OP_DELEGRETURN] = { .op_func = (nfsd4op_func)nfsd4_delegreturn, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_DELEGRETURN", .op_rsize_bop = nfsd4_only_status_rsize, .op_get_currentstateid = (stateid_getter)nfsd4_get_delegreturnstateid, }, [OP_GETATTR] = { .op_func = (nfsd4op_func)nfsd4_getattr, .op_flags = ALLOWED_ON_ABSENT_FS, .op_rsize_bop = nfsd4_getattr_rsize, .op_name = "OP_GETATTR", }, [OP_GETFH] = { .op_func = (nfsd4op_func)nfsd4_getfh, .op_name = "OP_GETFH", .op_rsize_bop = (nfsd4op_rsize)nfsd4_getfh_rsize, }, [OP_LINK] = { .op_func = (nfsd4op_func)nfsd4_link, .op_flags = ALLOWED_ON_ABSENT_FS | OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_LINK", .op_rsize_bop = (nfsd4op_rsize)nfsd4_link_rsize, }, [OP_LOCK] = { .op_func = (nfsd4op_func)nfsd4_lock, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_LOCK", .op_rsize_bop = (nfsd4op_rsize)nfsd4_lock_rsize, .op_set_currentstateid = (stateid_setter)nfsd4_set_lockstateid, }, [OP_LOCKT] = { .op_func = (nfsd4op_func)nfsd4_lockt, .op_name = "OP_LOCKT", .op_rsize_bop = (nfsd4op_rsize)nfsd4_lock_rsize, }, [OP_LOCKU] = { .op_func = (nfsd4op_func)nfsd4_locku, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_LOCKU", .op_rsize_bop = (nfsd4op_rsize)nfsd4_status_stateid_rsize, .op_get_currentstateid = (stateid_getter)nfsd4_get_lockustateid, }, [OP_LOOKUP] = { .op_func = (nfsd4op_func)nfsd4_lookup, .op_flags = OP_HANDLES_WRONGSEC | OP_CLEAR_STATEID, .op_name = "OP_LOOKUP", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_LOOKUPP] = { .op_func = (nfsd4op_func)nfsd4_lookupp, .op_flags = OP_HANDLES_WRONGSEC | OP_CLEAR_STATEID, .op_name = "OP_LOOKUPP", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_NVERIFY] = { .op_func = (nfsd4op_func)nfsd4_nverify, .op_name = "OP_NVERIFY", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_OPEN] = { .op_func = (nfsd4op_func)nfsd4_open, .op_flags = OP_HANDLES_WRONGSEC | OP_MODIFIES_SOMETHING, .op_name = "OP_OPEN", .op_rsize_bop = (nfsd4op_rsize)nfsd4_open_rsize, .op_set_currentstateid = (stateid_setter)nfsd4_set_openstateid, }, [OP_OPEN_CONFIRM] = { .op_func = (nfsd4op_func)nfsd4_open_confirm, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_OPEN_CONFIRM", .op_rsize_bop = (nfsd4op_rsize)nfsd4_status_stateid_rsize, }, [OP_OPEN_DOWNGRADE] = { .op_func = (nfsd4op_func)nfsd4_open_downgrade, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_OPEN_DOWNGRADE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_status_stateid_rsize, .op_get_currentstateid = (stateid_getter)nfsd4_get_opendowngradestateid, .op_set_currentstateid = (stateid_setter)nfsd4_set_opendowngradestateid, }, [OP_PUTFH] = { .op_func = (nfsd4op_func)nfsd4_putfh, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_IS_PUTFH_LIKE | OP_CLEAR_STATEID, .op_name = "OP_PUTFH", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_PUTPUBFH] = { .op_func = (nfsd4op_func)nfsd4_putrootfh, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_IS_PUTFH_LIKE | OP_CLEAR_STATEID, .op_name = "OP_PUTPUBFH", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_PUTROOTFH] = { .op_func = (nfsd4op_func)nfsd4_putrootfh, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_IS_PUTFH_LIKE | OP_CLEAR_STATEID, .op_name = "OP_PUTROOTFH", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_READ] = { .op_func = (nfsd4op_func)nfsd4_read, .op_name = "OP_READ", .op_rsize_bop = (nfsd4op_rsize)nfsd4_read_rsize, .op_get_currentstateid = (stateid_getter)nfsd4_get_readstateid, }, [OP_READDIR] = { .op_func = (nfsd4op_func)nfsd4_readdir, .op_name = "OP_READDIR", .op_rsize_bop = (nfsd4op_rsize)nfsd4_readdir_rsize, }, [OP_READLINK] = { .op_func = (nfsd4op_func)nfsd4_readlink, .op_name = "OP_READLINK", .op_rsize_bop = (nfsd4op_rsize)nfsd4_readlink_rsize, }, [OP_REMOVE] = { .op_func = (nfsd4op_func)nfsd4_remove, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_REMOVE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_remove_rsize, }, [OP_RENAME] = { .op_func = (nfsd4op_func)nfsd4_rename, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_RENAME", .op_rsize_bop = (nfsd4op_rsize)nfsd4_rename_rsize, }, [OP_RENEW] = { .op_func = (nfsd4op_func)nfsd4_renew, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_MODIFIES_SOMETHING, .op_name = "OP_RENEW", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_RESTOREFH] = { .op_func = (nfsd4op_func)nfsd4_restorefh, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_IS_PUTFH_LIKE | OP_MODIFIES_SOMETHING, .op_name = "OP_RESTOREFH", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_SAVEFH] = { .op_func = (nfsd4op_func)nfsd4_savefh, .op_flags = OP_HANDLES_WRONGSEC | OP_MODIFIES_SOMETHING, .op_name = "OP_SAVEFH", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_SECINFO] = { .op_func = (nfsd4op_func)nfsd4_secinfo, .op_flags = OP_HANDLES_WRONGSEC, .op_name = "OP_SECINFO", .op_rsize_bop = (nfsd4op_rsize)nfsd4_secinfo_rsize, }, [OP_SETATTR] = { .op_func = (nfsd4op_func)nfsd4_setattr, .op_name = "OP_SETATTR", .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_rsize_bop = (nfsd4op_rsize)nfsd4_setattr_rsize, .op_get_currentstateid = (stateid_getter)nfsd4_get_setattrstateid, }, [OP_SETCLIENTID] = { .op_func = (nfsd4op_func)nfsd4_setclientid, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_SETCLIENTID", .op_rsize_bop = (nfsd4op_rsize)nfsd4_setclientid_rsize, }, [OP_SETCLIENTID_CONFIRM] = { .op_func = (nfsd4op_func)nfsd4_setclientid_confirm, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_SETCLIENTID_CONFIRM", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_VERIFY] = { .op_func = (nfsd4op_func)nfsd4_verify, .op_name = "OP_VERIFY", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_WRITE] = { .op_func = (nfsd4op_func)nfsd4_write, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_WRITE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_write_rsize, .op_get_currentstateid = (stateid_getter)nfsd4_get_writestateid, }, [OP_RELEASE_LOCKOWNER] = { .op_func = (nfsd4op_func)nfsd4_release_lockowner, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_MODIFIES_SOMETHING, .op_name = "OP_RELEASE_LOCKOWNER", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, /* NFSv4.1 operations */ [OP_EXCHANGE_ID] = { .op_func = (nfsd4op_func)nfsd4_exchange_id, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_AS_FIRST_OP | OP_MODIFIES_SOMETHING, .op_name = "OP_EXCHANGE_ID", .op_rsize_bop = (nfsd4op_rsize)nfsd4_exchange_id_rsize, }, [OP_BACKCHANNEL_CTL] = { .op_func = (nfsd4op_func)nfsd4_backchannel_ctl, .op_flags = ALLOWED_WITHOUT_FH | OP_MODIFIES_SOMETHING, .op_name = "OP_BACKCHANNEL_CTL", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_BIND_CONN_TO_SESSION] = { .op_func = (nfsd4op_func)nfsd4_bind_conn_to_session, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_AS_FIRST_OP | OP_MODIFIES_SOMETHING, .op_name = "OP_BIND_CONN_TO_SESSION", .op_rsize_bop = (nfsd4op_rsize)nfsd4_bind_conn_to_session_rsize, }, [OP_CREATE_SESSION] = { .op_func = (nfsd4op_func)nfsd4_create_session, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_AS_FIRST_OP | OP_MODIFIES_SOMETHING, .op_name = "OP_CREATE_SESSION", .op_rsize_bop = (nfsd4op_rsize)nfsd4_create_session_rsize, }, [OP_DESTROY_SESSION] = { .op_func = (nfsd4op_func)nfsd4_destroy_session, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_AS_FIRST_OP | OP_MODIFIES_SOMETHING, .op_name = "OP_DESTROY_SESSION", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_SEQUENCE] = { .op_func = (nfsd4op_func)nfsd4_sequence, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_AS_FIRST_OP, .op_name = "OP_SEQUENCE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_sequence_rsize, }, [OP_DESTROY_CLIENTID] = { .op_func = (nfsd4op_func)nfsd4_destroy_clientid, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_AS_FIRST_OP | OP_MODIFIES_SOMETHING, .op_name = "OP_DESTROY_CLIENTID", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_RECLAIM_COMPLETE] = { .op_func = (nfsd4op_func)nfsd4_reclaim_complete, .op_flags = ALLOWED_WITHOUT_FH | OP_MODIFIES_SOMETHING, .op_name = "OP_RECLAIM_COMPLETE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_SECINFO_NO_NAME] = { .op_func = (nfsd4op_func)nfsd4_secinfo_no_name, .op_flags = OP_HANDLES_WRONGSEC, .op_name = "OP_SECINFO_NO_NAME", .op_rsize_bop = (nfsd4op_rsize)nfsd4_secinfo_rsize, }, [OP_TEST_STATEID] = { .op_func = (nfsd4op_func)nfsd4_test_stateid, .op_flags = ALLOWED_WITHOUT_FH, .op_name = "OP_TEST_STATEID", .op_rsize_bop = (nfsd4op_rsize)nfsd4_test_stateid_rsize, }, [OP_FREE_STATEID] = { .op_func = (nfsd4op_func)nfsd4_free_stateid, .op_flags = ALLOWED_WITHOUT_FH | OP_MODIFIES_SOMETHING, .op_name = "OP_FREE_STATEID", .op_get_currentstateid = (stateid_getter)nfsd4_get_freestateid, .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, #ifdef CONFIG_NFSD_PNFS [OP_GETDEVICEINFO] = { .op_func = (nfsd4op_func)nfsd4_getdeviceinfo, .op_flags = ALLOWED_WITHOUT_FH, .op_name = "OP_GETDEVICEINFO", .op_rsize_bop = (nfsd4op_rsize)nfsd4_getdeviceinfo_rsize, }, [OP_LAYOUTGET] = { .op_func = (nfsd4op_func)nfsd4_layoutget, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_LAYOUTGET", .op_rsize_bop = (nfsd4op_rsize)nfsd4_layoutget_rsize, }, [OP_LAYOUTCOMMIT] = { .op_func = (nfsd4op_func)nfsd4_layoutcommit, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_LAYOUTCOMMIT", .op_rsize_bop = (nfsd4op_rsize)nfsd4_layoutcommit_rsize, }, [OP_LAYOUTRETURN] = { .op_func = (nfsd4op_func)nfsd4_layoutreturn, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_LAYOUTRETURN", .op_rsize_bop = (nfsd4op_rsize)nfsd4_layoutreturn_rsize, }, #endif /* CONFIG_NFSD_PNFS */ /* NFSv4.2 operations */ [OP_ALLOCATE] = { .op_func = (nfsd4op_func)nfsd4_allocate, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_ALLOCATE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_DEALLOCATE] = { .op_func = (nfsd4op_func)nfsd4_deallocate, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_DEALLOCATE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_CLONE] = { .op_func = (nfsd4op_func)nfsd4_clone, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_CLONE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_COPY] = { .op_func = (nfsd4op_func)nfsd4_copy, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_COPY", .op_rsize_bop = (nfsd4op_rsize)nfsd4_copy_rsize, }, [OP_SEEK] = { .op_func = (nfsd4op_func)nfsd4_seek, .op_name = "OP_SEEK", .op_rsize_bop = (nfsd4op_rsize)nfsd4_seek_rsize, }, }; /** * nfsd4_spo_must_allow - Determine if the compound op contains an * operation that is allowed to be sent with machine credentials * * @rqstp: a pointer to the struct svc_rqst * * Checks to see if the compound contains a spo_must_allow op * and confirms that it was sent with the proper machine creds. */ bool nfsd4_spo_must_allow(struct svc_rqst *rqstp) { struct nfsd4_compoundres *resp = rqstp->rq_resp; struct nfsd4_compoundargs *argp = rqstp->rq_argp; struct nfsd4_op *this = &argp->ops[resp->opcnt - 1]; struct nfsd4_compound_state *cstate = &resp->cstate; struct nfs4_op_map *allow = &cstate->clp->cl_spo_must_allow; u32 opiter; if (!cstate->minorversion) return false; if (cstate->spo_must_allowed == true) return true; opiter = resp->opcnt; while (opiter < argp->opcnt) { this = &argp->ops[opiter++]; if (test_bit(this->opnum, allow->u.longs) && cstate->clp->cl_mach_cred && nfsd4_mach_creds_match(cstate->clp, rqstp)) { cstate->spo_must_allowed = true; return true; } } cstate->spo_must_allowed = false; return false; } int nfsd4_max_reply(struct svc_rqst *rqstp, struct nfsd4_op *op) { if (op->opnum == OP_ILLEGAL || op->status == nfserr_notsupp) return op_encode_hdr_size * sizeof(__be32); BUG_ON(OPDESC(op)->op_rsize_bop == NULL); return OPDESC(op)->op_rsize_bop(rqstp, op); } void warn_on_nonidempotent_op(struct nfsd4_op *op) { if (OPDESC(op)->op_flags & OP_MODIFIES_SOMETHING) { pr_err("unable to encode reply to nonidempotent op %d (%s)\n", op->opnum, nfsd4_op_name(op->opnum)); WARN_ON_ONCE(1); } } static const char *nfsd4_op_name(unsigned opnum) { if (opnum < ARRAY_SIZE(nfsd4_ops)) return nfsd4_ops[opnum].op_name; return "unknown_operation"; } #define nfsd4_voidres nfsd4_voidargs struct nfsd4_voidargs { int dummy; }; static struct svc_procedure nfsd_procedures4[2] = { [NFSPROC4_NULL] = { .pc_func = (svc_procfunc) nfsd4_proc_null, .pc_encode = (kxdrproc_t) nfs4svc_encode_voidres, .pc_argsize = sizeof(struct nfsd4_voidargs), .pc_ressize = sizeof(struct nfsd4_voidres), .pc_cachetype = RC_NOCACHE, .pc_xdrressize = 1, }, [NFSPROC4_COMPOUND] = { .pc_func = (svc_procfunc) nfsd4_proc_compound, .pc_decode = (kxdrproc_t) nfs4svc_decode_compoundargs, .pc_encode = (kxdrproc_t) nfs4svc_encode_compoundres, .pc_argsize = sizeof(struct nfsd4_compoundargs), .pc_ressize = sizeof(struct nfsd4_compoundres), .pc_release = nfsd4_release_compoundargs, .pc_cachetype = RC_NOCACHE, .pc_xdrressize = NFSD_BUFSIZE/4, }, }; struct svc_version nfsd_version4 = { .vs_vers = 4, .vs_nproc = 2, .vs_proc = nfsd_procedures4, .vs_dispatch = nfsd_dispatch, .vs_xdrsize = NFS4_SVC_XDRSIZE, .vs_rpcb_optnl = true, .vs_need_cong_ctrl = true, }; /* * Local variables: * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-129/c/bad_3335_0
crossvul-cpp_data_good_3335_0
/* * Server-side procedures for NFSv4. * * Copyright (c) 2002 The Regents of the University of Michigan. * All rights reserved. * * Kendrick Smith <kmsmith@umich.edu> * Andy Adamson <andros@umich.edu> * * 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 ``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 <linux/file.h> #include <linux/falloc.h> #include <linux/slab.h> #include "idmap.h" #include "cache.h" #include "xdr4.h" #include "vfs.h" #include "current_stateid.h" #include "netns.h" #include "acl.h" #include "pnfs.h" #include "trace.h" #ifdef CONFIG_NFSD_V4_SECURITY_LABEL #include <linux/security.h> static inline void nfsd4_security_inode_setsecctx(struct svc_fh *resfh, struct xdr_netobj *label, u32 *bmval) { struct inode *inode = d_inode(resfh->fh_dentry); int status; inode_lock(inode); status = security_inode_setsecctx(resfh->fh_dentry, label->data, label->len); inode_unlock(inode); if (status) /* * XXX: We should really fail the whole open, but we may * already have created a new file, so it may be too * late. For now this seems the least of evils: */ bmval[2] &= ~FATTR4_WORD2_SECURITY_LABEL; return; } #else static inline void nfsd4_security_inode_setsecctx(struct svc_fh *resfh, struct xdr_netobj *label, u32 *bmval) { } #endif #define NFSDDBG_FACILITY NFSDDBG_PROC static u32 nfsd_attrmask[] = { NFSD_WRITEABLE_ATTRS_WORD0, NFSD_WRITEABLE_ATTRS_WORD1, NFSD_WRITEABLE_ATTRS_WORD2 }; static u32 nfsd41_ex_attrmask[] = { NFSD_SUPPATTR_EXCLCREAT_WORD0, NFSD_SUPPATTR_EXCLCREAT_WORD1, NFSD_SUPPATTR_EXCLCREAT_WORD2 }; static __be32 check_attr_support(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, u32 *bmval, u32 *writable) { struct dentry *dentry = cstate->current_fh.fh_dentry; struct svc_export *exp = cstate->current_fh.fh_export; if (!nfsd_attrs_supported(cstate->minorversion, bmval)) return nfserr_attrnotsupp; if ((bmval[0] & FATTR4_WORD0_ACL) && !IS_POSIXACL(d_inode(dentry))) return nfserr_attrnotsupp; if ((bmval[2] & FATTR4_WORD2_SECURITY_LABEL) && !(exp->ex_flags & NFSEXP_SECURITY_LABEL)) return nfserr_attrnotsupp; if (writable && !bmval_is_subset(bmval, writable)) return nfserr_inval; if (writable && (bmval[2] & FATTR4_WORD2_MODE_UMASK) && (bmval[1] & FATTR4_WORD1_MODE)) return nfserr_inval; return nfs_ok; } static __be32 nfsd4_check_open_attributes(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_open *open) { __be32 status = nfs_ok; if (open->op_create == NFS4_OPEN_CREATE) { if (open->op_createmode == NFS4_CREATE_UNCHECKED || open->op_createmode == NFS4_CREATE_GUARDED) status = check_attr_support(rqstp, cstate, open->op_bmval, nfsd_attrmask); else if (open->op_createmode == NFS4_CREATE_EXCLUSIVE4_1) status = check_attr_support(rqstp, cstate, open->op_bmval, nfsd41_ex_attrmask); } return status; } static int is_create_with_attrs(struct nfsd4_open *open) { return open->op_create == NFS4_OPEN_CREATE && (open->op_createmode == NFS4_CREATE_UNCHECKED || open->op_createmode == NFS4_CREATE_GUARDED || open->op_createmode == NFS4_CREATE_EXCLUSIVE4_1); } /* * if error occurs when setting the acl, just clear the acl bit * in the returned attr bitmap. */ static void do_set_nfs4_acl(struct svc_rqst *rqstp, struct svc_fh *fhp, struct nfs4_acl *acl, u32 *bmval) { __be32 status; status = nfsd4_set_nfs4_acl(rqstp, fhp, acl); if (status) /* * We should probably fail the whole open at this point, * but we've already created the file, so it's too late; * So this seems the least of evils: */ bmval[0] &= ~FATTR4_WORD0_ACL; } static inline void fh_dup2(struct svc_fh *dst, struct svc_fh *src) { fh_put(dst); dget(src->fh_dentry); if (src->fh_export) exp_get(src->fh_export); *dst = *src; } static __be32 do_open_permission(struct svc_rqst *rqstp, struct svc_fh *current_fh, struct nfsd4_open *open, int accmode) { __be32 status; if (open->op_truncate && !(open->op_share_access & NFS4_SHARE_ACCESS_WRITE)) return nfserr_inval; accmode |= NFSD_MAY_READ_IF_EXEC; if (open->op_share_access & NFS4_SHARE_ACCESS_READ) accmode |= NFSD_MAY_READ; if (open->op_share_access & NFS4_SHARE_ACCESS_WRITE) accmode |= (NFSD_MAY_WRITE | NFSD_MAY_TRUNC); if (open->op_share_deny & NFS4_SHARE_DENY_READ) accmode |= NFSD_MAY_WRITE; status = fh_verify(rqstp, current_fh, S_IFREG, accmode); return status; } static __be32 nfsd_check_obj_isreg(struct svc_fh *fh) { umode_t mode = d_inode(fh->fh_dentry)->i_mode; if (S_ISREG(mode)) return nfs_ok; if (S_ISDIR(mode)) return nfserr_isdir; /* * Using err_symlink as our catch-all case may look odd; but * there's no other obvious error for this case in 4.0, and we * happen to know that it will cause the linux v4 client to do * the right thing on attempts to open something other than a * regular file. */ return nfserr_symlink; } static void nfsd4_set_open_owner_reply_cache(struct nfsd4_compound_state *cstate, struct nfsd4_open *open, struct svc_fh *resfh) { if (nfsd4_has_session(cstate)) return; fh_copy_shallow(&open->op_openowner->oo_owner.so_replay.rp_openfh, &resfh->fh_handle); } static __be32 do_open_lookup(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_open *open, struct svc_fh **resfh) { struct svc_fh *current_fh = &cstate->current_fh; int accmode; __be32 status; *resfh = kmalloc(sizeof(struct svc_fh), GFP_KERNEL); if (!*resfh) return nfserr_jukebox; fh_init(*resfh, NFS4_FHSIZE); open->op_truncate = 0; if (open->op_create) { /* FIXME: check session persistence and pnfs flags. * The nfsv4.1 spec requires the following semantics: * * Persistent | pNFS | Server REQUIRED | Client Allowed * Reply Cache | server | | * -------------+--------+-----------------+-------------------- * no | no | EXCLUSIVE4_1 | EXCLUSIVE4_1 * | | | (SHOULD) * | | and EXCLUSIVE4 | or EXCLUSIVE4 * | | | (SHOULD NOT) * no | yes | EXCLUSIVE4_1 | EXCLUSIVE4_1 * yes | no | GUARDED4 | GUARDED4 * yes | yes | GUARDED4 | GUARDED4 */ /* * Note: create modes (UNCHECKED,GUARDED...) are the same * in NFSv4 as in v3 except EXCLUSIVE4_1. */ status = do_nfsd_create(rqstp, current_fh, open->op_fname.data, open->op_fname.len, &open->op_iattr, *resfh, open->op_createmode, (u32 *)open->op_verf.data, &open->op_truncate, &open->op_created); if (!status && open->op_label.len) nfsd4_security_inode_setsecctx(*resfh, &open->op_label, open->op_bmval); /* * Following rfc 3530 14.2.16, and rfc 5661 18.16.4 * use the returned bitmask to indicate which attributes * we used to store the verifier: */ if (nfsd_create_is_exclusive(open->op_createmode) && status == 0) open->op_bmval[1] |= (FATTR4_WORD1_TIME_ACCESS | FATTR4_WORD1_TIME_MODIFY); } else /* * Note this may exit with the parent still locked. * We will hold the lock until nfsd4_open's final * lookup, to prevent renames or unlinks until we've had * a chance to an acquire a delegation if appropriate. */ status = nfsd_lookup(rqstp, current_fh, open->op_fname.data, open->op_fname.len, *resfh); if (status) goto out; status = nfsd_check_obj_isreg(*resfh); if (status) goto out; if (is_create_with_attrs(open) && open->op_acl != NULL) do_set_nfs4_acl(rqstp, *resfh, open->op_acl, open->op_bmval); nfsd4_set_open_owner_reply_cache(cstate, open, *resfh); accmode = NFSD_MAY_NOP; if (open->op_created || open->op_claim_type == NFS4_OPEN_CLAIM_DELEGATE_CUR) accmode |= NFSD_MAY_OWNER_OVERRIDE; status = do_open_permission(rqstp, *resfh, open, accmode); set_change_info(&open->op_cinfo, current_fh); out: return status; } static __be32 do_open_fhandle(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_open *open) { struct svc_fh *current_fh = &cstate->current_fh; __be32 status; int accmode = 0; /* We don't know the target directory, and therefore can not * set the change info */ memset(&open->op_cinfo, 0, sizeof(struct nfsd4_change_info)); nfsd4_set_open_owner_reply_cache(cstate, open, current_fh); open->op_truncate = (open->op_iattr.ia_valid & ATTR_SIZE) && (open->op_iattr.ia_size == 0); /* * In the delegation case, the client is telling us about an * open that it *already* performed locally, some time ago. We * should let it succeed now if possible. * * In the case of a CLAIM_FH open, on the other hand, the client * may be counting on us to enforce permissions (the Linux 4.1 * client uses this for normal opens, for example). */ if (open->op_claim_type == NFS4_OPEN_CLAIM_DELEG_CUR_FH) accmode = NFSD_MAY_OWNER_OVERRIDE; status = do_open_permission(rqstp, current_fh, open, accmode); return status; } static void copy_clientid(clientid_t *clid, struct nfsd4_session *session) { struct nfsd4_sessionid *sid = (struct nfsd4_sessionid *)session->se_sessionid.data; clid->cl_boot = sid->clientid.cl_boot; clid->cl_id = sid->clientid.cl_id; } static __be32 nfsd4_open(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_open *open) { __be32 status; struct svc_fh *resfh = NULL; struct net *net = SVC_NET(rqstp); struct nfsd_net *nn = net_generic(net, nfsd_net_id); dprintk("NFSD: nfsd4_open filename %.*s op_openowner %p\n", (int)open->op_fname.len, open->op_fname.data, open->op_openowner); /* This check required by spec. */ if (open->op_create && open->op_claim_type != NFS4_OPEN_CLAIM_NULL) return nfserr_inval; open->op_created = 0; /* * RFC5661 18.51.3 * Before RECLAIM_COMPLETE done, server should deny new lock */ if (nfsd4_has_session(cstate) && !test_bit(NFSD4_CLIENT_RECLAIM_COMPLETE, &cstate->session->se_client->cl_flags) && open->op_claim_type != NFS4_OPEN_CLAIM_PREVIOUS) return nfserr_grace; if (nfsd4_has_session(cstate)) copy_clientid(&open->op_clientid, cstate->session); /* check seqid for replay. set nfs4_owner */ status = nfsd4_process_open1(cstate, open, nn); if (status == nfserr_replay_me) { struct nfs4_replay *rp = &open->op_openowner->oo_owner.so_replay; fh_put(&cstate->current_fh); fh_copy_shallow(&cstate->current_fh.fh_handle, &rp->rp_openfh); status = fh_verify(rqstp, &cstate->current_fh, 0, NFSD_MAY_NOP); if (status) dprintk("nfsd4_open: replay failed" " restoring previous filehandle\n"); else status = nfserr_replay_me; } if (status) goto out; if (open->op_xdr_error) { status = open->op_xdr_error; goto out; } status = nfsd4_check_open_attributes(rqstp, cstate, open); if (status) goto out; /* Openowner is now set, so sequence id will get bumped. Now we need * these checks before we do any creates: */ status = nfserr_grace; if (opens_in_grace(net) && open->op_claim_type != NFS4_OPEN_CLAIM_PREVIOUS) goto out; status = nfserr_no_grace; if (!opens_in_grace(net) && open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS) goto out; switch (open->op_claim_type) { case NFS4_OPEN_CLAIM_DELEGATE_CUR: case NFS4_OPEN_CLAIM_NULL: status = do_open_lookup(rqstp, cstate, open, &resfh); if (status) goto out; break; case NFS4_OPEN_CLAIM_PREVIOUS: status = nfs4_check_open_reclaim(&open->op_clientid, cstate, nn); if (status) goto out; open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED; case NFS4_OPEN_CLAIM_FH: case NFS4_OPEN_CLAIM_DELEG_CUR_FH: status = do_open_fhandle(rqstp, cstate, open); if (status) goto out; resfh = &cstate->current_fh; break; case NFS4_OPEN_CLAIM_DELEG_PREV_FH: case NFS4_OPEN_CLAIM_DELEGATE_PREV: dprintk("NFSD: unsupported OPEN claim type %d\n", open->op_claim_type); status = nfserr_notsupp; goto out; default: dprintk("NFSD: Invalid OPEN claim type %d\n", open->op_claim_type); status = nfserr_inval; goto out; } /* * nfsd4_process_open2() does the actual opening of the file. If * successful, it (1) truncates the file if open->op_truncate was * set, (2) sets open->op_stateid, (3) sets open->op_delegation. */ status = nfsd4_process_open2(rqstp, resfh, open); WARN(status && open->op_created, "nfsd4_process_open2 failed to open newly-created file! status=%u\n", be32_to_cpu(status)); out: if (resfh && resfh != &cstate->current_fh) { fh_dup2(&cstate->current_fh, resfh); fh_put(resfh); kfree(resfh); } nfsd4_cleanup_open_state(cstate, open); nfsd4_bump_seqid(cstate, status); return status; } /* * OPEN is the only seqid-mutating operation whose decoding can fail * with a seqid-mutating error (specifically, decoding of user names in * the attributes). Therefore we have to do some processing to look up * the stateowner so that we can bump the seqid. */ static __be32 nfsd4_open_omfg(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_op *op) { struct nfsd4_open *open = (struct nfsd4_open *)&op->u; if (!seqid_mutating_err(ntohl(op->status))) return op->status; if (nfsd4_has_session(cstate)) return op->status; open->op_xdr_error = op->status; return nfsd4_open(rqstp, cstate, open); } /* * filehandle-manipulating ops. */ static __be32 nfsd4_getfh(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct svc_fh **getfh) { if (!cstate->current_fh.fh_dentry) return nfserr_nofilehandle; *getfh = &cstate->current_fh; return nfs_ok; } static __be32 nfsd4_putfh(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_putfh *putfh) { fh_put(&cstate->current_fh); cstate->current_fh.fh_handle.fh_size = putfh->pf_fhlen; memcpy(&cstate->current_fh.fh_handle.fh_base, putfh->pf_fhval, putfh->pf_fhlen); return fh_verify(rqstp, &cstate->current_fh, 0, NFSD_MAY_BYPASS_GSS); } static __be32 nfsd4_putrootfh(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, void *arg) { __be32 status; fh_put(&cstate->current_fh); status = exp_pseudoroot(rqstp, &cstate->current_fh); return status; } static __be32 nfsd4_restorefh(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, void *arg) { if (!cstate->save_fh.fh_dentry) return nfserr_restorefh; fh_dup2(&cstate->current_fh, &cstate->save_fh); if (HAS_STATE_ID(cstate, SAVED_STATE_ID_FLAG)) { memcpy(&cstate->current_stateid, &cstate->save_stateid, sizeof(stateid_t)); SET_STATE_ID(cstate, CURRENT_STATE_ID_FLAG); } return nfs_ok; } static __be32 nfsd4_savefh(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, void *arg) { if (!cstate->current_fh.fh_dentry) return nfserr_nofilehandle; fh_dup2(&cstate->save_fh, &cstate->current_fh); if (HAS_STATE_ID(cstate, CURRENT_STATE_ID_FLAG)) { memcpy(&cstate->save_stateid, &cstate->current_stateid, sizeof(stateid_t)); SET_STATE_ID(cstate, SAVED_STATE_ID_FLAG); } return nfs_ok; } /* * misc nfsv4 ops */ static __be32 nfsd4_access(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_access *access) { if (access->ac_req_access & ~NFS3_ACCESS_FULL) return nfserr_inval; access->ac_resp_access = access->ac_req_access; return nfsd_access(rqstp, &cstate->current_fh, &access->ac_resp_access, &access->ac_supported); } static void gen_boot_verifier(nfs4_verifier *verifier, struct net *net) { __be32 verf[2]; struct nfsd_net *nn = net_generic(net, nfsd_net_id); /* * This is opaque to client, so no need to byte-swap. Use * __force to keep sparse happy */ verf[0] = (__force __be32)nn->nfssvc_boot.tv_sec; verf[1] = (__force __be32)nn->nfssvc_boot.tv_usec; memcpy(verifier->data, verf, sizeof(verifier->data)); } static __be32 nfsd4_commit(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_commit *commit) { gen_boot_verifier(&commit->co_verf, SVC_NET(rqstp)); return nfsd_commit(rqstp, &cstate->current_fh, commit->co_offset, commit->co_count); } static __be32 nfsd4_create(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_create *create) { struct svc_fh resfh; __be32 status; dev_t rdev; fh_init(&resfh, NFS4_FHSIZE); status = fh_verify(rqstp, &cstate->current_fh, S_IFDIR, NFSD_MAY_NOP); if (status) return status; status = check_attr_support(rqstp, cstate, create->cr_bmval, nfsd_attrmask); if (status) return status; switch (create->cr_type) { case NF4LNK: status = nfsd_symlink(rqstp, &cstate->current_fh, create->cr_name, create->cr_namelen, create->cr_data, &resfh); break; case NF4BLK: rdev = MKDEV(create->cr_specdata1, create->cr_specdata2); if (MAJOR(rdev) != create->cr_specdata1 || MINOR(rdev) != create->cr_specdata2) return nfserr_inval; status = nfsd_create(rqstp, &cstate->current_fh, create->cr_name, create->cr_namelen, &create->cr_iattr, S_IFBLK, rdev, &resfh); break; case NF4CHR: rdev = MKDEV(create->cr_specdata1, create->cr_specdata2); if (MAJOR(rdev) != create->cr_specdata1 || MINOR(rdev) != create->cr_specdata2) return nfserr_inval; status = nfsd_create(rqstp, &cstate->current_fh, create->cr_name, create->cr_namelen, &create->cr_iattr,S_IFCHR, rdev, &resfh); break; case NF4SOCK: status = nfsd_create(rqstp, &cstate->current_fh, create->cr_name, create->cr_namelen, &create->cr_iattr, S_IFSOCK, 0, &resfh); break; case NF4FIFO: status = nfsd_create(rqstp, &cstate->current_fh, create->cr_name, create->cr_namelen, &create->cr_iattr, S_IFIFO, 0, &resfh); break; case NF4DIR: create->cr_iattr.ia_valid &= ~ATTR_SIZE; status = nfsd_create(rqstp, &cstate->current_fh, create->cr_name, create->cr_namelen, &create->cr_iattr, S_IFDIR, 0, &resfh); break; default: status = nfserr_badtype; } if (status) goto out; if (create->cr_label.len) nfsd4_security_inode_setsecctx(&resfh, &create->cr_label, create->cr_bmval); if (create->cr_acl != NULL) do_set_nfs4_acl(rqstp, &resfh, create->cr_acl, create->cr_bmval); fh_unlock(&cstate->current_fh); set_change_info(&create->cr_cinfo, &cstate->current_fh); fh_dup2(&cstate->current_fh, &resfh); out: fh_put(&resfh); return status; } static __be32 nfsd4_getattr(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_getattr *getattr) { __be32 status; status = fh_verify(rqstp, &cstate->current_fh, 0, NFSD_MAY_NOP); if (status) return status; if (getattr->ga_bmval[1] & NFSD_WRITEONLY_ATTRS_WORD1) return nfserr_inval; getattr->ga_bmval[0] &= nfsd_suppattrs[cstate->minorversion][0]; getattr->ga_bmval[1] &= nfsd_suppattrs[cstate->minorversion][1]; getattr->ga_bmval[2] &= nfsd_suppattrs[cstate->minorversion][2]; getattr->ga_fhp = &cstate->current_fh; return nfs_ok; } static __be32 nfsd4_link(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_link *link) { __be32 status = nfserr_nofilehandle; if (!cstate->save_fh.fh_dentry) return status; status = nfsd_link(rqstp, &cstate->current_fh, link->li_name, link->li_namelen, &cstate->save_fh); if (!status) set_change_info(&link->li_cinfo, &cstate->current_fh); return status; } static __be32 nfsd4_do_lookupp(struct svc_rqst *rqstp, struct svc_fh *fh) { struct svc_fh tmp_fh; __be32 ret; fh_init(&tmp_fh, NFS4_FHSIZE); ret = exp_pseudoroot(rqstp, &tmp_fh); if (ret) return ret; if (tmp_fh.fh_dentry == fh->fh_dentry) { fh_put(&tmp_fh); return nfserr_noent; } fh_put(&tmp_fh); return nfsd_lookup(rqstp, fh, "..", 2, fh); } static __be32 nfsd4_lookupp(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, void *arg) { return nfsd4_do_lookupp(rqstp, &cstate->current_fh); } static __be32 nfsd4_lookup(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_lookup *lookup) { return nfsd_lookup(rqstp, &cstate->current_fh, lookup->lo_name, lookup->lo_len, &cstate->current_fh); } static __be32 nfsd4_read(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_read *read) { __be32 status; read->rd_filp = NULL; if (read->rd_offset >= OFFSET_MAX) return nfserr_inval; /* * If we do a zero copy read, then a client will see read data * that reflects the state of the file *after* performing the * following compound. * * To ensure proper ordering, we therefore turn off zero copy if * the client wants us to do more in this compound: */ if (!nfsd4_last_compound_op(rqstp)) clear_bit(RQ_SPLICE_OK, &rqstp->rq_flags); /* check stateid */ status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->current_fh, &read->rd_stateid, RD_STATE, &read->rd_filp, &read->rd_tmp_file); if (status) { dprintk("NFSD: nfsd4_read: couldn't process stateid!\n"); goto out; } status = nfs_ok; out: read->rd_rqstp = rqstp; read->rd_fhp = &cstate->current_fh; return status; } static __be32 nfsd4_readdir(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_readdir *readdir) { u64 cookie = readdir->rd_cookie; static const nfs4_verifier zeroverf; /* no need to check permission - this will be done in nfsd_readdir() */ if (readdir->rd_bmval[1] & NFSD_WRITEONLY_ATTRS_WORD1) return nfserr_inval; readdir->rd_bmval[0] &= nfsd_suppattrs[cstate->minorversion][0]; readdir->rd_bmval[1] &= nfsd_suppattrs[cstate->minorversion][1]; readdir->rd_bmval[2] &= nfsd_suppattrs[cstate->minorversion][2]; if ((cookie == 1) || (cookie == 2) || (cookie == 0 && memcmp(readdir->rd_verf.data, zeroverf.data, NFS4_VERIFIER_SIZE))) return nfserr_bad_cookie; readdir->rd_rqstp = rqstp; readdir->rd_fhp = &cstate->current_fh; return nfs_ok; } static __be32 nfsd4_readlink(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_readlink *readlink) { readlink->rl_rqstp = rqstp; readlink->rl_fhp = &cstate->current_fh; return nfs_ok; } static __be32 nfsd4_remove(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_remove *remove) { __be32 status; if (opens_in_grace(SVC_NET(rqstp))) return nfserr_grace; status = nfsd_unlink(rqstp, &cstate->current_fh, 0, remove->rm_name, remove->rm_namelen); if (!status) { fh_unlock(&cstate->current_fh); set_change_info(&remove->rm_cinfo, &cstate->current_fh); } return status; } static __be32 nfsd4_rename(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_rename *rename) { __be32 status = nfserr_nofilehandle; if (!cstate->save_fh.fh_dentry) return status; if (opens_in_grace(SVC_NET(rqstp)) && !(cstate->save_fh.fh_export->ex_flags & NFSEXP_NOSUBTREECHECK)) return nfserr_grace; status = nfsd_rename(rqstp, &cstate->save_fh, rename->rn_sname, rename->rn_snamelen, &cstate->current_fh, rename->rn_tname, rename->rn_tnamelen); if (status) return status; set_change_info(&rename->rn_sinfo, &cstate->current_fh); set_change_info(&rename->rn_tinfo, &cstate->save_fh); return nfs_ok; } static __be32 nfsd4_secinfo(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_secinfo *secinfo) { struct svc_export *exp; struct dentry *dentry; __be32 err; err = fh_verify(rqstp, &cstate->current_fh, S_IFDIR, NFSD_MAY_EXEC); if (err) return err; err = nfsd_lookup_dentry(rqstp, &cstate->current_fh, secinfo->si_name, secinfo->si_namelen, &exp, &dentry); if (err) return err; fh_unlock(&cstate->current_fh); if (d_really_is_negative(dentry)) { exp_put(exp); err = nfserr_noent; } else secinfo->si_exp = exp; dput(dentry); if (cstate->minorversion) /* See rfc 5661 section 2.6.3.1.1.8 */ fh_put(&cstate->current_fh); return err; } static __be32 nfsd4_secinfo_no_name(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_secinfo_no_name *sin) { __be32 err; switch (sin->sin_style) { case NFS4_SECINFO_STYLE4_CURRENT_FH: break; case NFS4_SECINFO_STYLE4_PARENT: err = nfsd4_do_lookupp(rqstp, &cstate->current_fh); if (err) return err; break; default: return nfserr_inval; } sin->sin_exp = exp_get(cstate->current_fh.fh_export); fh_put(&cstate->current_fh); return nfs_ok; } static __be32 nfsd4_setattr(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_setattr *setattr) { __be32 status = nfs_ok; int err; if (setattr->sa_iattr.ia_valid & ATTR_SIZE) { status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->current_fh, &setattr->sa_stateid, WR_STATE, NULL, NULL); if (status) { dprintk("NFSD: nfsd4_setattr: couldn't process stateid!\n"); return status; } } err = fh_want_write(&cstate->current_fh); if (err) return nfserrno(err); status = nfs_ok; status = check_attr_support(rqstp, cstate, setattr->sa_bmval, nfsd_attrmask); if (status) goto out; if (setattr->sa_acl != NULL) status = nfsd4_set_nfs4_acl(rqstp, &cstate->current_fh, setattr->sa_acl); if (status) goto out; if (setattr->sa_label.len) status = nfsd4_set_nfs4_label(rqstp, &cstate->current_fh, &setattr->sa_label); if (status) goto out; status = nfsd_setattr(rqstp, &cstate->current_fh, &setattr->sa_iattr, 0, (time_t)0); out: fh_drop_write(&cstate->current_fh); return status; } static int fill_in_write_vector(struct kvec *vec, struct nfsd4_write *write) { int i = 1; int buflen = write->wr_buflen; vec[0].iov_base = write->wr_head.iov_base; vec[0].iov_len = min_t(int, buflen, write->wr_head.iov_len); buflen -= vec[0].iov_len; while (buflen) { vec[i].iov_base = page_address(write->wr_pagelist[i - 1]); vec[i].iov_len = min_t(int, PAGE_SIZE, buflen); buflen -= vec[i].iov_len; i++; } return i; } static __be32 nfsd4_write(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_write *write) { stateid_t *stateid = &write->wr_stateid; struct file *filp = NULL; __be32 status = nfs_ok; unsigned long cnt; int nvecs; if (write->wr_offset >= OFFSET_MAX) return nfserr_inval; status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->current_fh, stateid, WR_STATE, &filp, NULL); if (status) { dprintk("NFSD: nfsd4_write: couldn't process stateid!\n"); return status; } cnt = write->wr_buflen; write->wr_how_written = write->wr_stable_how; gen_boot_verifier(&write->wr_verifier, SVC_NET(rqstp)); nvecs = fill_in_write_vector(rqstp->rq_vec, write); WARN_ON_ONCE(nvecs > ARRAY_SIZE(rqstp->rq_vec)); status = nfsd_vfs_write(rqstp, &cstate->current_fh, filp, write->wr_offset, rqstp->rq_vec, nvecs, &cnt, write->wr_how_written); fput(filp); write->wr_bytes_written = cnt; return status; } static __be32 nfsd4_verify_copy(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, stateid_t *src_stateid, struct file **src, stateid_t *dst_stateid, struct file **dst) { __be32 status; status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->save_fh, src_stateid, RD_STATE, src, NULL); if (status) { dprintk("NFSD: %s: couldn't process src stateid!\n", __func__); goto out; } status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->current_fh, dst_stateid, WR_STATE, dst, NULL); if (status) { dprintk("NFSD: %s: couldn't process dst stateid!\n", __func__); goto out_put_src; } /* fix up for NFS-specific error code */ if (!S_ISREG(file_inode(*src)->i_mode) || !S_ISREG(file_inode(*dst)->i_mode)) { status = nfserr_wrong_type; goto out_put_dst; } out: return status; out_put_dst: fput(*dst); out_put_src: fput(*src); goto out; } static __be32 nfsd4_clone(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_clone *clone) { struct file *src, *dst; __be32 status; status = nfsd4_verify_copy(rqstp, cstate, &clone->cl_src_stateid, &src, &clone->cl_dst_stateid, &dst); if (status) goto out; status = nfsd4_clone_file_range(src, clone->cl_src_pos, dst, clone->cl_dst_pos, clone->cl_count); fput(dst); fput(src); out: return status; } static __be32 nfsd4_copy(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_copy *copy) { struct file *src, *dst; __be32 status; ssize_t bytes; status = nfsd4_verify_copy(rqstp, cstate, &copy->cp_src_stateid, &src, &copy->cp_dst_stateid, &dst); if (status) goto out; bytes = nfsd_copy_file_range(src, copy->cp_src_pos, dst, copy->cp_dst_pos, copy->cp_count); if (bytes < 0) status = nfserrno(bytes); else { copy->cp_res.wr_bytes_written = bytes; copy->cp_res.wr_stable_how = NFS_UNSTABLE; copy->cp_consecutive = 1; copy->cp_synchronous = 1; gen_boot_verifier(&copy->cp_res.wr_verifier, SVC_NET(rqstp)); status = nfs_ok; } fput(src); fput(dst); out: return status; } static __be32 nfsd4_fallocate(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_fallocate *fallocate, int flags) { __be32 status = nfserr_notsupp; struct file *file; status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->current_fh, &fallocate->falloc_stateid, WR_STATE, &file, NULL); if (status != nfs_ok) { dprintk("NFSD: nfsd4_fallocate: couldn't process stateid!\n"); return status; } status = nfsd4_vfs_fallocate(rqstp, &cstate->current_fh, file, fallocate->falloc_offset, fallocate->falloc_length, flags); fput(file); return status; } static __be32 nfsd4_allocate(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_fallocate *fallocate) { return nfsd4_fallocate(rqstp, cstate, fallocate, 0); } static __be32 nfsd4_deallocate(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_fallocate *fallocate) { return nfsd4_fallocate(rqstp, cstate, fallocate, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE); } static __be32 nfsd4_seek(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_seek *seek) { int whence; __be32 status; struct file *file; status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->current_fh, &seek->seek_stateid, RD_STATE, &file, NULL); if (status) { dprintk("NFSD: nfsd4_seek: couldn't process stateid!\n"); return status; } switch (seek->seek_whence) { case NFS4_CONTENT_DATA: whence = SEEK_DATA; break; case NFS4_CONTENT_HOLE: whence = SEEK_HOLE; break; default: status = nfserr_union_notsupp; goto out; } /* * Note: This call does change file->f_pos, but nothing in NFSD * should ever file->f_pos. */ seek->seek_pos = vfs_llseek(file, seek->seek_offset, whence); if (seek->seek_pos < 0) status = nfserrno(seek->seek_pos); else if (seek->seek_pos >= i_size_read(file_inode(file))) seek->seek_eof = true; out: fput(file); return status; } /* This routine never returns NFS_OK! If there are no other errors, it * will return NFSERR_SAME or NFSERR_NOT_SAME depending on whether the * attributes matched. VERIFY is implemented by mapping NFSERR_SAME * to NFS_OK after the call; NVERIFY by mapping NFSERR_NOT_SAME to NFS_OK. */ static __be32 _nfsd4_verify(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_verify *verify) { __be32 *buf, *p; int count; __be32 status; status = fh_verify(rqstp, &cstate->current_fh, 0, NFSD_MAY_NOP); if (status) return status; status = check_attr_support(rqstp, cstate, verify->ve_bmval, NULL); if (status) return status; if ((verify->ve_bmval[0] & FATTR4_WORD0_RDATTR_ERROR) || (verify->ve_bmval[1] & NFSD_WRITEONLY_ATTRS_WORD1)) return nfserr_inval; if (verify->ve_attrlen & 3) return nfserr_inval; /* count in words: * bitmap_len(1) + bitmap(2) + attr_len(1) = 4 */ count = 4 + (verify->ve_attrlen >> 2); buf = kmalloc(count << 2, GFP_KERNEL); if (!buf) return nfserr_jukebox; p = buf; status = nfsd4_encode_fattr_to_buf(&p, count, &cstate->current_fh, cstate->current_fh.fh_export, cstate->current_fh.fh_dentry, verify->ve_bmval, rqstp, 0); /* * If nfsd4_encode_fattr() ran out of space, assume that's because * the attributes are longer (hence different) than those given: */ if (status == nfserr_resource) status = nfserr_not_same; if (status) goto out_kfree; /* skip bitmap */ p = buf + 1 + ntohl(buf[0]); status = nfserr_not_same; if (ntohl(*p++) != verify->ve_attrlen) goto out_kfree; if (!memcmp(p, verify->ve_attrval, verify->ve_attrlen)) status = nfserr_same; out_kfree: kfree(buf); return status; } static __be32 nfsd4_nverify(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_verify *verify) { __be32 status; status = _nfsd4_verify(rqstp, cstate, verify); return status == nfserr_not_same ? nfs_ok : status; } static __be32 nfsd4_verify(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_verify *verify) { __be32 status; status = _nfsd4_verify(rqstp, cstate, verify); return status == nfserr_same ? nfs_ok : status; } #ifdef CONFIG_NFSD_PNFS static const struct nfsd4_layout_ops * nfsd4_layout_verify(struct svc_export *exp, unsigned int layout_type) { if (!exp->ex_layout_types) { dprintk("%s: export does not support pNFS\n", __func__); return NULL; } if (layout_type >= LAYOUT_TYPE_MAX || !(exp->ex_layout_types & (1 << layout_type))) { dprintk("%s: layout type %d not supported\n", __func__, layout_type); return NULL; } return nfsd4_layout_ops[layout_type]; } static __be32 nfsd4_getdeviceinfo(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_getdeviceinfo *gdp) { const struct nfsd4_layout_ops *ops; struct nfsd4_deviceid_map *map; struct svc_export *exp; __be32 nfserr; dprintk("%s: layout_type %u dev_id [0x%llx:0x%x] maxcnt %u\n", __func__, gdp->gd_layout_type, gdp->gd_devid.fsid_idx, gdp->gd_devid.generation, gdp->gd_maxcount); map = nfsd4_find_devid_map(gdp->gd_devid.fsid_idx); if (!map) { dprintk("%s: couldn't find device ID to export mapping!\n", __func__); return nfserr_noent; } exp = rqst_exp_find(rqstp, map->fsid_type, map->fsid); if (IS_ERR(exp)) { dprintk("%s: could not find device id\n", __func__); return nfserr_noent; } nfserr = nfserr_layoutunavailable; ops = nfsd4_layout_verify(exp, gdp->gd_layout_type); if (!ops) goto out; nfserr = nfs_ok; if (gdp->gd_maxcount != 0) { nfserr = ops->proc_getdeviceinfo(exp->ex_path.mnt->mnt_sb, rqstp, cstate->session->se_client, gdp); } gdp->gd_notify_types &= ops->notify_types; out: exp_put(exp); return nfserr; } static __be32 nfsd4_layoutget(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_layoutget *lgp) { struct svc_fh *current_fh = &cstate->current_fh; const struct nfsd4_layout_ops *ops; struct nfs4_layout_stateid *ls; __be32 nfserr; int accmode; switch (lgp->lg_seg.iomode) { case IOMODE_READ: accmode = NFSD_MAY_READ; break; case IOMODE_RW: accmode = NFSD_MAY_READ | NFSD_MAY_WRITE; break; default: dprintk("%s: invalid iomode %d\n", __func__, lgp->lg_seg.iomode); nfserr = nfserr_badiomode; goto out; } nfserr = fh_verify(rqstp, current_fh, 0, accmode); if (nfserr) goto out; nfserr = nfserr_layoutunavailable; ops = nfsd4_layout_verify(current_fh->fh_export, lgp->lg_layout_type); if (!ops) goto out; /* * Verify minlength and range as per RFC5661: * o If loga_length is less than loga_minlength, * the metadata server MUST return NFS4ERR_INVAL. * o If the sum of loga_offset and loga_minlength exceeds * NFS4_UINT64_MAX, and loga_minlength is not * NFS4_UINT64_MAX, the error NFS4ERR_INVAL MUST result. * o If the sum of loga_offset and loga_length exceeds * NFS4_UINT64_MAX, and loga_length is not NFS4_UINT64_MAX, * the error NFS4ERR_INVAL MUST result. */ nfserr = nfserr_inval; if (lgp->lg_seg.length < lgp->lg_minlength || (lgp->lg_minlength != NFS4_MAX_UINT64 && lgp->lg_minlength > NFS4_MAX_UINT64 - lgp->lg_seg.offset) || (lgp->lg_seg.length != NFS4_MAX_UINT64 && lgp->lg_seg.length > NFS4_MAX_UINT64 - lgp->lg_seg.offset)) goto out; if (lgp->lg_seg.length == 0) goto out; nfserr = nfsd4_preprocess_layout_stateid(rqstp, cstate, &lgp->lg_sid, true, lgp->lg_layout_type, &ls); if (nfserr) { trace_layout_get_lookup_fail(&lgp->lg_sid); goto out; } nfserr = nfserr_recallconflict; if (atomic_read(&ls->ls_stid.sc_file->fi_lo_recalls)) goto out_put_stid; nfserr = ops->proc_layoutget(d_inode(current_fh->fh_dentry), current_fh, lgp); if (nfserr) goto out_put_stid; nfserr = nfsd4_insert_layout(lgp, ls); out_put_stid: mutex_unlock(&ls->ls_mutex); nfs4_put_stid(&ls->ls_stid); out: return nfserr; } static __be32 nfsd4_layoutcommit(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_layoutcommit *lcp) { const struct nfsd4_layout_seg *seg = &lcp->lc_seg; struct svc_fh *current_fh = &cstate->current_fh; const struct nfsd4_layout_ops *ops; loff_t new_size = lcp->lc_last_wr + 1; struct inode *inode; struct nfs4_layout_stateid *ls; __be32 nfserr; nfserr = fh_verify(rqstp, current_fh, 0, NFSD_MAY_WRITE); if (nfserr) goto out; nfserr = nfserr_layoutunavailable; ops = nfsd4_layout_verify(current_fh->fh_export, lcp->lc_layout_type); if (!ops) goto out; inode = d_inode(current_fh->fh_dentry); nfserr = nfserr_inval; if (new_size <= seg->offset) { dprintk("pnfsd: last write before layout segment\n"); goto out; } if (new_size > seg->offset + seg->length) { dprintk("pnfsd: last write beyond layout segment\n"); goto out; } if (!lcp->lc_newoffset && new_size > i_size_read(inode)) { dprintk("pnfsd: layoutcommit beyond EOF\n"); goto out; } nfserr = nfsd4_preprocess_layout_stateid(rqstp, cstate, &lcp->lc_sid, false, lcp->lc_layout_type, &ls); if (nfserr) { trace_layout_commit_lookup_fail(&lcp->lc_sid); /* fixup error code as per RFC5661 */ if (nfserr == nfserr_bad_stateid) nfserr = nfserr_badlayout; goto out; } /* LAYOUTCOMMIT does not require any serialization */ mutex_unlock(&ls->ls_mutex); if (new_size > i_size_read(inode)) { lcp->lc_size_chg = 1; lcp->lc_newsize = new_size; } else { lcp->lc_size_chg = 0; } nfserr = ops->proc_layoutcommit(inode, lcp); nfs4_put_stid(&ls->ls_stid); out: return nfserr; } static __be32 nfsd4_layoutreturn(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_layoutreturn *lrp) { struct svc_fh *current_fh = &cstate->current_fh; __be32 nfserr; nfserr = fh_verify(rqstp, current_fh, 0, NFSD_MAY_NOP); if (nfserr) goto out; nfserr = nfserr_layoutunavailable; if (!nfsd4_layout_verify(current_fh->fh_export, lrp->lr_layout_type)) goto out; switch (lrp->lr_seg.iomode) { case IOMODE_READ: case IOMODE_RW: case IOMODE_ANY: break; default: dprintk("%s: invalid iomode %d\n", __func__, lrp->lr_seg.iomode); nfserr = nfserr_inval; goto out; } switch (lrp->lr_return_type) { case RETURN_FILE: nfserr = nfsd4_return_file_layouts(rqstp, cstate, lrp); break; case RETURN_FSID: case RETURN_ALL: nfserr = nfsd4_return_client_layouts(rqstp, cstate, lrp); break; default: dprintk("%s: invalid return_type %d\n", __func__, lrp->lr_return_type); nfserr = nfserr_inval; break; } out: return nfserr; } #endif /* CONFIG_NFSD_PNFS */ /* * NULL call. */ static __be32 nfsd4_proc_null(struct svc_rqst *rqstp, void *argp, void *resp) { return nfs_ok; } static inline void nfsd4_increment_op_stats(u32 opnum) { if (opnum >= FIRST_NFS4_OP && opnum <= LAST_NFS4_OP) nfsdstats.nfs4_opcount[opnum]++; } typedef __be32(*nfsd4op_func)(struct svc_rqst *, struct nfsd4_compound_state *, void *); typedef u32(*nfsd4op_rsize)(struct svc_rqst *, struct nfsd4_op *op); typedef void(*stateid_setter)(struct nfsd4_compound_state *, void *); typedef void(*stateid_getter)(struct nfsd4_compound_state *, void *); enum nfsd4_op_flags { ALLOWED_WITHOUT_FH = 1 << 0, /* No current filehandle required */ ALLOWED_ON_ABSENT_FS = 1 << 1, /* ops processed on absent fs */ ALLOWED_AS_FIRST_OP = 1 << 2, /* ops reqired first in compound */ /* For rfc 5661 section 2.6.3.1.1: */ OP_HANDLES_WRONGSEC = 1 << 3, OP_IS_PUTFH_LIKE = 1 << 4, /* * These are the ops whose result size we estimate before * encoding, to avoid performing an op then not being able to * respond or cache a response. This includes writes and setattrs * as well as the operations usually called "nonidempotent": */ OP_MODIFIES_SOMETHING = 1 << 5, /* * Cache compounds containing these ops in the xid-based drc: * We use the DRC for compounds containing non-idempotent * operations, *except* those that are 4.1-specific (since * sessions provide their own EOS), and except for stateful * operations other than setclientid and setclientid_confirm * (since sequence numbers provide EOS for open, lock, etc in * the v4.0 case). */ OP_CACHEME = 1 << 6, /* * These are ops which clear current state id. */ OP_CLEAR_STATEID = 1 << 7, }; struct nfsd4_operation { nfsd4op_func op_func; u32 op_flags; char *op_name; /* Try to get response size before operation */ nfsd4op_rsize op_rsize_bop; stateid_getter op_get_currentstateid; stateid_setter op_set_currentstateid; }; static struct nfsd4_operation nfsd4_ops[]; static const char *nfsd4_op_name(unsigned opnum); /* * Enforce NFSv4.1 COMPOUND ordering rules: * * Also note, enforced elsewhere: * - SEQUENCE other than as first op results in * NFS4ERR_SEQUENCE_POS. (Enforced in nfsd4_sequence().) * - BIND_CONN_TO_SESSION must be the only op in its compound. * (Enforced in nfsd4_bind_conn_to_session().) * - DESTROY_SESSION must be the final operation in a compound, if * sessionid's in SEQUENCE and DESTROY_SESSION are the same. * (Enforced in nfsd4_destroy_session().) */ static __be32 nfs41_check_op_ordering(struct nfsd4_compoundargs *args) { struct nfsd4_op *op = &args->ops[0]; /* These ordering requirements don't apply to NFSv4.0: */ if (args->minorversion == 0) return nfs_ok; /* This is weird, but OK, not our problem: */ if (args->opcnt == 0) return nfs_ok; if (op->status == nfserr_op_illegal) return nfs_ok; if (!(nfsd4_ops[op->opnum].op_flags & ALLOWED_AS_FIRST_OP)) return nfserr_op_not_in_session; if (op->opnum == OP_SEQUENCE) return nfs_ok; if (args->opcnt != 1) return nfserr_not_only_op; return nfs_ok; } static inline struct nfsd4_operation *OPDESC(struct nfsd4_op *op) { return &nfsd4_ops[op->opnum]; } bool nfsd4_cache_this_op(struct nfsd4_op *op) { if (op->opnum == OP_ILLEGAL) return false; return OPDESC(op)->op_flags & OP_CACHEME; } static bool need_wrongsec_check(struct svc_rqst *rqstp) { struct nfsd4_compoundres *resp = rqstp->rq_resp; struct nfsd4_compoundargs *argp = rqstp->rq_argp; struct nfsd4_op *this = &argp->ops[resp->opcnt - 1]; struct nfsd4_op *next = &argp->ops[resp->opcnt]; struct nfsd4_operation *thisd; struct nfsd4_operation *nextd; thisd = OPDESC(this); /* * Most ops check wronsec on our own; only the putfh-like ops * have special rules. */ if (!(thisd->op_flags & OP_IS_PUTFH_LIKE)) return false; /* * rfc 5661 2.6.3.1.1.6: don't bother erroring out a * put-filehandle operation if we're not going to use the * result: */ if (argp->opcnt == resp->opcnt) return false; if (next->opnum == OP_ILLEGAL) return false; nextd = OPDESC(next); /* * Rest of 2.6.3.1.1: certain operations will return WRONGSEC * errors themselves as necessary; others should check for them * now: */ return !(nextd->op_flags & OP_HANDLES_WRONGSEC); } static void svcxdr_init_encode(struct svc_rqst *rqstp, struct nfsd4_compoundres *resp) { struct xdr_stream *xdr = &resp->xdr; struct xdr_buf *buf = &rqstp->rq_res; struct kvec *head = buf->head; xdr->buf = buf; xdr->iov = head; xdr->p = head->iov_base + head->iov_len; xdr->end = head->iov_base + PAGE_SIZE - rqstp->rq_auth_slack; /* Tail and page_len should be zero at this point: */ buf->len = buf->head[0].iov_len; xdr->scratch.iov_len = 0; xdr->page_ptr = buf->pages - 1; buf->buflen = PAGE_SIZE * (1 + rqstp->rq_page_end - buf->pages) - rqstp->rq_auth_slack; } /* * COMPOUND call. */ static __be32 nfsd4_proc_compound(struct svc_rqst *rqstp, struct nfsd4_compoundargs *args, struct nfsd4_compoundres *resp) { struct nfsd4_op *op; struct nfsd4_operation *opdesc; struct nfsd4_compound_state *cstate = &resp->cstate; struct svc_fh *current_fh = &cstate->current_fh; struct svc_fh *save_fh = &cstate->save_fh; __be32 status; svcxdr_init_encode(rqstp, resp); resp->tagp = resp->xdr.p; /* reserve space for: taglen, tag, and opcnt */ xdr_reserve_space(&resp->xdr, 8 + args->taglen); resp->taglen = args->taglen; resp->tag = args->tag; resp->rqstp = rqstp; cstate->minorversion = args->minorversion; fh_init(current_fh, NFS4_FHSIZE); fh_init(save_fh, NFS4_FHSIZE); /* * Don't use the deferral mechanism for NFSv4; compounds make it * too hard to avoid non-idempotency problems. */ clear_bit(RQ_USEDEFERRAL, &rqstp->rq_flags); /* * According to RFC3010, this takes precedence over all other errors. */ status = nfserr_minor_vers_mismatch; if (nfsd_minorversion(args->minorversion, NFSD_TEST) <= 0) goto out; status = nfs41_check_op_ordering(args); if (status) { op = &args->ops[0]; op->status = status; goto encode_op; } while (!status && resp->opcnt < args->opcnt) { op = &args->ops[resp->opcnt++]; dprintk("nfsv4 compound op #%d/%d: %d (%s)\n", resp->opcnt, args->opcnt, op->opnum, nfsd4_op_name(op->opnum)); /* * The XDR decode routines may have pre-set op->status; * for example, if there is a miscellaneous XDR error * it will be set to nfserr_bad_xdr. */ if (op->status) { if (op->opnum == OP_OPEN) op->status = nfsd4_open_omfg(rqstp, cstate, op); goto encode_op; } opdesc = OPDESC(op); if (!current_fh->fh_dentry) { if (!(opdesc->op_flags & ALLOWED_WITHOUT_FH)) { op->status = nfserr_nofilehandle; goto encode_op; } } else if (current_fh->fh_export->ex_fslocs.migrated && !(opdesc->op_flags & ALLOWED_ON_ABSENT_FS)) { op->status = nfserr_moved; goto encode_op; } fh_clear_wcc(current_fh); /* If op is non-idempotent */ if (opdesc->op_flags & OP_MODIFIES_SOMETHING) { /* * Don't execute this op if we couldn't encode a * succesful reply: */ u32 plen = opdesc->op_rsize_bop(rqstp, op); /* * Plus if there's another operation, make sure * we'll have space to at least encode an error: */ if (resp->opcnt < args->opcnt) plen += COMPOUND_ERR_SLACK_SPACE; op->status = nfsd4_check_resp_size(resp, plen); } if (op->status) goto encode_op; if (opdesc->op_get_currentstateid) opdesc->op_get_currentstateid(cstate, &op->u); op->status = opdesc->op_func(rqstp, cstate, &op->u); if (!op->status) { if (opdesc->op_set_currentstateid) opdesc->op_set_currentstateid(cstate, &op->u); if (opdesc->op_flags & OP_CLEAR_STATEID) clear_current_stateid(cstate); if (need_wrongsec_check(rqstp)) op->status = check_nfsd_access(current_fh->fh_export, rqstp); } encode_op: /* Only from SEQUENCE */ if (cstate->status == nfserr_replay_cache) { dprintk("%s NFS4.1 replay from cache\n", __func__); status = op->status; goto out; } if (op->status == nfserr_replay_me) { op->replay = &cstate->replay_owner->so_replay; nfsd4_encode_replay(&resp->xdr, op); status = op->status = op->replay->rp_status; } else { nfsd4_encode_operation(resp, op); status = op->status; } dprintk("nfsv4 compound op %p opcnt %d #%d: %d: status %d\n", args->ops, args->opcnt, resp->opcnt, op->opnum, be32_to_cpu(status)); nfsd4_cstate_clear_replay(cstate); nfsd4_increment_op_stats(op->opnum); } cstate->status = status; fh_put(current_fh); fh_put(save_fh); BUG_ON(cstate->replay_owner); out: /* Reset deferral mechanism for RPC deferrals */ set_bit(RQ_USEDEFERRAL, &rqstp->rq_flags); dprintk("nfsv4 compound returned %d\n", ntohl(status)); return status; } #define op_encode_hdr_size (2) #define op_encode_stateid_maxsz (XDR_QUADLEN(NFS4_STATEID_SIZE)) #define op_encode_verifier_maxsz (XDR_QUADLEN(NFS4_VERIFIER_SIZE)) #define op_encode_change_info_maxsz (5) #define nfs4_fattr_bitmap_maxsz (4) /* We'll fall back on returning no lockowner if run out of space: */ #define op_encode_lockowner_maxsz (0) #define op_encode_lock_denied_maxsz (8 + op_encode_lockowner_maxsz) #define nfs4_owner_maxsz (1 + XDR_QUADLEN(IDMAP_NAMESZ)) #define op_encode_ace_maxsz (3 + nfs4_owner_maxsz) #define op_encode_delegation_maxsz (1 + op_encode_stateid_maxsz + 1 + \ op_encode_ace_maxsz) #define op_encode_channel_attrs_maxsz (6 + 1 + 1) static inline u32 nfsd4_only_status_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size) * sizeof(__be32); } static inline u32 nfsd4_status_stateid_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_stateid_maxsz)* sizeof(__be32); } static inline u32 nfsd4_access_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { /* ac_supported, ac_resp_access */ return (op_encode_hdr_size + 2)* sizeof(__be32); } static inline u32 nfsd4_commit_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_verifier_maxsz) * sizeof(__be32); } static inline u32 nfsd4_create_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_change_info_maxsz + nfs4_fattr_bitmap_maxsz) * sizeof(__be32); } /* * Note since this is an idempotent operation we won't insist on failing * the op prematurely if the estimate is too large. We may turn off splice * reads unnecessarily. */ static inline u32 nfsd4_getattr_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { u32 *bmap = op->u.getattr.ga_bmval; u32 bmap0 = bmap[0], bmap1 = bmap[1], bmap2 = bmap[2]; u32 ret = 0; if (bmap0 & FATTR4_WORD0_ACL) return svc_max_payload(rqstp); if (bmap0 & FATTR4_WORD0_FS_LOCATIONS) return svc_max_payload(rqstp); if (bmap1 & FATTR4_WORD1_OWNER) { ret += IDMAP_NAMESZ + 4; bmap1 &= ~FATTR4_WORD1_OWNER; } if (bmap1 & FATTR4_WORD1_OWNER_GROUP) { ret += IDMAP_NAMESZ + 4; bmap1 &= ~FATTR4_WORD1_OWNER_GROUP; } if (bmap0 & FATTR4_WORD0_FILEHANDLE) { ret += NFS4_FHSIZE + 4; bmap0 &= ~FATTR4_WORD0_FILEHANDLE; } if (bmap2 & FATTR4_WORD2_SECURITY_LABEL) { ret += NFS4_MAXLABELLEN + 12; bmap2 &= ~FATTR4_WORD2_SECURITY_LABEL; } /* * Largest of remaining attributes are 16 bytes (e.g., * supported_attributes) */ ret += 16 * (hweight32(bmap0) + hweight32(bmap1) + hweight32(bmap2)); /* bitmask, length */ ret += 20; return ret; } static inline u32 nfsd4_getfh_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1) * sizeof(__be32) + NFS4_FHSIZE; } static inline u32 nfsd4_link_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_change_info_maxsz) * sizeof(__be32); } static inline u32 nfsd4_lock_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_lock_denied_maxsz) * sizeof(__be32); } static inline u32 nfsd4_open_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_stateid_maxsz + op_encode_change_info_maxsz + 1 + nfs4_fattr_bitmap_maxsz + op_encode_delegation_maxsz) * sizeof(__be32); } static inline u32 nfsd4_read_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { u32 maxcount = 0, rlen = 0; maxcount = svc_max_payload(rqstp); rlen = min(op->u.read.rd_length, maxcount); return (op_encode_hdr_size + 2 + XDR_QUADLEN(rlen)) * sizeof(__be32); } static inline u32 nfsd4_readdir_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { u32 maxcount = 0, rlen = 0; maxcount = svc_max_payload(rqstp); rlen = min(op->u.readdir.rd_maxcount, maxcount); return (op_encode_hdr_size + op_encode_verifier_maxsz + XDR_QUADLEN(rlen)) * sizeof(__be32); } static inline u32 nfsd4_readlink_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1) * sizeof(__be32) + PAGE_SIZE; } static inline u32 nfsd4_remove_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_change_info_maxsz) * sizeof(__be32); } static inline u32 nfsd4_rename_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_change_info_maxsz + op_encode_change_info_maxsz) * sizeof(__be32); } static inline u32 nfsd4_sequence_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + 5) * sizeof(__be32); } static inline u32 nfsd4_test_stateid_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1 + op->u.test_stateid.ts_num_ids) * sizeof(__be32); } static inline u32 nfsd4_setattr_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + nfs4_fattr_bitmap_maxsz) * sizeof(__be32); } static inline u32 nfsd4_secinfo_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + RPC_AUTH_MAXFLAVOR * (4 + XDR_QUADLEN(GSS_OID_MAX_LEN))) * sizeof(__be32); } static inline u32 nfsd4_setclientid_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 2 + XDR_QUADLEN(NFS4_VERIFIER_SIZE)) * sizeof(__be32); } static inline u32 nfsd4_write_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 2 + op_encode_verifier_maxsz) * sizeof(__be32); } static inline u32 nfsd4_exchange_id_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 2 + 1 + /* eir_clientid, eir_sequenceid */\ 1 + 1 + /* eir_flags, spr_how */\ 4 + /* spo_must_enforce & _allow with bitmap */\ 2 + /*eir_server_owner.so_minor_id */\ /* eir_server_owner.so_major_id<> */\ XDR_QUADLEN(NFS4_OPAQUE_LIMIT) + 1 +\ /* eir_server_scope<> */\ XDR_QUADLEN(NFS4_OPAQUE_LIMIT) + 1 +\ 1 + /* eir_server_impl_id array length */\ 0 /* ignored eir_server_impl_id contents */) * sizeof(__be32); } static inline u32 nfsd4_bind_conn_to_session_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + \ XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + /* bctsr_sessid */\ 2 /* bctsr_dir, use_conn_in_rdma_mode */) * sizeof(__be32); } static inline u32 nfsd4_create_session_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + \ XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + /* sessionid */\ 2 + /* csr_sequence, csr_flags */\ op_encode_channel_attrs_maxsz + \ op_encode_channel_attrs_maxsz) * sizeof(__be32); } static inline u32 nfsd4_copy_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1 /* wr_callback */ + op_encode_stateid_maxsz /* wr_callback */ + 2 /* wr_count */ + 1 /* wr_committed */ + op_encode_verifier_maxsz + 1 /* cr_consecutive */ + 1 /* cr_synchronous */) * sizeof(__be32); } #ifdef CONFIG_NFSD_PNFS static inline u32 nfsd4_getdeviceinfo_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { u32 maxcount = 0, rlen = 0; maxcount = svc_max_payload(rqstp); rlen = min(op->u.getdeviceinfo.gd_maxcount, maxcount); return (op_encode_hdr_size + 1 /* gd_layout_type*/ + XDR_QUADLEN(rlen) + 2 /* gd_notify_types */) * sizeof(__be32); } /* * At this stage we don't really know what layout driver will handle the request, * so we need to define an arbitrary upper bound here. */ #define MAX_LAYOUT_SIZE 128 static inline u32 nfsd4_layoutget_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1 /* logr_return_on_close */ + op_encode_stateid_maxsz + 1 /* nr of layouts */ + MAX_LAYOUT_SIZE) * sizeof(__be32); } static inline u32 nfsd4_layoutcommit_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1 /* locr_newsize */ + 2 /* ns_size */) * sizeof(__be32); } static inline u32 nfsd4_layoutreturn_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1 /* lrs_stateid */ + op_encode_stateid_maxsz) * sizeof(__be32); } #endif /* CONFIG_NFSD_PNFS */ static inline u32 nfsd4_seek_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 3) * sizeof(__be32); } static struct nfsd4_operation nfsd4_ops[] = { [OP_ACCESS] = { .op_func = (nfsd4op_func)nfsd4_access, .op_name = "OP_ACCESS", .op_rsize_bop = (nfsd4op_rsize)nfsd4_access_rsize, }, [OP_CLOSE] = { .op_func = (nfsd4op_func)nfsd4_close, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_CLOSE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_status_stateid_rsize, .op_get_currentstateid = (stateid_getter)nfsd4_get_closestateid, .op_set_currentstateid = (stateid_setter)nfsd4_set_closestateid, }, [OP_COMMIT] = { .op_func = (nfsd4op_func)nfsd4_commit, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_COMMIT", .op_rsize_bop = (nfsd4op_rsize)nfsd4_commit_rsize, }, [OP_CREATE] = { .op_func = (nfsd4op_func)nfsd4_create, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME | OP_CLEAR_STATEID, .op_name = "OP_CREATE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_create_rsize, }, [OP_DELEGRETURN] = { .op_func = (nfsd4op_func)nfsd4_delegreturn, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_DELEGRETURN", .op_rsize_bop = nfsd4_only_status_rsize, .op_get_currentstateid = (stateid_getter)nfsd4_get_delegreturnstateid, }, [OP_GETATTR] = { .op_func = (nfsd4op_func)nfsd4_getattr, .op_flags = ALLOWED_ON_ABSENT_FS, .op_rsize_bop = nfsd4_getattr_rsize, .op_name = "OP_GETATTR", }, [OP_GETFH] = { .op_func = (nfsd4op_func)nfsd4_getfh, .op_name = "OP_GETFH", .op_rsize_bop = (nfsd4op_rsize)nfsd4_getfh_rsize, }, [OP_LINK] = { .op_func = (nfsd4op_func)nfsd4_link, .op_flags = ALLOWED_ON_ABSENT_FS | OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_LINK", .op_rsize_bop = (nfsd4op_rsize)nfsd4_link_rsize, }, [OP_LOCK] = { .op_func = (nfsd4op_func)nfsd4_lock, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_LOCK", .op_rsize_bop = (nfsd4op_rsize)nfsd4_lock_rsize, .op_set_currentstateid = (stateid_setter)nfsd4_set_lockstateid, }, [OP_LOCKT] = { .op_func = (nfsd4op_func)nfsd4_lockt, .op_name = "OP_LOCKT", .op_rsize_bop = (nfsd4op_rsize)nfsd4_lock_rsize, }, [OP_LOCKU] = { .op_func = (nfsd4op_func)nfsd4_locku, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_LOCKU", .op_rsize_bop = (nfsd4op_rsize)nfsd4_status_stateid_rsize, .op_get_currentstateid = (stateid_getter)nfsd4_get_lockustateid, }, [OP_LOOKUP] = { .op_func = (nfsd4op_func)nfsd4_lookup, .op_flags = OP_HANDLES_WRONGSEC | OP_CLEAR_STATEID, .op_name = "OP_LOOKUP", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_LOOKUPP] = { .op_func = (nfsd4op_func)nfsd4_lookupp, .op_flags = OP_HANDLES_WRONGSEC | OP_CLEAR_STATEID, .op_name = "OP_LOOKUPP", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_NVERIFY] = { .op_func = (nfsd4op_func)nfsd4_nverify, .op_name = "OP_NVERIFY", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_OPEN] = { .op_func = (nfsd4op_func)nfsd4_open, .op_flags = OP_HANDLES_WRONGSEC | OP_MODIFIES_SOMETHING, .op_name = "OP_OPEN", .op_rsize_bop = (nfsd4op_rsize)nfsd4_open_rsize, .op_set_currentstateid = (stateid_setter)nfsd4_set_openstateid, }, [OP_OPEN_CONFIRM] = { .op_func = (nfsd4op_func)nfsd4_open_confirm, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_OPEN_CONFIRM", .op_rsize_bop = (nfsd4op_rsize)nfsd4_status_stateid_rsize, }, [OP_OPEN_DOWNGRADE] = { .op_func = (nfsd4op_func)nfsd4_open_downgrade, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_OPEN_DOWNGRADE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_status_stateid_rsize, .op_get_currentstateid = (stateid_getter)nfsd4_get_opendowngradestateid, .op_set_currentstateid = (stateid_setter)nfsd4_set_opendowngradestateid, }, [OP_PUTFH] = { .op_func = (nfsd4op_func)nfsd4_putfh, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_IS_PUTFH_LIKE | OP_CLEAR_STATEID, .op_name = "OP_PUTFH", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_PUTPUBFH] = { .op_func = (nfsd4op_func)nfsd4_putrootfh, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_IS_PUTFH_LIKE | OP_CLEAR_STATEID, .op_name = "OP_PUTPUBFH", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_PUTROOTFH] = { .op_func = (nfsd4op_func)nfsd4_putrootfh, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_IS_PUTFH_LIKE | OP_CLEAR_STATEID, .op_name = "OP_PUTROOTFH", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_READ] = { .op_func = (nfsd4op_func)nfsd4_read, .op_name = "OP_READ", .op_rsize_bop = (nfsd4op_rsize)nfsd4_read_rsize, .op_get_currentstateid = (stateid_getter)nfsd4_get_readstateid, }, [OP_READDIR] = { .op_func = (nfsd4op_func)nfsd4_readdir, .op_name = "OP_READDIR", .op_rsize_bop = (nfsd4op_rsize)nfsd4_readdir_rsize, }, [OP_READLINK] = { .op_func = (nfsd4op_func)nfsd4_readlink, .op_name = "OP_READLINK", .op_rsize_bop = (nfsd4op_rsize)nfsd4_readlink_rsize, }, [OP_REMOVE] = { .op_func = (nfsd4op_func)nfsd4_remove, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_REMOVE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_remove_rsize, }, [OP_RENAME] = { .op_func = (nfsd4op_func)nfsd4_rename, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_RENAME", .op_rsize_bop = (nfsd4op_rsize)nfsd4_rename_rsize, }, [OP_RENEW] = { .op_func = (nfsd4op_func)nfsd4_renew, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_MODIFIES_SOMETHING, .op_name = "OP_RENEW", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_RESTOREFH] = { .op_func = (nfsd4op_func)nfsd4_restorefh, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_IS_PUTFH_LIKE | OP_MODIFIES_SOMETHING, .op_name = "OP_RESTOREFH", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_SAVEFH] = { .op_func = (nfsd4op_func)nfsd4_savefh, .op_flags = OP_HANDLES_WRONGSEC | OP_MODIFIES_SOMETHING, .op_name = "OP_SAVEFH", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_SECINFO] = { .op_func = (nfsd4op_func)nfsd4_secinfo, .op_flags = OP_HANDLES_WRONGSEC, .op_name = "OP_SECINFO", .op_rsize_bop = (nfsd4op_rsize)nfsd4_secinfo_rsize, }, [OP_SETATTR] = { .op_func = (nfsd4op_func)nfsd4_setattr, .op_name = "OP_SETATTR", .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_rsize_bop = (nfsd4op_rsize)nfsd4_setattr_rsize, .op_get_currentstateid = (stateid_getter)nfsd4_get_setattrstateid, }, [OP_SETCLIENTID] = { .op_func = (nfsd4op_func)nfsd4_setclientid, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_SETCLIENTID", .op_rsize_bop = (nfsd4op_rsize)nfsd4_setclientid_rsize, }, [OP_SETCLIENTID_CONFIRM] = { .op_func = (nfsd4op_func)nfsd4_setclientid_confirm, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_SETCLIENTID_CONFIRM", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_VERIFY] = { .op_func = (nfsd4op_func)nfsd4_verify, .op_name = "OP_VERIFY", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_WRITE] = { .op_func = (nfsd4op_func)nfsd4_write, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_WRITE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_write_rsize, .op_get_currentstateid = (stateid_getter)nfsd4_get_writestateid, }, [OP_RELEASE_LOCKOWNER] = { .op_func = (nfsd4op_func)nfsd4_release_lockowner, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_ON_ABSENT_FS | OP_MODIFIES_SOMETHING, .op_name = "OP_RELEASE_LOCKOWNER", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, /* NFSv4.1 operations */ [OP_EXCHANGE_ID] = { .op_func = (nfsd4op_func)nfsd4_exchange_id, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_AS_FIRST_OP | OP_MODIFIES_SOMETHING, .op_name = "OP_EXCHANGE_ID", .op_rsize_bop = (nfsd4op_rsize)nfsd4_exchange_id_rsize, }, [OP_BACKCHANNEL_CTL] = { .op_func = (nfsd4op_func)nfsd4_backchannel_ctl, .op_flags = ALLOWED_WITHOUT_FH | OP_MODIFIES_SOMETHING, .op_name = "OP_BACKCHANNEL_CTL", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_BIND_CONN_TO_SESSION] = { .op_func = (nfsd4op_func)nfsd4_bind_conn_to_session, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_AS_FIRST_OP | OP_MODIFIES_SOMETHING, .op_name = "OP_BIND_CONN_TO_SESSION", .op_rsize_bop = (nfsd4op_rsize)nfsd4_bind_conn_to_session_rsize, }, [OP_CREATE_SESSION] = { .op_func = (nfsd4op_func)nfsd4_create_session, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_AS_FIRST_OP | OP_MODIFIES_SOMETHING, .op_name = "OP_CREATE_SESSION", .op_rsize_bop = (nfsd4op_rsize)nfsd4_create_session_rsize, }, [OP_DESTROY_SESSION] = { .op_func = (nfsd4op_func)nfsd4_destroy_session, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_AS_FIRST_OP | OP_MODIFIES_SOMETHING, .op_name = "OP_DESTROY_SESSION", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_SEQUENCE] = { .op_func = (nfsd4op_func)nfsd4_sequence, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_AS_FIRST_OP, .op_name = "OP_SEQUENCE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_sequence_rsize, }, [OP_DESTROY_CLIENTID] = { .op_func = (nfsd4op_func)nfsd4_destroy_clientid, .op_flags = ALLOWED_WITHOUT_FH | ALLOWED_AS_FIRST_OP | OP_MODIFIES_SOMETHING, .op_name = "OP_DESTROY_CLIENTID", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_RECLAIM_COMPLETE] = { .op_func = (nfsd4op_func)nfsd4_reclaim_complete, .op_flags = ALLOWED_WITHOUT_FH | OP_MODIFIES_SOMETHING, .op_name = "OP_RECLAIM_COMPLETE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_SECINFO_NO_NAME] = { .op_func = (nfsd4op_func)nfsd4_secinfo_no_name, .op_flags = OP_HANDLES_WRONGSEC, .op_name = "OP_SECINFO_NO_NAME", .op_rsize_bop = (nfsd4op_rsize)nfsd4_secinfo_rsize, }, [OP_TEST_STATEID] = { .op_func = (nfsd4op_func)nfsd4_test_stateid, .op_flags = ALLOWED_WITHOUT_FH, .op_name = "OP_TEST_STATEID", .op_rsize_bop = (nfsd4op_rsize)nfsd4_test_stateid_rsize, }, [OP_FREE_STATEID] = { .op_func = (nfsd4op_func)nfsd4_free_stateid, .op_flags = ALLOWED_WITHOUT_FH | OP_MODIFIES_SOMETHING, .op_name = "OP_FREE_STATEID", .op_get_currentstateid = (stateid_getter)nfsd4_get_freestateid, .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, #ifdef CONFIG_NFSD_PNFS [OP_GETDEVICEINFO] = { .op_func = (nfsd4op_func)nfsd4_getdeviceinfo, .op_flags = ALLOWED_WITHOUT_FH, .op_name = "OP_GETDEVICEINFO", .op_rsize_bop = (nfsd4op_rsize)nfsd4_getdeviceinfo_rsize, }, [OP_LAYOUTGET] = { .op_func = (nfsd4op_func)nfsd4_layoutget, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_LAYOUTGET", .op_rsize_bop = (nfsd4op_rsize)nfsd4_layoutget_rsize, }, [OP_LAYOUTCOMMIT] = { .op_func = (nfsd4op_func)nfsd4_layoutcommit, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_LAYOUTCOMMIT", .op_rsize_bop = (nfsd4op_rsize)nfsd4_layoutcommit_rsize, }, [OP_LAYOUTRETURN] = { .op_func = (nfsd4op_func)nfsd4_layoutreturn, .op_flags = OP_MODIFIES_SOMETHING, .op_name = "OP_LAYOUTRETURN", .op_rsize_bop = (nfsd4op_rsize)nfsd4_layoutreturn_rsize, }, #endif /* CONFIG_NFSD_PNFS */ /* NFSv4.2 operations */ [OP_ALLOCATE] = { .op_func = (nfsd4op_func)nfsd4_allocate, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_ALLOCATE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_DEALLOCATE] = { .op_func = (nfsd4op_func)nfsd4_deallocate, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_DEALLOCATE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_CLONE] = { .op_func = (nfsd4op_func)nfsd4_clone, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_CLONE", .op_rsize_bop = (nfsd4op_rsize)nfsd4_only_status_rsize, }, [OP_COPY] = { .op_func = (nfsd4op_func)nfsd4_copy, .op_flags = OP_MODIFIES_SOMETHING | OP_CACHEME, .op_name = "OP_COPY", .op_rsize_bop = (nfsd4op_rsize)nfsd4_copy_rsize, }, [OP_SEEK] = { .op_func = (nfsd4op_func)nfsd4_seek, .op_name = "OP_SEEK", .op_rsize_bop = (nfsd4op_rsize)nfsd4_seek_rsize, }, }; /** * nfsd4_spo_must_allow - Determine if the compound op contains an * operation that is allowed to be sent with machine credentials * * @rqstp: a pointer to the struct svc_rqst * * Checks to see if the compound contains a spo_must_allow op * and confirms that it was sent with the proper machine creds. */ bool nfsd4_spo_must_allow(struct svc_rqst *rqstp) { struct nfsd4_compoundres *resp = rqstp->rq_resp; struct nfsd4_compoundargs *argp = rqstp->rq_argp; struct nfsd4_op *this = &argp->ops[resp->opcnt - 1]; struct nfsd4_compound_state *cstate = &resp->cstate; struct nfs4_op_map *allow = &cstate->clp->cl_spo_must_allow; u32 opiter; if (!cstate->minorversion) return false; if (cstate->spo_must_allowed == true) return true; opiter = resp->opcnt; while (opiter < argp->opcnt) { this = &argp->ops[opiter++]; if (test_bit(this->opnum, allow->u.longs) && cstate->clp->cl_mach_cred && nfsd4_mach_creds_match(cstate->clp, rqstp)) { cstate->spo_must_allowed = true; return true; } } cstate->spo_must_allowed = false; return false; } int nfsd4_max_reply(struct svc_rqst *rqstp, struct nfsd4_op *op) { if (op->opnum == OP_ILLEGAL || op->status == nfserr_notsupp) return op_encode_hdr_size * sizeof(__be32); BUG_ON(OPDESC(op)->op_rsize_bop == NULL); return OPDESC(op)->op_rsize_bop(rqstp, op); } void warn_on_nonidempotent_op(struct nfsd4_op *op) { if (OPDESC(op)->op_flags & OP_MODIFIES_SOMETHING) { pr_err("unable to encode reply to nonidempotent op %d (%s)\n", op->opnum, nfsd4_op_name(op->opnum)); WARN_ON_ONCE(1); } } static const char *nfsd4_op_name(unsigned opnum) { if (opnum < ARRAY_SIZE(nfsd4_ops)) return nfsd4_ops[opnum].op_name; return "unknown_operation"; } #define nfsd4_voidres nfsd4_voidargs struct nfsd4_voidargs { int dummy; }; static struct svc_procedure nfsd_procedures4[2] = { [NFSPROC4_NULL] = { .pc_func = (svc_procfunc) nfsd4_proc_null, .pc_encode = (kxdrproc_t) nfs4svc_encode_voidres, .pc_argsize = sizeof(struct nfsd4_voidargs), .pc_ressize = sizeof(struct nfsd4_voidres), .pc_cachetype = RC_NOCACHE, .pc_xdrressize = 1, }, [NFSPROC4_COMPOUND] = { .pc_func = (svc_procfunc) nfsd4_proc_compound, .pc_decode = (kxdrproc_t) nfs4svc_decode_compoundargs, .pc_encode = (kxdrproc_t) nfs4svc_encode_compoundres, .pc_argsize = sizeof(struct nfsd4_compoundargs), .pc_ressize = sizeof(struct nfsd4_compoundres), .pc_release = nfsd4_release_compoundargs, .pc_cachetype = RC_NOCACHE, .pc_xdrressize = NFSD_BUFSIZE/4, }, }; struct svc_version nfsd_version4 = { .vs_vers = 4, .vs_nproc = 2, .vs_proc = nfsd_procedures4, .vs_dispatch = nfsd_dispatch, .vs_xdrsize = NFS4_SVC_XDRSIZE, .vs_rpcb_optnl = true, .vs_need_cong_ctrl = true, }; /* * Local variables: * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-129/c/good_3335_0
crossvul-cpp_data_bad_1182_0
/* * Westwood Studios VQA Video Decoder * Copyright (C) 2003 The FFmpeg project * * 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 */ /** * @file * VQA Video Decoder * @author Mike Melanson (melanson@pcisys.net) * @see http://wiki.multimedia.cx/index.php?title=VQA * * The VQA video decoder outputs PAL8 or RGB555 colorspace data, depending * on the type of data in the file. * * This decoder needs the 42-byte VQHD header from the beginning * of the VQA file passed through the extradata field. The VQHD header * is laid out as: * * bytes 0-3 chunk fourcc: 'VQHD' * bytes 4-7 chunk size in big-endian format, should be 0x0000002A * bytes 8-49 VQHD chunk data * * Bytes 8-49 are what this decoder expects to see. * * Briefly, VQA is a vector quantized animation format that operates in a * VGA palettized colorspace. It operates on pixel vectors (blocks) * of either 4x2 or 4x4 in size. Compressed VQA chunks can contain vector * codebooks, palette information, and code maps for rendering vectors onto * frames. Any of these components can also be compressed with a run-length * encoding (RLE) algorithm commonly referred to as "format80". * * VQA takes a novel approach to rate control. Each group of n frames * (usually, n = 8) relies on a different vector codebook. Rather than * transporting an entire codebook every 8th frame, the new codebook is * broken up into 8 pieces and sent along with the compressed video chunks * for each of the 8 frames preceding the 8 frames which require the * codebook. A full codebook is also sent on the very first frame of a * file. This is an interesting technique, although it makes random file * seeking difficult despite the fact that the frames are all intracoded. * * V1,2 VQA uses 12-bit codebook indexes. If the 12-bit indexes were * packed into bytes and then RLE compressed, bytewise, the results would * be poor. That is why the coding method divides each index into 2 parts, * the top 4 bits and the bottom 8 bits, then RL encodes the 4-bit pieces * together and the 8-bit pieces together. If most of the vectors are * clustered into one group of 256 vectors, most of the 4-bit index pieces * should be the same. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "libavutil/intreadwrite.h" #include "libavutil/imgutils.h" #include "avcodec.h" #include "bytestream.h" #include "internal.h" #define PALETTE_COUNT 256 #define VQA_HEADER_SIZE 0x2A /* allocate the maximum vector space, regardless of the file version: * (0xFF00 codebook vectors + 0x100 solid pixel vectors) * (4x4 pixels/block) */ #define MAX_CODEBOOK_VECTORS 0xFF00 #define SOLID_PIXEL_VECTORS 0x100 #define MAX_VECTORS (MAX_CODEBOOK_VECTORS + SOLID_PIXEL_VECTORS) #define MAX_CODEBOOK_SIZE (MAX_VECTORS * 4 * 4) #define CBF0_TAG MKBETAG('C', 'B', 'F', '0') #define CBFZ_TAG MKBETAG('C', 'B', 'F', 'Z') #define CBP0_TAG MKBETAG('C', 'B', 'P', '0') #define CBPZ_TAG MKBETAG('C', 'B', 'P', 'Z') #define CPL0_TAG MKBETAG('C', 'P', 'L', '0') #define CPLZ_TAG MKBETAG('C', 'P', 'L', 'Z') #define VPTZ_TAG MKBETAG('V', 'P', 'T', 'Z') typedef struct VqaContext { AVCodecContext *avctx; GetByteContext gb; uint32_t palette[PALETTE_COUNT]; int width; /* width of a frame */ int height; /* height of a frame */ int vector_width; /* width of individual vector */ int vector_height; /* height of individual vector */ int vqa_version; /* this should be either 1, 2 or 3 */ unsigned char *codebook; /* the current codebook */ int codebook_size; unsigned char *next_codebook_buffer; /* accumulator for next codebook */ int next_codebook_buffer_index; unsigned char *decode_buffer; int decode_buffer_size; /* number of frames to go before replacing codebook */ int partial_countdown; int partial_count; } VqaContext; static av_cold int vqa_decode_init(AVCodecContext *avctx) { VqaContext *s = avctx->priv_data; int i, j, codebook_index, ret; s->avctx = avctx; avctx->pix_fmt = AV_PIX_FMT_PAL8; /* make sure the extradata made it */ if (s->avctx->extradata_size != VQA_HEADER_SIZE) { av_log(s->avctx, AV_LOG_ERROR, "expected extradata size of %d\n", VQA_HEADER_SIZE); return AVERROR(EINVAL); } /* load up the VQA parameters from the header */ s->vqa_version = s->avctx->extradata[0]; switch (s->vqa_version) { case 1: case 2: break; case 3: avpriv_report_missing_feature(avctx, "VQA Version %d", s->vqa_version); return AVERROR_PATCHWELCOME; default: avpriv_request_sample(avctx, "VQA Version %i", s->vqa_version); return AVERROR_PATCHWELCOME; } s->width = AV_RL16(&s->avctx->extradata[6]); s->height = AV_RL16(&s->avctx->extradata[8]); if ((ret = av_image_check_size(s->width, s->height, 0, avctx)) < 0) { s->width= s->height= 0; return ret; } s->vector_width = s->avctx->extradata[10]; s->vector_height = s->avctx->extradata[11]; s->partial_count = s->partial_countdown = s->avctx->extradata[13]; /* the vector dimensions have to meet very stringent requirements */ if ((s->vector_width != 4) || ((s->vector_height != 2) && (s->vector_height != 4))) { /* return without further initialization */ return AVERROR_INVALIDDATA; } if (s->width % s->vector_width || s->height % s->vector_height) { av_log(avctx, AV_LOG_ERROR, "Image size not multiple of block size\n"); return AVERROR_INVALIDDATA; } /* allocate codebooks */ s->codebook_size = MAX_CODEBOOK_SIZE; s->codebook = av_malloc(s->codebook_size); if (!s->codebook) goto fail; s->next_codebook_buffer = av_malloc(s->codebook_size); if (!s->next_codebook_buffer) goto fail; /* allocate decode buffer */ s->decode_buffer_size = (s->width / s->vector_width) * (s->height / s->vector_height) * 2; s->decode_buffer = av_mallocz(s->decode_buffer_size); if (!s->decode_buffer) goto fail; /* initialize the solid-color vectors */ if (s->vector_height == 4) { codebook_index = 0xFF00 * 16; for (i = 0; i < 256; i++) for (j = 0; j < 16; j++) s->codebook[codebook_index++] = i; } else { codebook_index = 0xF00 * 8; for (i = 0; i < 256; i++) for (j = 0; j < 8; j++) s->codebook[codebook_index++] = i; } s->next_codebook_buffer_index = 0; return 0; fail: av_freep(&s->codebook); av_freep(&s->next_codebook_buffer); av_freep(&s->decode_buffer); return AVERROR(ENOMEM); } #define CHECK_COUNT() \ if (dest_index + count > dest_size) { \ av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: next op would overflow dest_index\n"); \ av_log(s->avctx, AV_LOG_ERROR, "current dest_index = %d, count = %d, dest_size = %d\n", \ dest_index, count, dest_size); \ return AVERROR_INVALIDDATA; \ } #define CHECK_COPY(idx) \ if (idx < 0 || idx + count > dest_size) { \ av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: next op would overflow dest_index\n"); \ av_log(s->avctx, AV_LOG_ERROR, "current src_pos = %d, count = %d, dest_size = %d\n", \ src_pos, count, dest_size); \ return AVERROR_INVALIDDATA; \ } static int decode_format80(VqaContext *s, int src_size, unsigned char *dest, int dest_size, int check_size) { int dest_index = 0; int count, opcode, start; int src_pos; unsigned char color; int i; if (src_size < 0 || src_size > bytestream2_get_bytes_left(&s->gb)) { av_log(s->avctx, AV_LOG_ERROR, "Chunk size %d is out of range\n", src_size); return AVERROR_INVALIDDATA; } start = bytestream2_tell(&s->gb); while (bytestream2_tell(&s->gb) - start < src_size) { opcode = bytestream2_get_byte(&s->gb); ff_tlog(s->avctx, "opcode %02X: ", opcode); /* 0x80 means that frame is finished */ if (opcode == 0x80) break; if (dest_index >= dest_size) { av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: dest_index (%d) exceeded dest_size (%d)\n", dest_index, dest_size); return AVERROR_INVALIDDATA; } if (opcode == 0xFF) { count = bytestream2_get_le16(&s->gb); src_pos = bytestream2_get_le16(&s->gb); ff_tlog(s->avctx, "(1) copy %X bytes from absolute pos %X\n", count, src_pos); CHECK_COUNT(); CHECK_COPY(src_pos); for (i = 0; i < count; i++) dest[dest_index + i] = dest[src_pos + i]; dest_index += count; } else if (opcode == 0xFE) { count = bytestream2_get_le16(&s->gb); color = bytestream2_get_byte(&s->gb); ff_tlog(s->avctx, "(2) set %X bytes to %02X\n", count, color); CHECK_COUNT(); memset(&dest[dest_index], color, count); dest_index += count; } else if ((opcode & 0xC0) == 0xC0) { count = (opcode & 0x3F) + 3; src_pos = bytestream2_get_le16(&s->gb); ff_tlog(s->avctx, "(3) copy %X bytes from absolute pos %X\n", count, src_pos); CHECK_COUNT(); CHECK_COPY(src_pos); for (i = 0; i < count; i++) dest[dest_index + i] = dest[src_pos + i]; dest_index += count; } else if (opcode > 0x80) { count = opcode & 0x3F; ff_tlog(s->avctx, "(4) copy %X bytes from source to dest\n", count); CHECK_COUNT(); bytestream2_get_buffer(&s->gb, &dest[dest_index], count); dest_index += count; } else { count = ((opcode & 0x70) >> 4) + 3; src_pos = bytestream2_get_byte(&s->gb) | ((opcode & 0x0F) << 8); ff_tlog(s->avctx, "(5) copy %X bytes from relpos %X\n", count, src_pos); CHECK_COUNT(); CHECK_COPY(dest_index - src_pos); for (i = 0; i < count; i++) dest[dest_index + i] = dest[dest_index - src_pos + i]; dest_index += count; } } /* validate that the entire destination buffer was filled; this is * important for decoding frame maps since each vector needs to have a * codebook entry; it is not important for compressed codebooks because * not every entry needs to be filled */ if (check_size) if (dest_index < dest_size) { av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: decode finished with dest_index (%d) < dest_size (%d)\n", dest_index, dest_size); memset(dest + dest_index, 0, dest_size - dest_index); } return 0; // let's display what we decoded anyway } static int vqa_decode_chunk(VqaContext *s, AVFrame *frame) { unsigned int chunk_type; unsigned int chunk_size; int byte_skip; unsigned int index = 0; int i; unsigned char r, g, b; int index_shift; int res; int cbf0_chunk = -1; int cbfz_chunk = -1; int cbp0_chunk = -1; int cbpz_chunk = -1; int cpl0_chunk = -1; int cplz_chunk = -1; int vptz_chunk = -1; int x, y; int lines = 0; int pixel_ptr; int vector_index = 0; int lobyte = 0; int hibyte = 0; int lobytes = 0; int hibytes = s->decode_buffer_size / 2; /* first, traverse through the frame and find the subchunks */ while (bytestream2_get_bytes_left(&s->gb) >= 8) { chunk_type = bytestream2_get_be32u(&s->gb); index = bytestream2_tell(&s->gb); chunk_size = bytestream2_get_be32u(&s->gb); switch (chunk_type) { case CBF0_TAG: cbf0_chunk = index; break; case CBFZ_TAG: cbfz_chunk = index; break; case CBP0_TAG: cbp0_chunk = index; break; case CBPZ_TAG: cbpz_chunk = index; break; case CPL0_TAG: cpl0_chunk = index; break; case CPLZ_TAG: cplz_chunk = index; break; case VPTZ_TAG: vptz_chunk = index; break; default: av_log(s->avctx, AV_LOG_ERROR, "Found unknown chunk type: %s (%08X)\n", av_fourcc2str(av_bswap32(chunk_type)), chunk_type); break; } byte_skip = chunk_size & 0x01; bytestream2_skip(&s->gb, chunk_size + byte_skip); } /* next, deal with the palette */ if ((cpl0_chunk != -1) && (cplz_chunk != -1)) { /* a chunk should not have both chunk types */ av_log(s->avctx, AV_LOG_ERROR, "problem: found both CPL0 and CPLZ chunks\n"); return AVERROR_INVALIDDATA; } /* decompress the palette chunk */ if (cplz_chunk != -1) { /* yet to be handled */ } /* convert the RGB palette into the machine's endian format */ if (cpl0_chunk != -1) { bytestream2_seek(&s->gb, cpl0_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); /* sanity check the palette size */ if (chunk_size / 3 > 256 || chunk_size > bytestream2_get_bytes_left(&s->gb)) { av_log(s->avctx, AV_LOG_ERROR, "problem: found a palette chunk with %d colors\n", chunk_size / 3); return AVERROR_INVALIDDATA; } for (i = 0; i < chunk_size / 3; i++) { /* scale by 4 to transform 6-bit palette -> 8-bit */ r = bytestream2_get_byteu(&s->gb) * 4; g = bytestream2_get_byteu(&s->gb) * 4; b = bytestream2_get_byteu(&s->gb) * 4; s->palette[i] = 0xFFU << 24 | r << 16 | g << 8 | b; s->palette[i] |= s->palette[i] >> 6 & 0x30303; } } /* next, look for a full codebook */ if ((cbf0_chunk != -1) && (cbfz_chunk != -1)) { /* a chunk should not have both chunk types */ av_log(s->avctx, AV_LOG_ERROR, "problem: found both CBF0 and CBFZ chunks\n"); return AVERROR_INVALIDDATA; } /* decompress the full codebook chunk */ if (cbfz_chunk != -1) { bytestream2_seek(&s->gb, cbfz_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if ((res = decode_format80(s, chunk_size, s->codebook, s->codebook_size, 0)) < 0) return res; } /* copy a full codebook */ if (cbf0_chunk != -1) { bytestream2_seek(&s->gb, cbf0_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); /* sanity check the full codebook size */ if (chunk_size > MAX_CODEBOOK_SIZE) { av_log(s->avctx, AV_LOG_ERROR, "problem: CBF0 chunk too large (0x%X bytes)\n", chunk_size); return AVERROR_INVALIDDATA; } bytestream2_get_buffer(&s->gb, s->codebook, chunk_size); } /* decode the frame */ if (vptz_chunk == -1) { /* something is wrong if there is no VPTZ chunk */ av_log(s->avctx, AV_LOG_ERROR, "problem: no VPTZ chunk found\n"); return AVERROR_INVALIDDATA; } bytestream2_seek(&s->gb, vptz_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if ((res = decode_format80(s, chunk_size, s->decode_buffer, s->decode_buffer_size, 1)) < 0) return res; /* render the final PAL8 frame */ if (s->vector_height == 4) index_shift = 4; else index_shift = 3; for (y = 0; y < s->height; y += s->vector_height) { for (x = 0; x < s->width; x += 4, lobytes++, hibytes++) { pixel_ptr = y * frame->linesize[0] + x; /* get the vector index, the method for which varies according to * VQA file version */ switch (s->vqa_version) { case 1: lobyte = s->decode_buffer[lobytes * 2]; hibyte = s->decode_buffer[(lobytes * 2) + 1]; vector_index = ((hibyte << 8) | lobyte) >> 3; vector_index <<= index_shift; lines = s->vector_height; /* uniform color fill - a quick hack */ if (hibyte == 0xFF) { while (lines--) { frame->data[0][pixel_ptr + 0] = 255 - lobyte; frame->data[0][pixel_ptr + 1] = 255 - lobyte; frame->data[0][pixel_ptr + 2] = 255 - lobyte; frame->data[0][pixel_ptr + 3] = 255 - lobyte; pixel_ptr += frame->linesize[0]; } lines=0; } break; case 2: lobyte = s->decode_buffer[lobytes]; hibyte = s->decode_buffer[hibytes]; vector_index = (hibyte << 8) | lobyte; vector_index <<= index_shift; lines = s->vector_height; break; case 3: /* not implemented yet */ lines = 0; break; } while (lines--) { frame->data[0][pixel_ptr + 0] = s->codebook[vector_index++]; frame->data[0][pixel_ptr + 1] = s->codebook[vector_index++]; frame->data[0][pixel_ptr + 2] = s->codebook[vector_index++]; frame->data[0][pixel_ptr + 3] = s->codebook[vector_index++]; pixel_ptr += frame->linesize[0]; } } } /* handle partial codebook */ if ((cbp0_chunk != -1) && (cbpz_chunk != -1)) { /* a chunk should not have both chunk types */ av_log(s->avctx, AV_LOG_ERROR, "problem: found both CBP0 and CBPZ chunks\n"); return AVERROR_INVALIDDATA; } if (cbp0_chunk != -1) { bytestream2_seek(&s->gb, cbp0_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if (chunk_size > MAX_CODEBOOK_SIZE - s->next_codebook_buffer_index) { av_log(s->avctx, AV_LOG_ERROR, "cbp0 chunk too large (%u bytes)\n", chunk_size); return AVERROR_INVALIDDATA; } /* accumulate partial codebook */ bytestream2_get_buffer(&s->gb, &s->next_codebook_buffer[s->next_codebook_buffer_index], chunk_size); s->next_codebook_buffer_index += chunk_size; s->partial_countdown--; if (s->partial_countdown <= 0) { /* time to replace codebook */ memcpy(s->codebook, s->next_codebook_buffer, s->next_codebook_buffer_index); /* reset accounting */ s->next_codebook_buffer_index = 0; s->partial_countdown = s->partial_count; } } if (cbpz_chunk != -1) { bytestream2_seek(&s->gb, cbpz_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if (chunk_size > MAX_CODEBOOK_SIZE - s->next_codebook_buffer_index) { av_log(s->avctx, AV_LOG_ERROR, "cbpz chunk too large (%u bytes)\n", chunk_size); return AVERROR_INVALIDDATA; } /* accumulate partial codebook */ bytestream2_get_buffer(&s->gb, &s->next_codebook_buffer[s->next_codebook_buffer_index], chunk_size); s->next_codebook_buffer_index += chunk_size; s->partial_countdown--; if (s->partial_countdown <= 0) { bytestream2_init(&s->gb, s->next_codebook_buffer, s->next_codebook_buffer_index); /* decompress codebook */ if ((res = decode_format80(s, s->next_codebook_buffer_index, s->codebook, s->codebook_size, 0)) < 0) return res; /* reset accounting */ s->next_codebook_buffer_index = 0; s->partial_countdown = s->partial_count; } } return 0; } static int vqa_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { VqaContext *s = avctx->priv_data; AVFrame *frame = data; int res; if ((res = ff_get_buffer(avctx, frame, 0)) < 0) return res; bytestream2_init(&s->gb, avpkt->data, avpkt->size); if ((res = vqa_decode_chunk(s, frame)) < 0) return res; /* make the palette available on the way out */ memcpy(frame->data[1], s->palette, PALETTE_COUNT * 4); frame->palette_has_changed = 1; *got_frame = 1; /* report that the buffer was completely consumed */ return avpkt->size; } static av_cold int vqa_decode_end(AVCodecContext *avctx) { VqaContext *s = avctx->priv_data; av_freep(&s->codebook); av_freep(&s->next_codebook_buffer); av_freep(&s->decode_buffer); return 0; } AVCodec ff_vqa_decoder = { .name = "vqavideo", .long_name = NULL_IF_CONFIG_SMALL("Westwood Studios VQA (Vector Quantized Animation) video"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_WS_VQA, .priv_data_size = sizeof(VqaContext), .init = vqa_decode_init, .close = vqa_decode_end, .decode = vqa_decode_frame, .capabilities = AV_CODEC_CAP_DR1, };
./CrossVul/dataset_final_sorted/CWE-129/c/bad_1182_0
crossvul-cpp_data_good_2552_0
/* * fs/f2fs/super.c * * Copyright (c) 2012 Samsung Electronics Co., Ltd. * http://www.samsung.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. */ #include <linux/module.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/statfs.h> #include <linux/buffer_head.h> #include <linux/backing-dev.h> #include <linux/kthread.h> #include <linux/parser.h> #include <linux/mount.h> #include <linux/seq_file.h> #include <linux/proc_fs.h> #include <linux/random.h> #include <linux/exportfs.h> #include <linux/blkdev.h> #include <linux/f2fs_fs.h> #include <linux/sysfs.h> #include "f2fs.h" #include "node.h" #include "segment.h" #include "xattr.h" #include "gc.h" #include "trace.h" #define CREATE_TRACE_POINTS #include <trace/events/f2fs.h> static struct proc_dir_entry *f2fs_proc_root; static struct kmem_cache *f2fs_inode_cachep; static struct kset *f2fs_kset; #ifdef CONFIG_F2FS_FAULT_INJECTION char *fault_name[FAULT_MAX] = { [FAULT_KMALLOC] = "kmalloc", [FAULT_PAGE_ALLOC] = "page alloc", [FAULT_ALLOC_NID] = "alloc nid", [FAULT_ORPHAN] = "orphan", [FAULT_BLOCK] = "no more block", [FAULT_DIR_DEPTH] = "too big dir depth", [FAULT_EVICT_INODE] = "evict_inode fail", [FAULT_TRUNCATE] = "truncate fail", [FAULT_IO] = "IO error", [FAULT_CHECKPOINT] = "checkpoint error", }; static void f2fs_build_fault_attr(struct f2fs_sb_info *sbi, unsigned int rate) { struct f2fs_fault_info *ffi = &sbi->fault_info; if (rate) { atomic_set(&ffi->inject_ops, 0); ffi->inject_rate = rate; ffi->inject_type = (1 << FAULT_MAX) - 1; } else { memset(ffi, 0, sizeof(struct f2fs_fault_info)); } } #endif /* f2fs-wide shrinker description */ static struct shrinker f2fs_shrinker_info = { .scan_objects = f2fs_shrink_scan, .count_objects = f2fs_shrink_count, .seeks = DEFAULT_SEEKS, }; enum { Opt_gc_background, Opt_disable_roll_forward, Opt_norecovery, Opt_discard, Opt_nodiscard, Opt_noheap, Opt_heap, Opt_user_xattr, Opt_nouser_xattr, Opt_acl, Opt_noacl, Opt_active_logs, Opt_disable_ext_identify, Opt_inline_xattr, Opt_noinline_xattr, Opt_inline_data, Opt_inline_dentry, Opt_noinline_dentry, Opt_flush_merge, Opt_noflush_merge, Opt_nobarrier, Opt_fastboot, Opt_extent_cache, Opt_noextent_cache, Opt_noinline_data, Opt_data_flush, Opt_mode, Opt_io_size_bits, Opt_fault_injection, Opt_lazytime, Opt_nolazytime, Opt_err, }; static match_table_t f2fs_tokens = { {Opt_gc_background, "background_gc=%s"}, {Opt_disable_roll_forward, "disable_roll_forward"}, {Opt_norecovery, "norecovery"}, {Opt_discard, "discard"}, {Opt_nodiscard, "nodiscard"}, {Opt_noheap, "no_heap"}, {Opt_heap, "heap"}, {Opt_user_xattr, "user_xattr"}, {Opt_nouser_xattr, "nouser_xattr"}, {Opt_acl, "acl"}, {Opt_noacl, "noacl"}, {Opt_active_logs, "active_logs=%u"}, {Opt_disable_ext_identify, "disable_ext_identify"}, {Opt_inline_xattr, "inline_xattr"}, {Opt_noinline_xattr, "noinline_xattr"}, {Opt_inline_data, "inline_data"}, {Opt_inline_dentry, "inline_dentry"}, {Opt_noinline_dentry, "noinline_dentry"}, {Opt_flush_merge, "flush_merge"}, {Opt_noflush_merge, "noflush_merge"}, {Opt_nobarrier, "nobarrier"}, {Opt_fastboot, "fastboot"}, {Opt_extent_cache, "extent_cache"}, {Opt_noextent_cache, "noextent_cache"}, {Opt_noinline_data, "noinline_data"}, {Opt_data_flush, "data_flush"}, {Opt_mode, "mode=%s"}, {Opt_io_size_bits, "io_bits=%u"}, {Opt_fault_injection, "fault_injection=%u"}, {Opt_lazytime, "lazytime"}, {Opt_nolazytime, "nolazytime"}, {Opt_err, NULL}, }; /* Sysfs support for f2fs */ enum { GC_THREAD, /* struct f2fs_gc_thread */ SM_INFO, /* struct f2fs_sm_info */ DCC_INFO, /* struct discard_cmd_control */ NM_INFO, /* struct f2fs_nm_info */ F2FS_SBI, /* struct f2fs_sb_info */ #ifdef CONFIG_F2FS_FAULT_INJECTION FAULT_INFO_RATE, /* struct f2fs_fault_info */ FAULT_INFO_TYPE, /* struct f2fs_fault_info */ #endif }; struct f2fs_attr { struct attribute attr; ssize_t (*show)(struct f2fs_attr *, struct f2fs_sb_info *, char *); ssize_t (*store)(struct f2fs_attr *, struct f2fs_sb_info *, const char *, size_t); int struct_type; int offset; }; static unsigned char *__struct_ptr(struct f2fs_sb_info *sbi, int struct_type) { if (struct_type == GC_THREAD) return (unsigned char *)sbi->gc_thread; else if (struct_type == SM_INFO) return (unsigned char *)SM_I(sbi); else if (struct_type == DCC_INFO) return (unsigned char *)SM_I(sbi)->dcc_info; else if (struct_type == NM_INFO) return (unsigned char *)NM_I(sbi); else if (struct_type == F2FS_SBI) return (unsigned char *)sbi; #ifdef CONFIG_F2FS_FAULT_INJECTION else if (struct_type == FAULT_INFO_RATE || struct_type == FAULT_INFO_TYPE) return (unsigned char *)&sbi->fault_info; #endif return NULL; } static ssize_t lifetime_write_kbytes_show(struct f2fs_attr *a, struct f2fs_sb_info *sbi, char *buf) { struct super_block *sb = sbi->sb; if (!sb->s_bdev->bd_part) return snprintf(buf, PAGE_SIZE, "0\n"); return snprintf(buf, PAGE_SIZE, "%llu\n", (unsigned long long)(sbi->kbytes_written + BD_PART_WRITTEN(sbi))); } static ssize_t f2fs_sbi_show(struct f2fs_attr *a, struct f2fs_sb_info *sbi, char *buf) { unsigned char *ptr = NULL; unsigned int *ui; ptr = __struct_ptr(sbi, a->struct_type); if (!ptr) return -EINVAL; ui = (unsigned int *)(ptr + a->offset); return snprintf(buf, PAGE_SIZE, "%u\n", *ui); } static ssize_t f2fs_sbi_store(struct f2fs_attr *a, struct f2fs_sb_info *sbi, const char *buf, size_t count) { unsigned char *ptr; unsigned long t; unsigned int *ui; ssize_t ret; ptr = __struct_ptr(sbi, a->struct_type); if (!ptr) return -EINVAL; ui = (unsigned int *)(ptr + a->offset); ret = kstrtoul(skip_spaces(buf), 0, &t); if (ret < 0) return ret; #ifdef CONFIG_F2FS_FAULT_INJECTION if (a->struct_type == FAULT_INFO_TYPE && t >= (1 << FAULT_MAX)) return -EINVAL; #endif *ui = t; return count; } static ssize_t f2fs_attr_show(struct kobject *kobj, struct attribute *attr, char *buf) { struct f2fs_sb_info *sbi = container_of(kobj, struct f2fs_sb_info, s_kobj); struct f2fs_attr *a = container_of(attr, struct f2fs_attr, attr); return a->show ? a->show(a, sbi, buf) : 0; } static ssize_t f2fs_attr_store(struct kobject *kobj, struct attribute *attr, const char *buf, size_t len) { struct f2fs_sb_info *sbi = container_of(kobj, struct f2fs_sb_info, s_kobj); struct f2fs_attr *a = container_of(attr, struct f2fs_attr, attr); return a->store ? a->store(a, sbi, buf, len) : 0; } static void f2fs_sb_release(struct kobject *kobj) { struct f2fs_sb_info *sbi = container_of(kobj, struct f2fs_sb_info, s_kobj); complete(&sbi->s_kobj_unregister); } #define F2FS_ATTR_OFFSET(_struct_type, _name, _mode, _show, _store, _offset) \ static struct f2fs_attr f2fs_attr_##_name = { \ .attr = {.name = __stringify(_name), .mode = _mode }, \ .show = _show, \ .store = _store, \ .struct_type = _struct_type, \ .offset = _offset \ } #define F2FS_RW_ATTR(struct_type, struct_name, name, elname) \ F2FS_ATTR_OFFSET(struct_type, name, 0644, \ f2fs_sbi_show, f2fs_sbi_store, \ offsetof(struct struct_name, elname)) #define F2FS_GENERAL_RO_ATTR(name) \ static struct f2fs_attr f2fs_attr_##name = __ATTR(name, 0444, name##_show, NULL) F2FS_RW_ATTR(GC_THREAD, f2fs_gc_kthread, gc_min_sleep_time, min_sleep_time); F2FS_RW_ATTR(GC_THREAD, f2fs_gc_kthread, gc_max_sleep_time, max_sleep_time); F2FS_RW_ATTR(GC_THREAD, f2fs_gc_kthread, gc_no_gc_sleep_time, no_gc_sleep_time); F2FS_RW_ATTR(GC_THREAD, f2fs_gc_kthread, gc_idle, gc_idle); F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, reclaim_segments, rec_prefree_segments); F2FS_RW_ATTR(DCC_INFO, discard_cmd_control, max_small_discards, max_discards); F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, batched_trim_sections, trim_sections); F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, ipu_policy, ipu_policy); F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, min_ipu_util, min_ipu_util); F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, min_fsync_blocks, min_fsync_blocks); F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, min_hot_blocks, min_hot_blocks); F2FS_RW_ATTR(NM_INFO, f2fs_nm_info, ram_thresh, ram_thresh); F2FS_RW_ATTR(NM_INFO, f2fs_nm_info, ra_nid_pages, ra_nid_pages); F2FS_RW_ATTR(NM_INFO, f2fs_nm_info, dirty_nats_ratio, dirty_nats_ratio); F2FS_RW_ATTR(F2FS_SBI, f2fs_sb_info, max_victim_search, max_victim_search); F2FS_RW_ATTR(F2FS_SBI, f2fs_sb_info, dir_level, dir_level); F2FS_RW_ATTR(F2FS_SBI, f2fs_sb_info, cp_interval, interval_time[CP_TIME]); F2FS_RW_ATTR(F2FS_SBI, f2fs_sb_info, idle_interval, interval_time[REQ_TIME]); #ifdef CONFIG_F2FS_FAULT_INJECTION F2FS_RW_ATTR(FAULT_INFO_RATE, f2fs_fault_info, inject_rate, inject_rate); F2FS_RW_ATTR(FAULT_INFO_TYPE, f2fs_fault_info, inject_type, inject_type); #endif F2FS_GENERAL_RO_ATTR(lifetime_write_kbytes); #define ATTR_LIST(name) (&f2fs_attr_##name.attr) static struct attribute *f2fs_attrs[] = { ATTR_LIST(gc_min_sleep_time), ATTR_LIST(gc_max_sleep_time), ATTR_LIST(gc_no_gc_sleep_time), ATTR_LIST(gc_idle), ATTR_LIST(reclaim_segments), ATTR_LIST(max_small_discards), ATTR_LIST(batched_trim_sections), ATTR_LIST(ipu_policy), ATTR_LIST(min_ipu_util), ATTR_LIST(min_fsync_blocks), ATTR_LIST(min_hot_blocks), ATTR_LIST(max_victim_search), ATTR_LIST(dir_level), ATTR_LIST(ram_thresh), ATTR_LIST(ra_nid_pages), ATTR_LIST(dirty_nats_ratio), ATTR_LIST(cp_interval), ATTR_LIST(idle_interval), #ifdef CONFIG_F2FS_FAULT_INJECTION ATTR_LIST(inject_rate), ATTR_LIST(inject_type), #endif ATTR_LIST(lifetime_write_kbytes), NULL, }; static const struct sysfs_ops f2fs_attr_ops = { .show = f2fs_attr_show, .store = f2fs_attr_store, }; static struct kobj_type f2fs_ktype = { .default_attrs = f2fs_attrs, .sysfs_ops = &f2fs_attr_ops, .release = f2fs_sb_release, }; void f2fs_msg(struct super_block *sb, const char *level, const char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; printk("%sF2FS-fs (%s): %pV\n", level, sb->s_id, &vaf); va_end(args); } static void init_once(void *foo) { struct f2fs_inode_info *fi = (struct f2fs_inode_info *) foo; inode_init_once(&fi->vfs_inode); } static int parse_options(struct super_block *sb, char *options) { struct f2fs_sb_info *sbi = F2FS_SB(sb); struct request_queue *q; substring_t args[MAX_OPT_ARGS]; char *p, *name; int arg = 0; if (!options) return 0; 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, f2fs_tokens, args); switch (token) { case Opt_gc_background: name = match_strdup(&args[0]); if (!name) return -ENOMEM; if (strlen(name) == 2 && !strncmp(name, "on", 2)) { set_opt(sbi, BG_GC); clear_opt(sbi, FORCE_FG_GC); } else if (strlen(name) == 3 && !strncmp(name, "off", 3)) { clear_opt(sbi, BG_GC); clear_opt(sbi, FORCE_FG_GC); } else if (strlen(name) == 4 && !strncmp(name, "sync", 4)) { set_opt(sbi, BG_GC); set_opt(sbi, FORCE_FG_GC); } else { kfree(name); return -EINVAL; } kfree(name); break; case Opt_disable_roll_forward: set_opt(sbi, DISABLE_ROLL_FORWARD); break; case Opt_norecovery: /* this option mounts f2fs with ro */ set_opt(sbi, DISABLE_ROLL_FORWARD); if (!f2fs_readonly(sb)) return -EINVAL; break; case Opt_discard: q = bdev_get_queue(sb->s_bdev); if (blk_queue_discard(q)) { set_opt(sbi, DISCARD); } else if (!f2fs_sb_mounted_blkzoned(sb)) { f2fs_msg(sb, KERN_WARNING, "mounting with \"discard\" option, but " "the device does not support discard"); } break; case Opt_nodiscard: if (f2fs_sb_mounted_blkzoned(sb)) { f2fs_msg(sb, KERN_WARNING, "discard is required for zoned block devices"); return -EINVAL; } clear_opt(sbi, DISCARD); break; case Opt_noheap: set_opt(sbi, NOHEAP); break; case Opt_heap: clear_opt(sbi, NOHEAP); break; #ifdef CONFIG_F2FS_FS_XATTR case Opt_user_xattr: set_opt(sbi, XATTR_USER); break; case Opt_nouser_xattr: clear_opt(sbi, XATTR_USER); break; case Opt_inline_xattr: set_opt(sbi, INLINE_XATTR); break; case Opt_noinline_xattr: clear_opt(sbi, INLINE_XATTR); break; #else case Opt_user_xattr: f2fs_msg(sb, KERN_INFO, "user_xattr options not supported"); break; case Opt_nouser_xattr: f2fs_msg(sb, KERN_INFO, "nouser_xattr options not supported"); break; case Opt_inline_xattr: f2fs_msg(sb, KERN_INFO, "inline_xattr options not supported"); break; case Opt_noinline_xattr: f2fs_msg(sb, KERN_INFO, "noinline_xattr options not supported"); break; #endif #ifdef CONFIG_F2FS_FS_POSIX_ACL case Opt_acl: set_opt(sbi, POSIX_ACL); break; case Opt_noacl: clear_opt(sbi, POSIX_ACL); break; #else case Opt_acl: f2fs_msg(sb, KERN_INFO, "acl options not supported"); break; case Opt_noacl: f2fs_msg(sb, KERN_INFO, "noacl options not supported"); break; #endif case Opt_active_logs: if (args->from && match_int(args, &arg)) return -EINVAL; if (arg != 2 && arg != 4 && arg != NR_CURSEG_TYPE) return -EINVAL; sbi->active_logs = arg; break; case Opt_disable_ext_identify: set_opt(sbi, DISABLE_EXT_IDENTIFY); break; case Opt_inline_data: set_opt(sbi, INLINE_DATA); break; case Opt_inline_dentry: set_opt(sbi, INLINE_DENTRY); break; case Opt_noinline_dentry: clear_opt(sbi, INLINE_DENTRY); break; case Opt_flush_merge: set_opt(sbi, FLUSH_MERGE); break; case Opt_noflush_merge: clear_opt(sbi, FLUSH_MERGE); break; case Opt_nobarrier: set_opt(sbi, NOBARRIER); break; case Opt_fastboot: set_opt(sbi, FASTBOOT); break; case Opt_extent_cache: set_opt(sbi, EXTENT_CACHE); break; case Opt_noextent_cache: clear_opt(sbi, EXTENT_CACHE); break; case Opt_noinline_data: clear_opt(sbi, INLINE_DATA); break; case Opt_data_flush: set_opt(sbi, DATA_FLUSH); break; case Opt_mode: name = match_strdup(&args[0]); if (!name) return -ENOMEM; if (strlen(name) == 8 && !strncmp(name, "adaptive", 8)) { if (f2fs_sb_mounted_blkzoned(sb)) { f2fs_msg(sb, KERN_WARNING, "adaptive mode is not allowed with " "zoned block device feature"); kfree(name); return -EINVAL; } set_opt_mode(sbi, F2FS_MOUNT_ADAPTIVE); } else if (strlen(name) == 3 && !strncmp(name, "lfs", 3)) { set_opt_mode(sbi, F2FS_MOUNT_LFS); } else { kfree(name); return -EINVAL; } kfree(name); break; case Opt_io_size_bits: if (args->from && match_int(args, &arg)) return -EINVAL; if (arg > __ilog2_u32(BIO_MAX_PAGES)) { f2fs_msg(sb, KERN_WARNING, "Not support %d, larger than %d", 1 << arg, BIO_MAX_PAGES); return -EINVAL; } sbi->write_io_size_bits = arg; break; case Opt_fault_injection: if (args->from && match_int(args, &arg)) return -EINVAL; #ifdef CONFIG_F2FS_FAULT_INJECTION f2fs_build_fault_attr(sbi, arg); set_opt(sbi, FAULT_INJECTION); #else f2fs_msg(sb, KERN_INFO, "FAULT_INJECTION was not selected"); #endif break; case Opt_lazytime: sb->s_flags |= MS_LAZYTIME; break; case Opt_nolazytime: sb->s_flags &= ~MS_LAZYTIME; break; default: f2fs_msg(sb, KERN_ERR, "Unrecognized mount option \"%s\" or missing value", p); return -EINVAL; } } if (F2FS_IO_SIZE_BITS(sbi) && !test_opt(sbi, LFS)) { f2fs_msg(sb, KERN_ERR, "Should set mode=lfs with %uKB-sized IO", F2FS_IO_SIZE_KB(sbi)); return -EINVAL; } return 0; } static struct inode *f2fs_alloc_inode(struct super_block *sb) { struct f2fs_inode_info *fi; fi = kmem_cache_alloc(f2fs_inode_cachep, GFP_F2FS_ZERO); if (!fi) return NULL; init_once((void *) fi); /* Initialize f2fs-specific inode info */ fi->vfs_inode.i_version = 1; atomic_set(&fi->dirty_pages, 0); fi->i_current_depth = 1; fi->i_advise = 0; init_rwsem(&fi->i_sem); INIT_LIST_HEAD(&fi->dirty_list); INIT_LIST_HEAD(&fi->gdirty_list); INIT_LIST_HEAD(&fi->inmem_pages); mutex_init(&fi->inmem_lock); init_rwsem(&fi->dio_rwsem[READ]); init_rwsem(&fi->dio_rwsem[WRITE]); /* Will be used by directory only */ fi->i_dir_level = F2FS_SB(sb)->dir_level; return &fi->vfs_inode; } static int f2fs_drop_inode(struct inode *inode) { int ret; /* * This is to avoid a deadlock condition like below. * writeback_single_inode(inode) * - f2fs_write_data_page * - f2fs_gc -> iput -> evict * - inode_wait_for_writeback(inode) */ if ((!inode_unhashed(inode) && inode->i_state & I_SYNC)) { if (!inode->i_nlink && !is_bad_inode(inode)) { /* to avoid evict_inode call simultaneously */ atomic_inc(&inode->i_count); spin_unlock(&inode->i_lock); /* some remained atomic pages should discarded */ if (f2fs_is_atomic_file(inode)) drop_inmem_pages(inode); /* should remain fi->extent_tree for writepage */ f2fs_destroy_extent_node(inode); sb_start_intwrite(inode->i_sb); f2fs_i_size_write(inode, 0); if (F2FS_HAS_BLOCKS(inode)) f2fs_truncate(inode); sb_end_intwrite(inode->i_sb); fscrypt_put_encryption_info(inode, NULL); spin_lock(&inode->i_lock); atomic_dec(&inode->i_count); } trace_f2fs_drop_inode(inode, 0); return 0; } ret = generic_drop_inode(inode); trace_f2fs_drop_inode(inode, ret); return ret; } int f2fs_inode_dirtied(struct inode *inode, bool sync) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); int ret = 0; spin_lock(&sbi->inode_lock[DIRTY_META]); if (is_inode_flag_set(inode, FI_DIRTY_INODE)) { ret = 1; } else { set_inode_flag(inode, FI_DIRTY_INODE); stat_inc_dirty_inode(sbi, DIRTY_META); } if (sync && list_empty(&F2FS_I(inode)->gdirty_list)) { list_add_tail(&F2FS_I(inode)->gdirty_list, &sbi->inode_list[DIRTY_META]); inc_page_count(sbi, F2FS_DIRTY_IMETA); } spin_unlock(&sbi->inode_lock[DIRTY_META]); return ret; } void f2fs_inode_synced(struct inode *inode) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); spin_lock(&sbi->inode_lock[DIRTY_META]); if (!is_inode_flag_set(inode, FI_DIRTY_INODE)) { spin_unlock(&sbi->inode_lock[DIRTY_META]); return; } if (!list_empty(&F2FS_I(inode)->gdirty_list)) { list_del_init(&F2FS_I(inode)->gdirty_list); dec_page_count(sbi, F2FS_DIRTY_IMETA); } clear_inode_flag(inode, FI_DIRTY_INODE); clear_inode_flag(inode, FI_AUTO_RECOVER); stat_dec_dirty_inode(F2FS_I_SB(inode), DIRTY_META); spin_unlock(&sbi->inode_lock[DIRTY_META]); } /* * f2fs_dirty_inode() is called from __mark_inode_dirty() * * We should call set_dirty_inode to write the dirty inode through write_inode. */ static void f2fs_dirty_inode(struct inode *inode, int flags) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); if (inode->i_ino == F2FS_NODE_INO(sbi) || inode->i_ino == F2FS_META_INO(sbi)) return; if (flags == I_DIRTY_TIME) return; if (is_inode_flag_set(inode, FI_AUTO_RECOVER)) clear_inode_flag(inode, FI_AUTO_RECOVER); f2fs_inode_dirtied(inode, false); } static void f2fs_i_callback(struct rcu_head *head) { struct inode *inode = container_of(head, struct inode, i_rcu); kmem_cache_free(f2fs_inode_cachep, F2FS_I(inode)); } static void f2fs_destroy_inode(struct inode *inode) { call_rcu(&inode->i_rcu, f2fs_i_callback); } static void destroy_percpu_info(struct f2fs_sb_info *sbi) { percpu_counter_destroy(&sbi->alloc_valid_block_count); percpu_counter_destroy(&sbi->total_valid_inode_count); } static void destroy_device_list(struct f2fs_sb_info *sbi) { int i; for (i = 0; i < sbi->s_ndevs; i++) { blkdev_put(FDEV(i).bdev, FMODE_EXCL); #ifdef CONFIG_BLK_DEV_ZONED kfree(FDEV(i).blkz_type); #endif } kfree(sbi->devs); } static void f2fs_put_super(struct super_block *sb) { struct f2fs_sb_info *sbi = F2FS_SB(sb); if (sbi->s_proc) { remove_proc_entry("segment_info", sbi->s_proc); remove_proc_entry("segment_bits", sbi->s_proc); remove_proc_entry(sb->s_id, f2fs_proc_root); } kobject_del(&sbi->s_kobj); stop_gc_thread(sbi); /* prevent remaining shrinker jobs */ mutex_lock(&sbi->umount_mutex); /* * We don't need to do checkpoint when superblock is clean. * But, the previous checkpoint was not done by umount, it needs to do * clean checkpoint again. */ if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) || !is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) { struct cp_control cpc = { .reason = CP_UMOUNT, }; write_checkpoint(sbi, &cpc); } /* be sure to wait for any on-going discard commands */ f2fs_wait_discard_bios(sbi); if (!sbi->discard_blks) { struct cp_control cpc = { .reason = CP_UMOUNT | CP_TRIMMED, }; write_checkpoint(sbi, &cpc); } /* write_checkpoint can update stat informaion */ f2fs_destroy_stats(sbi); /* * normally superblock is clean, so we need to release this. * In addition, EIO will skip do checkpoint, we need this as well. */ release_ino_entry(sbi, true); f2fs_leave_shrinker(sbi); mutex_unlock(&sbi->umount_mutex); /* our cp_error case, we can wait for any writeback page */ f2fs_flush_merged_bios(sbi); iput(sbi->node_inode); iput(sbi->meta_inode); /* destroy f2fs internal modules */ destroy_node_manager(sbi); destroy_segment_manager(sbi); kfree(sbi->ckpt); kobject_put(&sbi->s_kobj); wait_for_completion(&sbi->s_kobj_unregister); sb->s_fs_info = NULL; if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); kfree(sbi->raw_super); destroy_device_list(sbi); mempool_destroy(sbi->write_io_dummy); destroy_percpu_info(sbi); kfree(sbi); } int f2fs_sync_fs(struct super_block *sb, int sync) { struct f2fs_sb_info *sbi = F2FS_SB(sb); int err = 0; trace_f2fs_sync_fs(sb, sync); if (sync) { struct cp_control cpc; cpc.reason = __get_cp_reason(sbi); mutex_lock(&sbi->gc_mutex); err = write_checkpoint(sbi, &cpc); mutex_unlock(&sbi->gc_mutex); } f2fs_trace_ios(NULL, 1); return err; } static int f2fs_freeze(struct super_block *sb) { if (f2fs_readonly(sb)) return 0; /* IO error happened before */ if (unlikely(f2fs_cp_error(F2FS_SB(sb)))) return -EIO; /* must be clean, since sync_filesystem() was already called */ if (is_sbi_flag_set(F2FS_SB(sb), SBI_IS_DIRTY)) return -EINVAL; return 0; } static int f2fs_unfreeze(struct super_block *sb) { return 0; } static int f2fs_statfs(struct dentry *dentry, struct kstatfs *buf) { struct super_block *sb = dentry->d_sb; struct f2fs_sb_info *sbi = F2FS_SB(sb); u64 id = huge_encode_dev(sb->s_bdev->bd_dev); block_t total_count, user_block_count, start_count, ovp_count; total_count = le64_to_cpu(sbi->raw_super->block_count); user_block_count = sbi->user_block_count; start_count = le32_to_cpu(sbi->raw_super->segment0_blkaddr); ovp_count = SM_I(sbi)->ovp_segments << sbi->log_blocks_per_seg; buf->f_type = F2FS_SUPER_MAGIC; buf->f_bsize = sbi->blocksize; buf->f_blocks = total_count - start_count; buf->f_bfree = user_block_count - valid_user_blocks(sbi) + ovp_count; buf->f_bavail = user_block_count - valid_user_blocks(sbi); buf->f_files = sbi->total_node_count - F2FS_RESERVED_NODE_NUM; buf->f_ffree = min(buf->f_files - valid_node_count(sbi), buf->f_bavail); buf->f_namelen = F2FS_NAME_LEN; buf->f_fsid.val[0] = (u32)id; buf->f_fsid.val[1] = (u32)(id >> 32); return 0; } static int f2fs_show_options(struct seq_file *seq, struct dentry *root) { struct f2fs_sb_info *sbi = F2FS_SB(root->d_sb); if (!f2fs_readonly(sbi->sb) && test_opt(sbi, BG_GC)) { if (test_opt(sbi, FORCE_FG_GC)) seq_printf(seq, ",background_gc=%s", "sync"); else seq_printf(seq, ",background_gc=%s", "on"); } else { seq_printf(seq, ",background_gc=%s", "off"); } if (test_opt(sbi, DISABLE_ROLL_FORWARD)) seq_puts(seq, ",disable_roll_forward"); if (test_opt(sbi, DISCARD)) seq_puts(seq, ",discard"); if (test_opt(sbi, NOHEAP)) seq_puts(seq, ",no_heap"); else seq_puts(seq, ",heap"); #ifdef CONFIG_F2FS_FS_XATTR if (test_opt(sbi, XATTR_USER)) seq_puts(seq, ",user_xattr"); else seq_puts(seq, ",nouser_xattr"); if (test_opt(sbi, INLINE_XATTR)) seq_puts(seq, ",inline_xattr"); else seq_puts(seq, ",noinline_xattr"); #endif #ifdef CONFIG_F2FS_FS_POSIX_ACL if (test_opt(sbi, POSIX_ACL)) seq_puts(seq, ",acl"); else seq_puts(seq, ",noacl"); #endif if (test_opt(sbi, DISABLE_EXT_IDENTIFY)) seq_puts(seq, ",disable_ext_identify"); if (test_opt(sbi, INLINE_DATA)) seq_puts(seq, ",inline_data"); else seq_puts(seq, ",noinline_data"); if (test_opt(sbi, INLINE_DENTRY)) seq_puts(seq, ",inline_dentry"); else seq_puts(seq, ",noinline_dentry"); if (!f2fs_readonly(sbi->sb) && test_opt(sbi, FLUSH_MERGE)) seq_puts(seq, ",flush_merge"); if (test_opt(sbi, NOBARRIER)) seq_puts(seq, ",nobarrier"); if (test_opt(sbi, FASTBOOT)) seq_puts(seq, ",fastboot"); if (test_opt(sbi, EXTENT_CACHE)) seq_puts(seq, ",extent_cache"); else seq_puts(seq, ",noextent_cache"); if (test_opt(sbi, DATA_FLUSH)) seq_puts(seq, ",data_flush"); seq_puts(seq, ",mode="); if (test_opt(sbi, ADAPTIVE)) seq_puts(seq, "adaptive"); else if (test_opt(sbi, LFS)) seq_puts(seq, "lfs"); seq_printf(seq, ",active_logs=%u", sbi->active_logs); if (F2FS_IO_SIZE_BITS(sbi)) seq_printf(seq, ",io_size=%uKB", F2FS_IO_SIZE_KB(sbi)); #ifdef CONFIG_F2FS_FAULT_INJECTION if (test_opt(sbi, FAULT_INJECTION)) seq_puts(seq, ",fault_injection"); #endif return 0; } static int segment_info_seq_show(struct seq_file *seq, void *offset) { struct super_block *sb = seq->private; struct f2fs_sb_info *sbi = F2FS_SB(sb); unsigned int total_segs = le32_to_cpu(sbi->raw_super->segment_count_main); int i; seq_puts(seq, "format: segment_type|valid_blocks\n" "segment_type(0:HD, 1:WD, 2:CD, 3:HN, 4:WN, 5:CN)\n"); for (i = 0; i < total_segs; i++) { struct seg_entry *se = get_seg_entry(sbi, i); if ((i % 10) == 0) seq_printf(seq, "%-10d", i); seq_printf(seq, "%d|%-3u", se->type, get_valid_blocks(sbi, i, false)); if ((i % 10) == 9 || i == (total_segs - 1)) seq_putc(seq, '\n'); else seq_putc(seq, ' '); } return 0; } static int segment_bits_seq_show(struct seq_file *seq, void *offset) { struct super_block *sb = seq->private; struct f2fs_sb_info *sbi = F2FS_SB(sb); unsigned int total_segs = le32_to_cpu(sbi->raw_super->segment_count_main); int i, j; seq_puts(seq, "format: segment_type|valid_blocks|bitmaps\n" "segment_type(0:HD, 1:WD, 2:CD, 3:HN, 4:WN, 5:CN)\n"); for (i = 0; i < total_segs; i++) { struct seg_entry *se = get_seg_entry(sbi, i); seq_printf(seq, "%-10d", i); seq_printf(seq, "%d|%-3u|", se->type, get_valid_blocks(sbi, i, false)); for (j = 0; j < SIT_VBLOCK_MAP_SIZE; j++) seq_printf(seq, " %.2x", se->cur_valid_map[j]); seq_putc(seq, '\n'); } return 0; } #define F2FS_PROC_FILE_DEF(_name) \ static int _name##_open_fs(struct inode *inode, struct file *file) \ { \ return single_open(file, _name##_seq_show, PDE_DATA(inode)); \ } \ \ static const struct file_operations f2fs_seq_##_name##_fops = { \ .open = _name##_open_fs, \ .read = seq_read, \ .llseek = seq_lseek, \ .release = single_release, \ }; F2FS_PROC_FILE_DEF(segment_info); F2FS_PROC_FILE_DEF(segment_bits); static void default_options(struct f2fs_sb_info *sbi) { /* init some FS parameters */ sbi->active_logs = NR_CURSEG_TYPE; set_opt(sbi, BG_GC); set_opt(sbi, INLINE_XATTR); set_opt(sbi, INLINE_DATA); set_opt(sbi, INLINE_DENTRY); set_opt(sbi, EXTENT_CACHE); set_opt(sbi, NOHEAP); sbi->sb->s_flags |= MS_LAZYTIME; set_opt(sbi, FLUSH_MERGE); if (f2fs_sb_mounted_blkzoned(sbi->sb)) { set_opt_mode(sbi, F2FS_MOUNT_LFS); set_opt(sbi, DISCARD); } else { set_opt_mode(sbi, F2FS_MOUNT_ADAPTIVE); } #ifdef CONFIG_F2FS_FS_XATTR set_opt(sbi, XATTR_USER); #endif #ifdef CONFIG_F2FS_FS_POSIX_ACL set_opt(sbi, POSIX_ACL); #endif #ifdef CONFIG_F2FS_FAULT_INJECTION f2fs_build_fault_attr(sbi, 0); #endif } static int f2fs_remount(struct super_block *sb, int *flags, char *data) { struct f2fs_sb_info *sbi = F2FS_SB(sb); struct f2fs_mount_info org_mount_opt; int err, active_logs; bool need_restart_gc = false; bool need_stop_gc = false; bool no_extent_cache = !test_opt(sbi, EXTENT_CACHE); #ifdef CONFIG_F2FS_FAULT_INJECTION struct f2fs_fault_info ffi = sbi->fault_info; #endif /* * Save the old mount options in case we * need to restore them. */ org_mount_opt = sbi->mount_opt; active_logs = sbi->active_logs; /* recover superblocks we couldn't write due to previous RO mount */ if (!(*flags & MS_RDONLY) && is_sbi_flag_set(sbi, SBI_NEED_SB_WRITE)) { err = f2fs_commit_super(sbi, false); f2fs_msg(sb, KERN_INFO, "Try to recover all the superblocks, ret: %d", err); if (!err) clear_sbi_flag(sbi, SBI_NEED_SB_WRITE); } sbi->mount_opt.opt = 0; default_options(sbi); /* parse mount options */ err = parse_options(sb, data); if (err) goto restore_opts; /* * Previous and new state of filesystem is RO, * so skip checking GC and FLUSH_MERGE conditions. */ if (f2fs_readonly(sb) && (*flags & MS_RDONLY)) goto skip; /* disallow enable/disable extent_cache dynamically */ if (no_extent_cache == !!test_opt(sbi, EXTENT_CACHE)) { err = -EINVAL; f2fs_msg(sbi->sb, KERN_WARNING, "switch extent_cache option is not allowed"); goto restore_opts; } /* * We stop the GC thread if FS is mounted as RO * or if background_gc = off is passed in mount * option. Also sync the filesystem. */ if ((*flags & MS_RDONLY) || !test_opt(sbi, BG_GC)) { if (sbi->gc_thread) { stop_gc_thread(sbi); need_restart_gc = true; } } else if (!sbi->gc_thread) { err = start_gc_thread(sbi); if (err) goto restore_opts; need_stop_gc = true; } if (*flags & MS_RDONLY) { writeback_inodes_sb(sb, WB_REASON_SYNC); sync_inodes_sb(sb); set_sbi_flag(sbi, SBI_IS_DIRTY); set_sbi_flag(sbi, SBI_IS_CLOSE); f2fs_sync_fs(sb, 1); clear_sbi_flag(sbi, SBI_IS_CLOSE); } /* * We stop issue flush thread if FS is mounted as RO * or if flush_merge is not passed in mount option. */ if ((*flags & MS_RDONLY) || !test_opt(sbi, FLUSH_MERGE)) { clear_opt(sbi, FLUSH_MERGE); destroy_flush_cmd_control(sbi, false); } else { err = create_flush_cmd_control(sbi); if (err) goto restore_gc; } skip: /* Update the POSIXACL Flag */ sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | (test_opt(sbi, POSIX_ACL) ? MS_POSIXACL : 0); return 0; restore_gc: if (need_restart_gc) { if (start_gc_thread(sbi)) f2fs_msg(sbi->sb, KERN_WARNING, "background gc thread has stopped"); } else if (need_stop_gc) { stop_gc_thread(sbi); } restore_opts: sbi->mount_opt = org_mount_opt; sbi->active_logs = active_logs; #ifdef CONFIG_F2FS_FAULT_INJECTION sbi->fault_info = ffi; #endif return err; } static struct super_operations f2fs_sops = { .alloc_inode = f2fs_alloc_inode, .drop_inode = f2fs_drop_inode, .destroy_inode = f2fs_destroy_inode, .write_inode = f2fs_write_inode, .dirty_inode = f2fs_dirty_inode, .show_options = f2fs_show_options, .evict_inode = f2fs_evict_inode, .put_super = f2fs_put_super, .sync_fs = f2fs_sync_fs, .freeze_fs = f2fs_freeze, .unfreeze_fs = f2fs_unfreeze, .statfs = f2fs_statfs, .remount_fs = f2fs_remount, }; #ifdef CONFIG_F2FS_FS_ENCRYPTION static int f2fs_get_context(struct inode *inode, void *ctx, size_t len) { return f2fs_getxattr(inode, F2FS_XATTR_INDEX_ENCRYPTION, F2FS_XATTR_NAME_ENCRYPTION_CONTEXT, ctx, len, NULL); } static int f2fs_set_context(struct inode *inode, const void *ctx, size_t len, void *fs_data) { return f2fs_setxattr(inode, F2FS_XATTR_INDEX_ENCRYPTION, F2FS_XATTR_NAME_ENCRYPTION_CONTEXT, ctx, len, fs_data, XATTR_CREATE); } static unsigned f2fs_max_namelen(struct inode *inode) { return S_ISLNK(inode->i_mode) ? inode->i_sb->s_blocksize : F2FS_NAME_LEN; } static const struct fscrypt_operations f2fs_cryptops = { .key_prefix = "f2fs:", .get_context = f2fs_get_context, .set_context = f2fs_set_context, .is_encrypted = f2fs_encrypted_inode, .empty_dir = f2fs_empty_dir, .max_namelen = f2fs_max_namelen, }; #else static const struct fscrypt_operations f2fs_cryptops = { .is_encrypted = f2fs_encrypted_inode, }; #endif static struct inode *f2fs_nfs_get_inode(struct super_block *sb, u64 ino, u32 generation) { struct f2fs_sb_info *sbi = F2FS_SB(sb); struct inode *inode; if (check_nid_range(sbi, ino)) return ERR_PTR(-ESTALE); /* * f2fs_iget isn't quite right if the inode is currently unallocated! * However f2fs_iget currently does appropriate checks to handle stale * inodes so everything is OK. */ inode = f2fs_iget(sb, ino); if (IS_ERR(inode)) return ERR_CAST(inode); if (unlikely(generation && inode->i_generation != generation)) { /* we didn't find the right inode.. */ iput(inode); return ERR_PTR(-ESTALE); } return inode; } static struct dentry *f2fs_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, f2fs_nfs_get_inode); } static struct dentry *f2fs_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, f2fs_nfs_get_inode); } static const struct export_operations f2fs_export_ops = { .fh_to_dentry = f2fs_fh_to_dentry, .fh_to_parent = f2fs_fh_to_parent, .get_parent = f2fs_get_parent, }; static loff_t max_file_blocks(void) { loff_t result = (DEF_ADDRS_PER_INODE - F2FS_INLINE_XATTR_ADDRS); loff_t leaf_count = ADDRS_PER_BLOCK; /* two direct node blocks */ result += (leaf_count * 2); /* two indirect node blocks */ leaf_count *= NIDS_PER_BLOCK; result += (leaf_count * 2); /* one double indirect node block */ leaf_count *= NIDS_PER_BLOCK; result += leaf_count; return result; } static int __f2fs_commit_super(struct buffer_head *bh, struct f2fs_super_block *super) { lock_buffer(bh); if (super) memcpy(bh->b_data + F2FS_SUPER_OFFSET, super, sizeof(*super)); set_buffer_uptodate(bh); set_buffer_dirty(bh); unlock_buffer(bh); /* it's rare case, we can do fua all the time */ return __sync_dirty_buffer(bh, REQ_SYNC | REQ_PREFLUSH | REQ_FUA); } static inline bool sanity_check_area_boundary(struct f2fs_sb_info *sbi, struct buffer_head *bh) { struct f2fs_super_block *raw_super = (struct f2fs_super_block *) (bh->b_data + F2FS_SUPER_OFFSET); struct super_block *sb = sbi->sb; u32 segment0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr); u32 cp_blkaddr = le32_to_cpu(raw_super->cp_blkaddr); u32 sit_blkaddr = le32_to_cpu(raw_super->sit_blkaddr); u32 nat_blkaddr = le32_to_cpu(raw_super->nat_blkaddr); u32 ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr); u32 main_blkaddr = le32_to_cpu(raw_super->main_blkaddr); u32 segment_count_ckpt = le32_to_cpu(raw_super->segment_count_ckpt); u32 segment_count_sit = le32_to_cpu(raw_super->segment_count_sit); u32 segment_count_nat = le32_to_cpu(raw_super->segment_count_nat); u32 segment_count_ssa = le32_to_cpu(raw_super->segment_count_ssa); u32 segment_count_main = le32_to_cpu(raw_super->segment_count_main); u32 segment_count = le32_to_cpu(raw_super->segment_count); u32 log_blocks_per_seg = le32_to_cpu(raw_super->log_blocks_per_seg); u64 main_end_blkaddr = main_blkaddr + (segment_count_main << log_blocks_per_seg); u64 seg_end_blkaddr = segment0_blkaddr + (segment_count << log_blocks_per_seg); if (segment0_blkaddr != cp_blkaddr) { f2fs_msg(sb, KERN_INFO, "Mismatch start address, segment0(%u) cp_blkaddr(%u)", segment0_blkaddr, cp_blkaddr); return true; } if (cp_blkaddr + (segment_count_ckpt << log_blocks_per_seg) != sit_blkaddr) { f2fs_msg(sb, KERN_INFO, "Wrong CP boundary, start(%u) end(%u) blocks(%u)", cp_blkaddr, sit_blkaddr, segment_count_ckpt << log_blocks_per_seg); return true; } if (sit_blkaddr + (segment_count_sit << log_blocks_per_seg) != nat_blkaddr) { f2fs_msg(sb, KERN_INFO, "Wrong SIT boundary, start(%u) end(%u) blocks(%u)", sit_blkaddr, nat_blkaddr, segment_count_sit << log_blocks_per_seg); return true; } if (nat_blkaddr + (segment_count_nat << log_blocks_per_seg) != ssa_blkaddr) { f2fs_msg(sb, KERN_INFO, "Wrong NAT boundary, start(%u) end(%u) blocks(%u)", nat_blkaddr, ssa_blkaddr, segment_count_nat << log_blocks_per_seg); return true; } if (ssa_blkaddr + (segment_count_ssa << log_blocks_per_seg) != main_blkaddr) { f2fs_msg(sb, KERN_INFO, "Wrong SSA boundary, start(%u) end(%u) blocks(%u)", ssa_blkaddr, main_blkaddr, segment_count_ssa << log_blocks_per_seg); return true; } if (main_end_blkaddr > seg_end_blkaddr) { f2fs_msg(sb, KERN_INFO, "Wrong MAIN_AREA boundary, start(%u) end(%u) block(%u)", main_blkaddr, segment0_blkaddr + (segment_count << log_blocks_per_seg), segment_count_main << log_blocks_per_seg); return true; } else if (main_end_blkaddr < seg_end_blkaddr) { int err = 0; char *res; /* fix in-memory information all the time */ raw_super->segment_count = cpu_to_le32((main_end_blkaddr - segment0_blkaddr) >> log_blocks_per_seg); if (f2fs_readonly(sb) || bdev_read_only(sb->s_bdev)) { set_sbi_flag(sbi, SBI_NEED_SB_WRITE); res = "internally"; } else { err = __f2fs_commit_super(bh, NULL); res = err ? "failed" : "done"; } f2fs_msg(sb, KERN_INFO, "Fix alignment : %s, start(%u) end(%u) block(%u)", res, main_blkaddr, segment0_blkaddr + (segment_count << log_blocks_per_seg), segment_count_main << log_blocks_per_seg); if (err) return true; } return false; } static int sanity_check_raw_super(struct f2fs_sb_info *sbi, struct buffer_head *bh) { struct f2fs_super_block *raw_super = (struct f2fs_super_block *) (bh->b_data + F2FS_SUPER_OFFSET); struct super_block *sb = sbi->sb; unsigned int blocksize; if (F2FS_SUPER_MAGIC != le32_to_cpu(raw_super->magic)) { f2fs_msg(sb, KERN_INFO, "Magic Mismatch, valid(0x%x) - read(0x%x)", F2FS_SUPER_MAGIC, le32_to_cpu(raw_super->magic)); return 1; } /* Currently, support only 4KB page cache size */ if (F2FS_BLKSIZE != PAGE_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid page_cache_size (%lu), supports only 4KB\n", PAGE_SIZE); return 1; } /* Currently, support only 4KB block size */ blocksize = 1 << le32_to_cpu(raw_super->log_blocksize); if (blocksize != F2FS_BLKSIZE) { f2fs_msg(sb, KERN_INFO, "Invalid blocksize (%u), supports only 4KB\n", blocksize); return 1; } /* check log blocks per segment */ if (le32_to_cpu(raw_super->log_blocks_per_seg) != 9) { f2fs_msg(sb, KERN_INFO, "Invalid log blocks per segment (%u)\n", le32_to_cpu(raw_super->log_blocks_per_seg)); return 1; } /* Currently, support 512/1024/2048/4096 bytes sector size */ if (le32_to_cpu(raw_super->log_sectorsize) > F2FS_MAX_LOG_SECTOR_SIZE || le32_to_cpu(raw_super->log_sectorsize) < F2FS_MIN_LOG_SECTOR_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid log sectorsize (%u)", le32_to_cpu(raw_super->log_sectorsize)); return 1; } if (le32_to_cpu(raw_super->log_sectors_per_block) + le32_to_cpu(raw_super->log_sectorsize) != F2FS_MAX_LOG_SECTOR_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid log sectors per block(%u) log sectorsize(%u)", le32_to_cpu(raw_super->log_sectors_per_block), le32_to_cpu(raw_super->log_sectorsize)); return 1; } /* check reserved ino info */ if (le32_to_cpu(raw_super->node_ino) != 1 || le32_to_cpu(raw_super->meta_ino) != 2 || le32_to_cpu(raw_super->root_ino) != 3) { f2fs_msg(sb, KERN_INFO, "Invalid Fs Meta Ino: node(%u) meta(%u) root(%u)", le32_to_cpu(raw_super->node_ino), le32_to_cpu(raw_super->meta_ino), le32_to_cpu(raw_super->root_ino)); return 1; } if (le32_to_cpu(raw_super->segment_count) > F2FS_MAX_SEGMENT) { f2fs_msg(sb, KERN_INFO, "Invalid segment count (%u)", le32_to_cpu(raw_super->segment_count)); return 1; } /* check CP/SIT/NAT/SSA/MAIN_AREA area boundary */ if (sanity_check_area_boundary(sbi, bh)) return 1; return 0; } int sanity_check_ckpt(struct f2fs_sb_info *sbi) { unsigned int total, fsmeta; struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi); struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); unsigned int ovp_segments, reserved_segments; unsigned int main_segs, blocks_per_seg; int i; total = le32_to_cpu(raw_super->segment_count); fsmeta = le32_to_cpu(raw_super->segment_count_ckpt); fsmeta += le32_to_cpu(raw_super->segment_count_sit); fsmeta += le32_to_cpu(raw_super->segment_count_nat); fsmeta += le32_to_cpu(ckpt->rsvd_segment_count); fsmeta += le32_to_cpu(raw_super->segment_count_ssa); if (unlikely(fsmeta >= total)) return 1; ovp_segments = le32_to_cpu(ckpt->overprov_segment_count); reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count); if (unlikely(fsmeta < F2FS_MIN_SEGMENTS || ovp_segments == 0 || reserved_segments == 0)) { f2fs_msg(sbi->sb, KERN_ERR, "Wrong layout: check mkfs.f2fs version"); return 1; } main_segs = le32_to_cpu(raw_super->segment_count_main); blocks_per_seg = sbi->blocks_per_seg; for (i = 0; i < NR_CURSEG_NODE_TYPE; i++) { if (le32_to_cpu(ckpt->cur_node_segno[i]) >= main_segs || le16_to_cpu(ckpt->cur_node_blkoff[i]) >= blocks_per_seg) return 1; } for (i = 0; i < NR_CURSEG_DATA_TYPE; i++) { if (le32_to_cpu(ckpt->cur_data_segno[i]) >= main_segs || le16_to_cpu(ckpt->cur_data_blkoff[i]) >= blocks_per_seg) return 1; } if (unlikely(f2fs_cp_error(sbi))) { f2fs_msg(sbi->sb, KERN_ERR, "A bug case: need to run fsck"); return 1; } return 0; } static void init_sb_info(struct f2fs_sb_info *sbi) { struct f2fs_super_block *raw_super = sbi->raw_super; int i; sbi->log_sectors_per_block = le32_to_cpu(raw_super->log_sectors_per_block); sbi->log_blocksize = le32_to_cpu(raw_super->log_blocksize); sbi->blocksize = 1 << sbi->log_blocksize; sbi->log_blocks_per_seg = le32_to_cpu(raw_super->log_blocks_per_seg); sbi->blocks_per_seg = 1 << sbi->log_blocks_per_seg; sbi->segs_per_sec = le32_to_cpu(raw_super->segs_per_sec); sbi->secs_per_zone = le32_to_cpu(raw_super->secs_per_zone); sbi->total_sections = le32_to_cpu(raw_super->section_count); sbi->total_node_count = (le32_to_cpu(raw_super->segment_count_nat) / 2) * sbi->blocks_per_seg * NAT_ENTRY_PER_BLOCK; sbi->root_ino_num = le32_to_cpu(raw_super->root_ino); sbi->node_ino_num = le32_to_cpu(raw_super->node_ino); sbi->meta_ino_num = le32_to_cpu(raw_super->meta_ino); sbi->cur_victim_sec = NULL_SECNO; sbi->max_victim_search = DEF_MAX_VICTIM_SEARCH; sbi->dir_level = DEF_DIR_LEVEL; sbi->interval_time[CP_TIME] = DEF_CP_INTERVAL; sbi->interval_time[REQ_TIME] = DEF_IDLE_INTERVAL; clear_sbi_flag(sbi, SBI_NEED_FSCK); for (i = 0; i < NR_COUNT_TYPE; i++) atomic_set(&sbi->nr_pages[i], 0); atomic_set(&sbi->wb_sync_req, 0); INIT_LIST_HEAD(&sbi->s_list); mutex_init(&sbi->umount_mutex); mutex_init(&sbi->wio_mutex[NODE]); mutex_init(&sbi->wio_mutex[DATA]); spin_lock_init(&sbi->cp_lock); } static int init_percpu_info(struct f2fs_sb_info *sbi) { int err; err = percpu_counter_init(&sbi->alloc_valid_block_count, 0, GFP_KERNEL); if (err) return err; return percpu_counter_init(&sbi->total_valid_inode_count, 0, GFP_KERNEL); } #ifdef CONFIG_BLK_DEV_ZONED static int init_blkz_info(struct f2fs_sb_info *sbi, int devi) { struct block_device *bdev = FDEV(devi).bdev; sector_t nr_sectors = bdev->bd_part->nr_sects; sector_t sector = 0; struct blk_zone *zones; unsigned int i, nr_zones; unsigned int n = 0; int err = -EIO; if (!f2fs_sb_mounted_blkzoned(sbi->sb)) return 0; if (sbi->blocks_per_blkz && sbi->blocks_per_blkz != SECTOR_TO_BLOCK(bdev_zone_sectors(bdev))) return -EINVAL; sbi->blocks_per_blkz = SECTOR_TO_BLOCK(bdev_zone_sectors(bdev)); if (sbi->log_blocks_per_blkz && sbi->log_blocks_per_blkz != __ilog2_u32(sbi->blocks_per_blkz)) return -EINVAL; sbi->log_blocks_per_blkz = __ilog2_u32(sbi->blocks_per_blkz); FDEV(devi).nr_blkz = SECTOR_TO_BLOCK(nr_sectors) >> sbi->log_blocks_per_blkz; if (nr_sectors & (bdev_zone_sectors(bdev) - 1)) FDEV(devi).nr_blkz++; FDEV(devi).blkz_type = kmalloc(FDEV(devi).nr_blkz, GFP_KERNEL); if (!FDEV(devi).blkz_type) return -ENOMEM; #define F2FS_REPORT_NR_ZONES 4096 zones = kcalloc(F2FS_REPORT_NR_ZONES, sizeof(struct blk_zone), GFP_KERNEL); if (!zones) return -ENOMEM; /* Get block zones type */ while (zones && sector < nr_sectors) { nr_zones = F2FS_REPORT_NR_ZONES; err = blkdev_report_zones(bdev, sector, zones, &nr_zones, GFP_KERNEL); if (err) break; if (!nr_zones) { err = -EIO; break; } for (i = 0; i < nr_zones; i++) { FDEV(devi).blkz_type[n] = zones[i].type; sector += zones[i].len; n++; } } kfree(zones); return err; } #endif /* * Read f2fs raw super block. * Because we have two copies of super block, so read both of them * to get the first valid one. If any one of them is broken, we pass * them recovery flag back to the caller. */ static int read_raw_super_block(struct f2fs_sb_info *sbi, struct f2fs_super_block **raw_super, int *valid_super_block, int *recovery) { struct super_block *sb = sbi->sb; int block; struct buffer_head *bh; struct f2fs_super_block *super; int err = 0; super = kzalloc(sizeof(struct f2fs_super_block), GFP_KERNEL); if (!super) return -ENOMEM; for (block = 0; block < 2; block++) { bh = sb_bread(sb, block); if (!bh) { f2fs_msg(sb, KERN_ERR, "Unable to read %dth superblock", block + 1); err = -EIO; continue; } /* sanity checking of raw super */ if (sanity_check_raw_super(sbi, bh)) { f2fs_msg(sb, KERN_ERR, "Can't find valid F2FS filesystem in %dth superblock", block + 1); err = -EINVAL; brelse(bh); continue; } if (!*raw_super) { memcpy(super, bh->b_data + F2FS_SUPER_OFFSET, sizeof(*super)); *valid_super_block = block; *raw_super = super; } brelse(bh); } /* Fail to read any one of the superblocks*/ if (err < 0) *recovery = 1; /* No valid superblock */ if (!*raw_super) kfree(super); else err = 0; return err; } int f2fs_commit_super(struct f2fs_sb_info *sbi, bool recover) { struct buffer_head *bh; int err; if ((recover && f2fs_readonly(sbi->sb)) || bdev_read_only(sbi->sb->s_bdev)) { set_sbi_flag(sbi, SBI_NEED_SB_WRITE); return -EROFS; } /* write back-up superblock first */ bh = sb_getblk(sbi->sb, sbi->valid_super_block ? 0: 1); if (!bh) return -EIO; err = __f2fs_commit_super(bh, F2FS_RAW_SUPER(sbi)); brelse(bh); /* if we are in recovery path, skip writing valid superblock */ if (recover || err) return err; /* write current valid superblock */ bh = sb_getblk(sbi->sb, sbi->valid_super_block); if (!bh) return -EIO; err = __f2fs_commit_super(bh, F2FS_RAW_SUPER(sbi)); brelse(bh); return err; } static int f2fs_scan_devices(struct f2fs_sb_info *sbi) { struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi); unsigned int max_devices = MAX_DEVICES; int i; /* Initialize single device information */ if (!RDEV(0).path[0]) { if (!bdev_is_zoned(sbi->sb->s_bdev)) return 0; max_devices = 1; } /* * Initialize multiple devices information, or single * zoned block device information. */ sbi->devs = kcalloc(max_devices, sizeof(struct f2fs_dev_info), GFP_KERNEL); if (!sbi->devs) return -ENOMEM; for (i = 0; i < max_devices; i++) { if (i > 0 && !RDEV(i).path[0]) break; if (max_devices == 1) { /* Single zoned block device mount */ FDEV(0).bdev = blkdev_get_by_dev(sbi->sb->s_bdev->bd_dev, sbi->sb->s_mode, sbi->sb->s_type); } else { /* Multi-device mount */ memcpy(FDEV(i).path, RDEV(i).path, MAX_PATH_LEN); FDEV(i).total_segments = le32_to_cpu(RDEV(i).total_segments); if (i == 0) { FDEV(i).start_blk = 0; FDEV(i).end_blk = FDEV(i).start_blk + (FDEV(i).total_segments << sbi->log_blocks_per_seg) - 1 + le32_to_cpu(raw_super->segment0_blkaddr); } else { FDEV(i).start_blk = FDEV(i - 1).end_blk + 1; FDEV(i).end_blk = FDEV(i).start_blk + (FDEV(i).total_segments << sbi->log_blocks_per_seg) - 1; } FDEV(i).bdev = blkdev_get_by_path(FDEV(i).path, sbi->sb->s_mode, sbi->sb->s_type); } if (IS_ERR(FDEV(i).bdev)) return PTR_ERR(FDEV(i).bdev); /* to release errored devices */ sbi->s_ndevs = i + 1; #ifdef CONFIG_BLK_DEV_ZONED if (bdev_zoned_model(FDEV(i).bdev) == BLK_ZONED_HM && !f2fs_sb_mounted_blkzoned(sbi->sb)) { f2fs_msg(sbi->sb, KERN_ERR, "Zoned block device feature not enabled\n"); return -EINVAL; } if (bdev_zoned_model(FDEV(i).bdev) != BLK_ZONED_NONE) { if (init_blkz_info(sbi, i)) { f2fs_msg(sbi->sb, KERN_ERR, "Failed to initialize F2FS blkzone information"); return -EINVAL; } if (max_devices == 1) break; f2fs_msg(sbi->sb, KERN_INFO, "Mount Device [%2d]: %20s, %8u, %8x - %8x (zone: %s)", i, FDEV(i).path, FDEV(i).total_segments, FDEV(i).start_blk, FDEV(i).end_blk, bdev_zoned_model(FDEV(i).bdev) == BLK_ZONED_HA ? "Host-aware" : "Host-managed"); continue; } #endif f2fs_msg(sbi->sb, KERN_INFO, "Mount Device [%2d]: %20s, %8u, %8x - %8x", i, FDEV(i).path, FDEV(i).total_segments, FDEV(i).start_blk, FDEV(i).end_blk); } f2fs_msg(sbi->sb, KERN_INFO, "IO Block Size: %8d KB", F2FS_IO_SIZE_KB(sbi)); return 0; } static int f2fs_fill_super(struct super_block *sb, void *data, int silent) { struct f2fs_sb_info *sbi; struct f2fs_super_block *raw_super; struct inode *root; int err; bool retry = true, need_fsck = false; char *options = NULL; int recovery, i, valid_super_block; struct curseg_info *seg_i; try_onemore: err = -EINVAL; raw_super = NULL; valid_super_block = -1; recovery = 0; /* allocate memory for f2fs-specific super block info */ sbi = kzalloc(sizeof(struct f2fs_sb_info), GFP_KERNEL); if (!sbi) return -ENOMEM; sbi->sb = sb; /* Load the checksum driver */ sbi->s_chksum_driver = crypto_alloc_shash("crc32", 0, 0); if (IS_ERR(sbi->s_chksum_driver)) { f2fs_msg(sb, KERN_ERR, "Cannot load crc32 driver."); err = PTR_ERR(sbi->s_chksum_driver); sbi->s_chksum_driver = NULL; goto free_sbi; } /* set a block size */ if (unlikely(!sb_set_blocksize(sb, F2FS_BLKSIZE))) { f2fs_msg(sb, KERN_ERR, "unable to set blocksize"); goto free_sbi; } err = read_raw_super_block(sbi, &raw_super, &valid_super_block, &recovery); if (err) goto free_sbi; sb->s_fs_info = sbi; sbi->raw_super = raw_super; /* * The BLKZONED feature indicates that the drive was formatted with * zone alignment optimization. This is optional for host-aware * devices, but mandatory for host-managed zoned block devices. */ #ifndef CONFIG_BLK_DEV_ZONED if (f2fs_sb_mounted_blkzoned(sb)) { f2fs_msg(sb, KERN_ERR, "Zoned block device support is not enabled\n"); goto free_sb_buf; } #endif default_options(sbi); /* parse mount options */ options = kstrdup((const char *)data, GFP_KERNEL); if (data && !options) { err = -ENOMEM; goto free_sb_buf; } err = parse_options(sb, options); if (err) goto free_options; sbi->max_file_blocks = max_file_blocks(); sb->s_maxbytes = sbi->max_file_blocks << le32_to_cpu(raw_super->log_blocksize); sb->s_max_links = F2FS_LINK_MAX; get_random_bytes(&sbi->s_next_generation, sizeof(u32)); sb->s_op = &f2fs_sops; sb->s_cop = &f2fs_cryptops; sb->s_xattr = f2fs_xattr_handlers; sb->s_export_op = &f2fs_export_ops; sb->s_magic = F2FS_SUPER_MAGIC; sb->s_time_gran = 1; sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | (test_opt(sbi, POSIX_ACL) ? MS_POSIXACL : 0); memcpy(sb->s_uuid, raw_super->uuid, sizeof(raw_super->uuid)); /* init f2fs-specific super block info */ sbi->valid_super_block = valid_super_block; mutex_init(&sbi->gc_mutex); mutex_init(&sbi->cp_mutex); init_rwsem(&sbi->node_write); init_rwsem(&sbi->node_change); /* disallow all the data/node/meta page writes */ set_sbi_flag(sbi, SBI_POR_DOING); spin_lock_init(&sbi->stat_lock); init_rwsem(&sbi->read_io.io_rwsem); sbi->read_io.sbi = sbi; sbi->read_io.bio = NULL; for (i = 0; i < NR_PAGE_TYPE; i++) { init_rwsem(&sbi->write_io[i].io_rwsem); sbi->write_io[i].sbi = sbi; sbi->write_io[i].bio = NULL; } init_rwsem(&sbi->cp_rwsem); init_waitqueue_head(&sbi->cp_wait); init_sb_info(sbi); err = init_percpu_info(sbi); if (err) goto free_options; if (F2FS_IO_SIZE(sbi) > 1) { sbi->write_io_dummy = mempool_create_page_pool(2 * (F2FS_IO_SIZE(sbi) - 1), 0); if (!sbi->write_io_dummy) goto free_options; } /* get an inode for meta space */ sbi->meta_inode = f2fs_iget(sb, F2FS_META_INO(sbi)); if (IS_ERR(sbi->meta_inode)) { f2fs_msg(sb, KERN_ERR, "Failed to read F2FS meta data inode"); err = PTR_ERR(sbi->meta_inode); goto free_io_dummy; } err = get_valid_checkpoint(sbi); if (err) { f2fs_msg(sb, KERN_ERR, "Failed to get valid F2FS checkpoint"); goto free_meta_inode; } /* Initialize device list */ err = f2fs_scan_devices(sbi); if (err) { f2fs_msg(sb, KERN_ERR, "Failed to find devices"); goto free_devices; } sbi->total_valid_node_count = le32_to_cpu(sbi->ckpt->valid_node_count); percpu_counter_set(&sbi->total_valid_inode_count, le32_to_cpu(sbi->ckpt->valid_inode_count)); sbi->user_block_count = le64_to_cpu(sbi->ckpt->user_block_count); sbi->total_valid_block_count = le64_to_cpu(sbi->ckpt->valid_block_count); sbi->last_valid_block_count = sbi->total_valid_block_count; for (i = 0; i < NR_INODE_TYPE; i++) { INIT_LIST_HEAD(&sbi->inode_list[i]); spin_lock_init(&sbi->inode_lock[i]); } init_extent_cache_info(sbi); init_ino_entry_info(sbi); /* setup f2fs internal modules */ err = build_segment_manager(sbi); if (err) { f2fs_msg(sb, KERN_ERR, "Failed to initialize F2FS segment manager"); goto free_sm; } err = build_node_manager(sbi); if (err) { f2fs_msg(sb, KERN_ERR, "Failed to initialize F2FS node manager"); goto free_nm; } /* For write statistics */ if (sb->s_bdev->bd_part) sbi->sectors_written_start = (u64)part_stat_read(sb->s_bdev->bd_part, sectors[1]); /* Read accumulated write IO statistics if exists */ seg_i = CURSEG_I(sbi, CURSEG_HOT_NODE); if (__exist_node_summaries(sbi)) sbi->kbytes_written = le64_to_cpu(seg_i->journal->info.kbytes_written); build_gc_manager(sbi); /* get an inode for node space */ sbi->node_inode = f2fs_iget(sb, F2FS_NODE_INO(sbi)); if (IS_ERR(sbi->node_inode)) { f2fs_msg(sb, KERN_ERR, "Failed to read node inode"); err = PTR_ERR(sbi->node_inode); goto free_nm; } f2fs_join_shrinker(sbi); err = f2fs_build_stats(sbi); if (err) goto free_nm; /* if there are nt orphan nodes free them */ err = recover_orphan_inodes(sbi); if (err) goto free_node_inode; /* read root inode and dentry */ root = f2fs_iget(sb, F2FS_ROOT_INO(sbi)); if (IS_ERR(root)) { f2fs_msg(sb, KERN_ERR, "Failed to read root inode"); err = PTR_ERR(root); goto free_node_inode; } if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) { iput(root); err = -EINVAL; goto free_node_inode; } sb->s_root = d_make_root(root); /* allocate root dentry */ if (!sb->s_root) { err = -ENOMEM; goto free_root_inode; } if (f2fs_proc_root) sbi->s_proc = proc_mkdir(sb->s_id, f2fs_proc_root); if (sbi->s_proc) { proc_create_data("segment_info", S_IRUGO, sbi->s_proc, &f2fs_seq_segment_info_fops, sb); proc_create_data("segment_bits", S_IRUGO, sbi->s_proc, &f2fs_seq_segment_bits_fops, sb); } sbi->s_kobj.kset = f2fs_kset; init_completion(&sbi->s_kobj_unregister); err = kobject_init_and_add(&sbi->s_kobj, &f2fs_ktype, NULL, "%s", sb->s_id); if (err) goto free_proc; /* recover fsynced data */ if (!test_opt(sbi, DISABLE_ROLL_FORWARD)) { /* * mount should be failed, when device has readonly mode, and * previous checkpoint was not done by clean system shutdown. */ if (bdev_read_only(sb->s_bdev) && !is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) { err = -EROFS; goto free_kobj; } if (need_fsck) set_sbi_flag(sbi, SBI_NEED_FSCK); if (!retry) goto skip_recovery; err = recover_fsync_data(sbi, false); if (err < 0) { need_fsck = true; f2fs_msg(sb, KERN_ERR, "Cannot recover all fsync data errno=%d", err); goto free_kobj; } } else { err = recover_fsync_data(sbi, true); if (!f2fs_readonly(sb) && err > 0) { err = -EINVAL; f2fs_msg(sb, KERN_ERR, "Need to recover fsync data"); goto free_kobj; } } skip_recovery: /* recover_fsync_data() cleared this already */ clear_sbi_flag(sbi, SBI_POR_DOING); /* * If filesystem is not mounted as read-only then * do start the gc_thread. */ if (test_opt(sbi, BG_GC) && !f2fs_readonly(sb)) { /* After POR, we can run background GC thread.*/ err = start_gc_thread(sbi); if (err) goto free_kobj; } kfree(options); /* recover broken superblock */ if (recovery) { err = f2fs_commit_super(sbi, true); f2fs_msg(sb, KERN_INFO, "Try to recover %dth superblock, ret: %d", sbi->valid_super_block ? 1 : 2, err); } f2fs_msg(sbi->sb, KERN_NOTICE, "Mounted with checkpoint version = %llx", cur_cp_version(F2FS_CKPT(sbi))); f2fs_update_time(sbi, CP_TIME); f2fs_update_time(sbi, REQ_TIME); return 0; free_kobj: f2fs_sync_inode_meta(sbi); kobject_del(&sbi->s_kobj); kobject_put(&sbi->s_kobj); wait_for_completion(&sbi->s_kobj_unregister); free_proc: if (sbi->s_proc) { remove_proc_entry("segment_info", sbi->s_proc); remove_proc_entry("segment_bits", sbi->s_proc); remove_proc_entry(sb->s_id, f2fs_proc_root); } free_root_inode: dput(sb->s_root); sb->s_root = NULL; free_node_inode: truncate_inode_pages_final(NODE_MAPPING(sbi)); mutex_lock(&sbi->umount_mutex); release_ino_entry(sbi, true); f2fs_leave_shrinker(sbi); /* * Some dirty meta pages can be produced by recover_orphan_inodes() * failed by EIO. Then, iput(node_inode) can trigger balance_fs_bg() * followed by write_checkpoint() through f2fs_write_node_pages(), which * falls into an infinite loop in sync_meta_pages(). */ truncate_inode_pages_final(META_MAPPING(sbi)); iput(sbi->node_inode); mutex_unlock(&sbi->umount_mutex); f2fs_destroy_stats(sbi); free_nm: destroy_node_manager(sbi); free_sm: destroy_segment_manager(sbi); free_devices: destroy_device_list(sbi); kfree(sbi->ckpt); free_meta_inode: make_bad_inode(sbi->meta_inode); iput(sbi->meta_inode); free_io_dummy: mempool_destroy(sbi->write_io_dummy); free_options: destroy_percpu_info(sbi); kfree(options); free_sb_buf: kfree(raw_super); free_sbi: if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); kfree(sbi); /* give only one another chance */ if (retry) { retry = false; shrink_dcache_sb(sb); goto try_onemore; } return err; } static struct dentry *f2fs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_bdev(fs_type, flags, dev_name, data, f2fs_fill_super); } static void kill_f2fs_super(struct super_block *sb) { if (sb->s_root) set_sbi_flag(F2FS_SB(sb), SBI_IS_CLOSE); kill_block_super(sb); } static struct file_system_type f2fs_fs_type = { .owner = THIS_MODULE, .name = "f2fs", .mount = f2fs_mount, .kill_sb = kill_f2fs_super, .fs_flags = FS_REQUIRES_DEV, }; MODULE_ALIAS_FS("f2fs"); static int __init init_inodecache(void) { f2fs_inode_cachep = kmem_cache_create("f2fs_inode_cache", sizeof(struct f2fs_inode_info), 0, SLAB_RECLAIM_ACCOUNT|SLAB_ACCOUNT, NULL); if (!f2fs_inode_cachep) 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(f2fs_inode_cachep); } static int __init init_f2fs_fs(void) { int err; f2fs_build_trace_ios(); err = init_inodecache(); if (err) goto fail; err = create_node_manager_caches(); if (err) goto free_inodecache; err = create_segment_manager_caches(); if (err) goto free_node_manager_caches; err = create_checkpoint_caches(); if (err) goto free_segment_manager_caches; err = create_extent_cache(); if (err) goto free_checkpoint_caches; f2fs_kset = kset_create_and_add("f2fs", NULL, fs_kobj); if (!f2fs_kset) { err = -ENOMEM; goto free_extent_cache; } err = register_shrinker(&f2fs_shrinker_info); if (err) goto free_kset; err = register_filesystem(&f2fs_fs_type); if (err) goto free_shrinker; err = f2fs_create_root_stats(); if (err) goto free_filesystem; f2fs_proc_root = proc_mkdir("fs/f2fs", NULL); return 0; free_filesystem: unregister_filesystem(&f2fs_fs_type); free_shrinker: unregister_shrinker(&f2fs_shrinker_info); free_kset: kset_unregister(f2fs_kset); free_extent_cache: destroy_extent_cache(); free_checkpoint_caches: destroy_checkpoint_caches(); free_segment_manager_caches: destroy_segment_manager_caches(); free_node_manager_caches: destroy_node_manager_caches(); free_inodecache: destroy_inodecache(); fail: return err; } static void __exit exit_f2fs_fs(void) { remove_proc_entry("fs/f2fs", NULL); f2fs_destroy_root_stats(); unregister_filesystem(&f2fs_fs_type); unregister_shrinker(&f2fs_shrinker_info); kset_unregister(f2fs_kset); destroy_extent_cache(); destroy_checkpoint_caches(); destroy_segment_manager_caches(); destroy_node_manager_caches(); destroy_inodecache(); f2fs_destroy_trace_ios(); } module_init(init_f2fs_fs) module_exit(exit_f2fs_fs) MODULE_AUTHOR("Samsung Electronics's Praesto Team"); MODULE_DESCRIPTION("Flash Friendly File System"); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-129/c/good_2552_0
crossvul-cpp_data_bad_1431_0
/* * nf_nat_snmp_basic.c * * Basic SNMP Application Layer Gateway * * This IP NAT module is intended for use with SNMP network * discovery and monitoring applications where target networks use * conflicting private address realms. * * Static NAT is used to remap the networks from the view of the network * management system at the IP layer, and this module remaps some application * layer addresses to match. * * The simplest form of ALG is performed, where only tagged IP addresses * are modified. The module does not need to be MIB aware and only scans * messages at the ASN.1/BER level. * * Currently, only SNMPv1 and SNMPv2 are supported. * * More information on ALG and associated issues can be found in * RFC 2962 * * The ASB.1/BER parsing code is derived from the gxsnmp package by Gregory * McLean & Jochen Friedrich, stripped down for use in the kernel. * * Copyright (c) 2000 RP Internet (www.rpi.net.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. * 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/>. * * Author: James Morris <jmorris@intercode.com.au> * * Copyright (c) 2006-2010 Patrick McHardy <kaber@trash.net> */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/in.h> #include <linux/ip.h> #include <linux/udp.h> #include <net/checksum.h> #include <net/udp.h> #include <net/netfilter/nf_nat.h> #include <net/netfilter/nf_conntrack_expect.h> #include <net/netfilter/nf_conntrack_helper.h> #include <linux/netfilter/nf_conntrack_snmp.h> #include "nf_nat_snmp_basic.asn1.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("James Morris <jmorris@intercode.com.au>"); MODULE_DESCRIPTION("Basic SNMP Application Layer Gateway"); MODULE_ALIAS("ip_nat_snmp_basic"); MODULE_ALIAS_NFCT_HELPER("snmp_trap"); #define SNMP_PORT 161 #define SNMP_TRAP_PORT 162 static DEFINE_SPINLOCK(snmp_lock); struct snmp_ctx { unsigned char *begin; __sum16 *check; __be32 from; __be32 to; }; static void fast_csum(struct snmp_ctx *ctx, unsigned char offset) { unsigned char s[12] = {0,}; int size; if (offset & 1) { memcpy(&s[1], &ctx->from, 4); memcpy(&s[7], &ctx->to, 4); s[0] = ~0; s[1] = ~s[1]; s[2] = ~s[2]; s[3] = ~s[3]; s[4] = ~s[4]; s[5] = ~0; size = 12; } else { memcpy(&s[0], &ctx->from, 4); memcpy(&s[4], &ctx->to, 4); s[0] = ~s[0]; s[1] = ~s[1]; s[2] = ~s[2]; s[3] = ~s[3]; size = 8; } *ctx->check = csum_fold(csum_partial(s, size, ~csum_unfold(*ctx->check))); } int snmp_version(void *context, size_t hdrlen, unsigned char tag, const void *data, size_t datalen) { if (*(unsigned char *)data > 1) return -ENOTSUPP; return 1; } int snmp_helper(void *context, size_t hdrlen, unsigned char tag, const void *data, size_t datalen) { struct snmp_ctx *ctx = (struct snmp_ctx *)context; __be32 *pdata = (__be32 *)data; if (*pdata == ctx->from) { pr_debug("%s: %pI4 to %pI4\n", __func__, (void *)&ctx->from, (void *)&ctx->to); if (*ctx->check) fast_csum(ctx, (unsigned char *)data - ctx->begin); *pdata = ctx->to; } return 1; } static int snmp_translate(struct nf_conn *ct, int dir, struct sk_buff *skb) { struct iphdr *iph = ip_hdr(skb); struct udphdr *udph = (struct udphdr *)((__be32 *)iph + iph->ihl); u16 datalen = ntohs(udph->len) - sizeof(struct udphdr); char *data = (unsigned char *)udph + sizeof(struct udphdr); struct snmp_ctx ctx; int ret; if (dir == IP_CT_DIR_ORIGINAL) { ctx.from = ct->tuplehash[dir].tuple.src.u3.ip; ctx.to = ct->tuplehash[!dir].tuple.dst.u3.ip; } else { ctx.from = ct->tuplehash[!dir].tuple.src.u3.ip; ctx.to = ct->tuplehash[dir].tuple.dst.u3.ip; } if (ctx.from == ctx.to) return NF_ACCEPT; ctx.begin = (unsigned char *)udph + sizeof(struct udphdr); ctx.check = &udph->check; ret = asn1_ber_decoder(&nf_nat_snmp_basic_decoder, &ctx, data, datalen); if (ret < 0) { nf_ct_helper_log(skb, ct, "parser failed\n"); return NF_DROP; } return NF_ACCEPT; } /* We don't actually set up expectations, just adjust internal IP * addresses if this is being NATted */ static int help(struct sk_buff *skb, unsigned int protoff, struct nf_conn *ct, enum ip_conntrack_info ctinfo) { int dir = CTINFO2DIR(ctinfo); unsigned int ret; const struct iphdr *iph = ip_hdr(skb); const struct udphdr *udph = (struct udphdr *)((__be32 *)iph + iph->ihl); /* SNMP replies and originating SNMP traps get mangled */ if (udph->source == htons(SNMP_PORT) && dir != IP_CT_DIR_REPLY) return NF_ACCEPT; if (udph->dest == htons(SNMP_TRAP_PORT) && dir != IP_CT_DIR_ORIGINAL) return NF_ACCEPT; /* No NAT? */ if (!(ct->status & IPS_NAT_MASK)) return NF_ACCEPT; /* Make sure the packet length is ok. So far, we were only guaranteed * to have a valid length IP header plus 8 bytes, which means we have * enough room for a UDP header. Just verify the UDP length field so we * can mess around with the payload. */ if (ntohs(udph->len) != skb->len - (iph->ihl << 2)) { nf_ct_helper_log(skb, ct, "dropping malformed packet\n"); return NF_DROP; } if (!skb_make_writable(skb, skb->len)) { nf_ct_helper_log(skb, ct, "cannot mangle packet"); return NF_DROP; } spin_lock_bh(&snmp_lock); ret = snmp_translate(ct, dir, skb); spin_unlock_bh(&snmp_lock); return ret; } static const struct nf_conntrack_expect_policy snmp_exp_policy = { .max_expected = 0, .timeout = 180, }; static struct nf_conntrack_helper snmp_trap_helper __read_mostly = { .me = THIS_MODULE, .help = help, .expect_policy = &snmp_exp_policy, .name = "snmp_trap", .tuple.src.l3num = AF_INET, .tuple.src.u.udp.port = cpu_to_be16(SNMP_TRAP_PORT), .tuple.dst.protonum = IPPROTO_UDP, }; static int __init nf_nat_snmp_basic_init(void) { BUG_ON(nf_nat_snmp_hook != NULL); RCU_INIT_POINTER(nf_nat_snmp_hook, help); return nf_conntrack_helper_register(&snmp_trap_helper); } static void __exit nf_nat_snmp_basic_fini(void) { RCU_INIT_POINTER(nf_nat_snmp_hook, NULL); synchronize_rcu(); nf_conntrack_helper_unregister(&snmp_trap_helper); } module_init(nf_nat_snmp_basic_init); module_exit(nf_nat_snmp_basic_fini);
./CrossVul/dataset_final_sorted/CWE-129/c/bad_1431_0
crossvul-cpp_data_bad_2552_0
/* * fs/f2fs/super.c * * Copyright (c) 2012 Samsung Electronics Co., Ltd. * http://www.samsung.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. */ #include <linux/module.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/statfs.h> #include <linux/buffer_head.h> #include <linux/backing-dev.h> #include <linux/kthread.h> #include <linux/parser.h> #include <linux/mount.h> #include <linux/seq_file.h> #include <linux/proc_fs.h> #include <linux/random.h> #include <linux/exportfs.h> #include <linux/blkdev.h> #include <linux/f2fs_fs.h> #include <linux/sysfs.h> #include "f2fs.h" #include "node.h" #include "segment.h" #include "xattr.h" #include "gc.h" #include "trace.h" #define CREATE_TRACE_POINTS #include <trace/events/f2fs.h> static struct proc_dir_entry *f2fs_proc_root; static struct kmem_cache *f2fs_inode_cachep; static struct kset *f2fs_kset; #ifdef CONFIG_F2FS_FAULT_INJECTION char *fault_name[FAULT_MAX] = { [FAULT_KMALLOC] = "kmalloc", [FAULT_PAGE_ALLOC] = "page alloc", [FAULT_ALLOC_NID] = "alloc nid", [FAULT_ORPHAN] = "orphan", [FAULT_BLOCK] = "no more block", [FAULT_DIR_DEPTH] = "too big dir depth", [FAULT_EVICT_INODE] = "evict_inode fail", [FAULT_TRUNCATE] = "truncate fail", [FAULT_IO] = "IO error", [FAULT_CHECKPOINT] = "checkpoint error", }; static void f2fs_build_fault_attr(struct f2fs_sb_info *sbi, unsigned int rate) { struct f2fs_fault_info *ffi = &sbi->fault_info; if (rate) { atomic_set(&ffi->inject_ops, 0); ffi->inject_rate = rate; ffi->inject_type = (1 << FAULT_MAX) - 1; } else { memset(ffi, 0, sizeof(struct f2fs_fault_info)); } } #endif /* f2fs-wide shrinker description */ static struct shrinker f2fs_shrinker_info = { .scan_objects = f2fs_shrink_scan, .count_objects = f2fs_shrink_count, .seeks = DEFAULT_SEEKS, }; enum { Opt_gc_background, Opt_disable_roll_forward, Opt_norecovery, Opt_discard, Opt_nodiscard, Opt_noheap, Opt_heap, Opt_user_xattr, Opt_nouser_xattr, Opt_acl, Opt_noacl, Opt_active_logs, Opt_disable_ext_identify, Opt_inline_xattr, Opt_noinline_xattr, Opt_inline_data, Opt_inline_dentry, Opt_noinline_dentry, Opt_flush_merge, Opt_noflush_merge, Opt_nobarrier, Opt_fastboot, Opt_extent_cache, Opt_noextent_cache, Opt_noinline_data, Opt_data_flush, Opt_mode, Opt_io_size_bits, Opt_fault_injection, Opt_lazytime, Opt_nolazytime, Opt_err, }; static match_table_t f2fs_tokens = { {Opt_gc_background, "background_gc=%s"}, {Opt_disable_roll_forward, "disable_roll_forward"}, {Opt_norecovery, "norecovery"}, {Opt_discard, "discard"}, {Opt_nodiscard, "nodiscard"}, {Opt_noheap, "no_heap"}, {Opt_heap, "heap"}, {Opt_user_xattr, "user_xattr"}, {Opt_nouser_xattr, "nouser_xattr"}, {Opt_acl, "acl"}, {Opt_noacl, "noacl"}, {Opt_active_logs, "active_logs=%u"}, {Opt_disable_ext_identify, "disable_ext_identify"}, {Opt_inline_xattr, "inline_xattr"}, {Opt_noinline_xattr, "noinline_xattr"}, {Opt_inline_data, "inline_data"}, {Opt_inline_dentry, "inline_dentry"}, {Opt_noinline_dentry, "noinline_dentry"}, {Opt_flush_merge, "flush_merge"}, {Opt_noflush_merge, "noflush_merge"}, {Opt_nobarrier, "nobarrier"}, {Opt_fastboot, "fastboot"}, {Opt_extent_cache, "extent_cache"}, {Opt_noextent_cache, "noextent_cache"}, {Opt_noinline_data, "noinline_data"}, {Opt_data_flush, "data_flush"}, {Opt_mode, "mode=%s"}, {Opt_io_size_bits, "io_bits=%u"}, {Opt_fault_injection, "fault_injection=%u"}, {Opt_lazytime, "lazytime"}, {Opt_nolazytime, "nolazytime"}, {Opt_err, NULL}, }; /* Sysfs support for f2fs */ enum { GC_THREAD, /* struct f2fs_gc_thread */ SM_INFO, /* struct f2fs_sm_info */ DCC_INFO, /* struct discard_cmd_control */ NM_INFO, /* struct f2fs_nm_info */ F2FS_SBI, /* struct f2fs_sb_info */ #ifdef CONFIG_F2FS_FAULT_INJECTION FAULT_INFO_RATE, /* struct f2fs_fault_info */ FAULT_INFO_TYPE, /* struct f2fs_fault_info */ #endif }; struct f2fs_attr { struct attribute attr; ssize_t (*show)(struct f2fs_attr *, struct f2fs_sb_info *, char *); ssize_t (*store)(struct f2fs_attr *, struct f2fs_sb_info *, const char *, size_t); int struct_type; int offset; }; static unsigned char *__struct_ptr(struct f2fs_sb_info *sbi, int struct_type) { if (struct_type == GC_THREAD) return (unsigned char *)sbi->gc_thread; else if (struct_type == SM_INFO) return (unsigned char *)SM_I(sbi); else if (struct_type == DCC_INFO) return (unsigned char *)SM_I(sbi)->dcc_info; else if (struct_type == NM_INFO) return (unsigned char *)NM_I(sbi); else if (struct_type == F2FS_SBI) return (unsigned char *)sbi; #ifdef CONFIG_F2FS_FAULT_INJECTION else if (struct_type == FAULT_INFO_RATE || struct_type == FAULT_INFO_TYPE) return (unsigned char *)&sbi->fault_info; #endif return NULL; } static ssize_t lifetime_write_kbytes_show(struct f2fs_attr *a, struct f2fs_sb_info *sbi, char *buf) { struct super_block *sb = sbi->sb; if (!sb->s_bdev->bd_part) return snprintf(buf, PAGE_SIZE, "0\n"); return snprintf(buf, PAGE_SIZE, "%llu\n", (unsigned long long)(sbi->kbytes_written + BD_PART_WRITTEN(sbi))); } static ssize_t f2fs_sbi_show(struct f2fs_attr *a, struct f2fs_sb_info *sbi, char *buf) { unsigned char *ptr = NULL; unsigned int *ui; ptr = __struct_ptr(sbi, a->struct_type); if (!ptr) return -EINVAL; ui = (unsigned int *)(ptr + a->offset); return snprintf(buf, PAGE_SIZE, "%u\n", *ui); } static ssize_t f2fs_sbi_store(struct f2fs_attr *a, struct f2fs_sb_info *sbi, const char *buf, size_t count) { unsigned char *ptr; unsigned long t; unsigned int *ui; ssize_t ret; ptr = __struct_ptr(sbi, a->struct_type); if (!ptr) return -EINVAL; ui = (unsigned int *)(ptr + a->offset); ret = kstrtoul(skip_spaces(buf), 0, &t); if (ret < 0) return ret; #ifdef CONFIG_F2FS_FAULT_INJECTION if (a->struct_type == FAULT_INFO_TYPE && t >= (1 << FAULT_MAX)) return -EINVAL; #endif *ui = t; return count; } static ssize_t f2fs_attr_show(struct kobject *kobj, struct attribute *attr, char *buf) { struct f2fs_sb_info *sbi = container_of(kobj, struct f2fs_sb_info, s_kobj); struct f2fs_attr *a = container_of(attr, struct f2fs_attr, attr); return a->show ? a->show(a, sbi, buf) : 0; } static ssize_t f2fs_attr_store(struct kobject *kobj, struct attribute *attr, const char *buf, size_t len) { struct f2fs_sb_info *sbi = container_of(kobj, struct f2fs_sb_info, s_kobj); struct f2fs_attr *a = container_of(attr, struct f2fs_attr, attr); return a->store ? a->store(a, sbi, buf, len) : 0; } static void f2fs_sb_release(struct kobject *kobj) { struct f2fs_sb_info *sbi = container_of(kobj, struct f2fs_sb_info, s_kobj); complete(&sbi->s_kobj_unregister); } #define F2FS_ATTR_OFFSET(_struct_type, _name, _mode, _show, _store, _offset) \ static struct f2fs_attr f2fs_attr_##_name = { \ .attr = {.name = __stringify(_name), .mode = _mode }, \ .show = _show, \ .store = _store, \ .struct_type = _struct_type, \ .offset = _offset \ } #define F2FS_RW_ATTR(struct_type, struct_name, name, elname) \ F2FS_ATTR_OFFSET(struct_type, name, 0644, \ f2fs_sbi_show, f2fs_sbi_store, \ offsetof(struct struct_name, elname)) #define F2FS_GENERAL_RO_ATTR(name) \ static struct f2fs_attr f2fs_attr_##name = __ATTR(name, 0444, name##_show, NULL) F2FS_RW_ATTR(GC_THREAD, f2fs_gc_kthread, gc_min_sleep_time, min_sleep_time); F2FS_RW_ATTR(GC_THREAD, f2fs_gc_kthread, gc_max_sleep_time, max_sleep_time); F2FS_RW_ATTR(GC_THREAD, f2fs_gc_kthread, gc_no_gc_sleep_time, no_gc_sleep_time); F2FS_RW_ATTR(GC_THREAD, f2fs_gc_kthread, gc_idle, gc_idle); F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, reclaim_segments, rec_prefree_segments); F2FS_RW_ATTR(DCC_INFO, discard_cmd_control, max_small_discards, max_discards); F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, batched_trim_sections, trim_sections); F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, ipu_policy, ipu_policy); F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, min_ipu_util, min_ipu_util); F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, min_fsync_blocks, min_fsync_blocks); F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, min_hot_blocks, min_hot_blocks); F2FS_RW_ATTR(NM_INFO, f2fs_nm_info, ram_thresh, ram_thresh); F2FS_RW_ATTR(NM_INFO, f2fs_nm_info, ra_nid_pages, ra_nid_pages); F2FS_RW_ATTR(NM_INFO, f2fs_nm_info, dirty_nats_ratio, dirty_nats_ratio); F2FS_RW_ATTR(F2FS_SBI, f2fs_sb_info, max_victim_search, max_victim_search); F2FS_RW_ATTR(F2FS_SBI, f2fs_sb_info, dir_level, dir_level); F2FS_RW_ATTR(F2FS_SBI, f2fs_sb_info, cp_interval, interval_time[CP_TIME]); F2FS_RW_ATTR(F2FS_SBI, f2fs_sb_info, idle_interval, interval_time[REQ_TIME]); #ifdef CONFIG_F2FS_FAULT_INJECTION F2FS_RW_ATTR(FAULT_INFO_RATE, f2fs_fault_info, inject_rate, inject_rate); F2FS_RW_ATTR(FAULT_INFO_TYPE, f2fs_fault_info, inject_type, inject_type); #endif F2FS_GENERAL_RO_ATTR(lifetime_write_kbytes); #define ATTR_LIST(name) (&f2fs_attr_##name.attr) static struct attribute *f2fs_attrs[] = { ATTR_LIST(gc_min_sleep_time), ATTR_LIST(gc_max_sleep_time), ATTR_LIST(gc_no_gc_sleep_time), ATTR_LIST(gc_idle), ATTR_LIST(reclaim_segments), ATTR_LIST(max_small_discards), ATTR_LIST(batched_trim_sections), ATTR_LIST(ipu_policy), ATTR_LIST(min_ipu_util), ATTR_LIST(min_fsync_blocks), ATTR_LIST(min_hot_blocks), ATTR_LIST(max_victim_search), ATTR_LIST(dir_level), ATTR_LIST(ram_thresh), ATTR_LIST(ra_nid_pages), ATTR_LIST(dirty_nats_ratio), ATTR_LIST(cp_interval), ATTR_LIST(idle_interval), #ifdef CONFIG_F2FS_FAULT_INJECTION ATTR_LIST(inject_rate), ATTR_LIST(inject_type), #endif ATTR_LIST(lifetime_write_kbytes), NULL, }; static const struct sysfs_ops f2fs_attr_ops = { .show = f2fs_attr_show, .store = f2fs_attr_store, }; static struct kobj_type f2fs_ktype = { .default_attrs = f2fs_attrs, .sysfs_ops = &f2fs_attr_ops, .release = f2fs_sb_release, }; void f2fs_msg(struct super_block *sb, const char *level, const char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; printk("%sF2FS-fs (%s): %pV\n", level, sb->s_id, &vaf); va_end(args); } static void init_once(void *foo) { struct f2fs_inode_info *fi = (struct f2fs_inode_info *) foo; inode_init_once(&fi->vfs_inode); } static int parse_options(struct super_block *sb, char *options) { struct f2fs_sb_info *sbi = F2FS_SB(sb); struct request_queue *q; substring_t args[MAX_OPT_ARGS]; char *p, *name; int arg = 0; if (!options) return 0; 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, f2fs_tokens, args); switch (token) { case Opt_gc_background: name = match_strdup(&args[0]); if (!name) return -ENOMEM; if (strlen(name) == 2 && !strncmp(name, "on", 2)) { set_opt(sbi, BG_GC); clear_opt(sbi, FORCE_FG_GC); } else if (strlen(name) == 3 && !strncmp(name, "off", 3)) { clear_opt(sbi, BG_GC); clear_opt(sbi, FORCE_FG_GC); } else if (strlen(name) == 4 && !strncmp(name, "sync", 4)) { set_opt(sbi, BG_GC); set_opt(sbi, FORCE_FG_GC); } else { kfree(name); return -EINVAL; } kfree(name); break; case Opt_disable_roll_forward: set_opt(sbi, DISABLE_ROLL_FORWARD); break; case Opt_norecovery: /* this option mounts f2fs with ro */ set_opt(sbi, DISABLE_ROLL_FORWARD); if (!f2fs_readonly(sb)) return -EINVAL; break; case Opt_discard: q = bdev_get_queue(sb->s_bdev); if (blk_queue_discard(q)) { set_opt(sbi, DISCARD); } else if (!f2fs_sb_mounted_blkzoned(sb)) { f2fs_msg(sb, KERN_WARNING, "mounting with \"discard\" option, but " "the device does not support discard"); } break; case Opt_nodiscard: if (f2fs_sb_mounted_blkzoned(sb)) { f2fs_msg(sb, KERN_WARNING, "discard is required for zoned block devices"); return -EINVAL; } clear_opt(sbi, DISCARD); break; case Opt_noheap: set_opt(sbi, NOHEAP); break; case Opt_heap: clear_opt(sbi, NOHEAP); break; #ifdef CONFIG_F2FS_FS_XATTR case Opt_user_xattr: set_opt(sbi, XATTR_USER); break; case Opt_nouser_xattr: clear_opt(sbi, XATTR_USER); break; case Opt_inline_xattr: set_opt(sbi, INLINE_XATTR); break; case Opt_noinline_xattr: clear_opt(sbi, INLINE_XATTR); break; #else case Opt_user_xattr: f2fs_msg(sb, KERN_INFO, "user_xattr options not supported"); break; case Opt_nouser_xattr: f2fs_msg(sb, KERN_INFO, "nouser_xattr options not supported"); break; case Opt_inline_xattr: f2fs_msg(sb, KERN_INFO, "inline_xattr options not supported"); break; case Opt_noinline_xattr: f2fs_msg(sb, KERN_INFO, "noinline_xattr options not supported"); break; #endif #ifdef CONFIG_F2FS_FS_POSIX_ACL case Opt_acl: set_opt(sbi, POSIX_ACL); break; case Opt_noacl: clear_opt(sbi, POSIX_ACL); break; #else case Opt_acl: f2fs_msg(sb, KERN_INFO, "acl options not supported"); break; case Opt_noacl: f2fs_msg(sb, KERN_INFO, "noacl options not supported"); break; #endif case Opt_active_logs: if (args->from && match_int(args, &arg)) return -EINVAL; if (arg != 2 && arg != 4 && arg != NR_CURSEG_TYPE) return -EINVAL; sbi->active_logs = arg; break; case Opt_disable_ext_identify: set_opt(sbi, DISABLE_EXT_IDENTIFY); break; case Opt_inline_data: set_opt(sbi, INLINE_DATA); break; case Opt_inline_dentry: set_opt(sbi, INLINE_DENTRY); break; case Opt_noinline_dentry: clear_opt(sbi, INLINE_DENTRY); break; case Opt_flush_merge: set_opt(sbi, FLUSH_MERGE); break; case Opt_noflush_merge: clear_opt(sbi, FLUSH_MERGE); break; case Opt_nobarrier: set_opt(sbi, NOBARRIER); break; case Opt_fastboot: set_opt(sbi, FASTBOOT); break; case Opt_extent_cache: set_opt(sbi, EXTENT_CACHE); break; case Opt_noextent_cache: clear_opt(sbi, EXTENT_CACHE); break; case Opt_noinline_data: clear_opt(sbi, INLINE_DATA); break; case Opt_data_flush: set_opt(sbi, DATA_FLUSH); break; case Opt_mode: name = match_strdup(&args[0]); if (!name) return -ENOMEM; if (strlen(name) == 8 && !strncmp(name, "adaptive", 8)) { if (f2fs_sb_mounted_blkzoned(sb)) { f2fs_msg(sb, KERN_WARNING, "adaptive mode is not allowed with " "zoned block device feature"); kfree(name); return -EINVAL; } set_opt_mode(sbi, F2FS_MOUNT_ADAPTIVE); } else if (strlen(name) == 3 && !strncmp(name, "lfs", 3)) { set_opt_mode(sbi, F2FS_MOUNT_LFS); } else { kfree(name); return -EINVAL; } kfree(name); break; case Opt_io_size_bits: if (args->from && match_int(args, &arg)) return -EINVAL; if (arg > __ilog2_u32(BIO_MAX_PAGES)) { f2fs_msg(sb, KERN_WARNING, "Not support %d, larger than %d", 1 << arg, BIO_MAX_PAGES); return -EINVAL; } sbi->write_io_size_bits = arg; break; case Opt_fault_injection: if (args->from && match_int(args, &arg)) return -EINVAL; #ifdef CONFIG_F2FS_FAULT_INJECTION f2fs_build_fault_attr(sbi, arg); set_opt(sbi, FAULT_INJECTION); #else f2fs_msg(sb, KERN_INFO, "FAULT_INJECTION was not selected"); #endif break; case Opt_lazytime: sb->s_flags |= MS_LAZYTIME; break; case Opt_nolazytime: sb->s_flags &= ~MS_LAZYTIME; break; default: f2fs_msg(sb, KERN_ERR, "Unrecognized mount option \"%s\" or missing value", p); return -EINVAL; } } if (F2FS_IO_SIZE_BITS(sbi) && !test_opt(sbi, LFS)) { f2fs_msg(sb, KERN_ERR, "Should set mode=lfs with %uKB-sized IO", F2FS_IO_SIZE_KB(sbi)); return -EINVAL; } return 0; } static struct inode *f2fs_alloc_inode(struct super_block *sb) { struct f2fs_inode_info *fi; fi = kmem_cache_alloc(f2fs_inode_cachep, GFP_F2FS_ZERO); if (!fi) return NULL; init_once((void *) fi); /* Initialize f2fs-specific inode info */ fi->vfs_inode.i_version = 1; atomic_set(&fi->dirty_pages, 0); fi->i_current_depth = 1; fi->i_advise = 0; init_rwsem(&fi->i_sem); INIT_LIST_HEAD(&fi->dirty_list); INIT_LIST_HEAD(&fi->gdirty_list); INIT_LIST_HEAD(&fi->inmem_pages); mutex_init(&fi->inmem_lock); init_rwsem(&fi->dio_rwsem[READ]); init_rwsem(&fi->dio_rwsem[WRITE]); /* Will be used by directory only */ fi->i_dir_level = F2FS_SB(sb)->dir_level; return &fi->vfs_inode; } static int f2fs_drop_inode(struct inode *inode) { int ret; /* * This is to avoid a deadlock condition like below. * writeback_single_inode(inode) * - f2fs_write_data_page * - f2fs_gc -> iput -> evict * - inode_wait_for_writeback(inode) */ if ((!inode_unhashed(inode) && inode->i_state & I_SYNC)) { if (!inode->i_nlink && !is_bad_inode(inode)) { /* to avoid evict_inode call simultaneously */ atomic_inc(&inode->i_count); spin_unlock(&inode->i_lock); /* some remained atomic pages should discarded */ if (f2fs_is_atomic_file(inode)) drop_inmem_pages(inode); /* should remain fi->extent_tree for writepage */ f2fs_destroy_extent_node(inode); sb_start_intwrite(inode->i_sb); f2fs_i_size_write(inode, 0); if (F2FS_HAS_BLOCKS(inode)) f2fs_truncate(inode); sb_end_intwrite(inode->i_sb); fscrypt_put_encryption_info(inode, NULL); spin_lock(&inode->i_lock); atomic_dec(&inode->i_count); } trace_f2fs_drop_inode(inode, 0); return 0; } ret = generic_drop_inode(inode); trace_f2fs_drop_inode(inode, ret); return ret; } int f2fs_inode_dirtied(struct inode *inode, bool sync) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); int ret = 0; spin_lock(&sbi->inode_lock[DIRTY_META]); if (is_inode_flag_set(inode, FI_DIRTY_INODE)) { ret = 1; } else { set_inode_flag(inode, FI_DIRTY_INODE); stat_inc_dirty_inode(sbi, DIRTY_META); } if (sync && list_empty(&F2FS_I(inode)->gdirty_list)) { list_add_tail(&F2FS_I(inode)->gdirty_list, &sbi->inode_list[DIRTY_META]); inc_page_count(sbi, F2FS_DIRTY_IMETA); } spin_unlock(&sbi->inode_lock[DIRTY_META]); return ret; } void f2fs_inode_synced(struct inode *inode) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); spin_lock(&sbi->inode_lock[DIRTY_META]); if (!is_inode_flag_set(inode, FI_DIRTY_INODE)) { spin_unlock(&sbi->inode_lock[DIRTY_META]); return; } if (!list_empty(&F2FS_I(inode)->gdirty_list)) { list_del_init(&F2FS_I(inode)->gdirty_list); dec_page_count(sbi, F2FS_DIRTY_IMETA); } clear_inode_flag(inode, FI_DIRTY_INODE); clear_inode_flag(inode, FI_AUTO_RECOVER); stat_dec_dirty_inode(F2FS_I_SB(inode), DIRTY_META); spin_unlock(&sbi->inode_lock[DIRTY_META]); } /* * f2fs_dirty_inode() is called from __mark_inode_dirty() * * We should call set_dirty_inode to write the dirty inode through write_inode. */ static void f2fs_dirty_inode(struct inode *inode, int flags) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); if (inode->i_ino == F2FS_NODE_INO(sbi) || inode->i_ino == F2FS_META_INO(sbi)) return; if (flags == I_DIRTY_TIME) return; if (is_inode_flag_set(inode, FI_AUTO_RECOVER)) clear_inode_flag(inode, FI_AUTO_RECOVER); f2fs_inode_dirtied(inode, false); } static void f2fs_i_callback(struct rcu_head *head) { struct inode *inode = container_of(head, struct inode, i_rcu); kmem_cache_free(f2fs_inode_cachep, F2FS_I(inode)); } static void f2fs_destroy_inode(struct inode *inode) { call_rcu(&inode->i_rcu, f2fs_i_callback); } static void destroy_percpu_info(struct f2fs_sb_info *sbi) { percpu_counter_destroy(&sbi->alloc_valid_block_count); percpu_counter_destroy(&sbi->total_valid_inode_count); } static void destroy_device_list(struct f2fs_sb_info *sbi) { int i; for (i = 0; i < sbi->s_ndevs; i++) { blkdev_put(FDEV(i).bdev, FMODE_EXCL); #ifdef CONFIG_BLK_DEV_ZONED kfree(FDEV(i).blkz_type); #endif } kfree(sbi->devs); } static void f2fs_put_super(struct super_block *sb) { struct f2fs_sb_info *sbi = F2FS_SB(sb); if (sbi->s_proc) { remove_proc_entry("segment_info", sbi->s_proc); remove_proc_entry("segment_bits", sbi->s_proc); remove_proc_entry(sb->s_id, f2fs_proc_root); } kobject_del(&sbi->s_kobj); stop_gc_thread(sbi); /* prevent remaining shrinker jobs */ mutex_lock(&sbi->umount_mutex); /* * We don't need to do checkpoint when superblock is clean. * But, the previous checkpoint was not done by umount, it needs to do * clean checkpoint again. */ if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) || !is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) { struct cp_control cpc = { .reason = CP_UMOUNT, }; write_checkpoint(sbi, &cpc); } /* be sure to wait for any on-going discard commands */ f2fs_wait_discard_bios(sbi); if (!sbi->discard_blks) { struct cp_control cpc = { .reason = CP_UMOUNT | CP_TRIMMED, }; write_checkpoint(sbi, &cpc); } /* write_checkpoint can update stat informaion */ f2fs_destroy_stats(sbi); /* * normally superblock is clean, so we need to release this. * In addition, EIO will skip do checkpoint, we need this as well. */ release_ino_entry(sbi, true); f2fs_leave_shrinker(sbi); mutex_unlock(&sbi->umount_mutex); /* our cp_error case, we can wait for any writeback page */ f2fs_flush_merged_bios(sbi); iput(sbi->node_inode); iput(sbi->meta_inode); /* destroy f2fs internal modules */ destroy_node_manager(sbi); destroy_segment_manager(sbi); kfree(sbi->ckpt); kobject_put(&sbi->s_kobj); wait_for_completion(&sbi->s_kobj_unregister); sb->s_fs_info = NULL; if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); kfree(sbi->raw_super); destroy_device_list(sbi); mempool_destroy(sbi->write_io_dummy); destroy_percpu_info(sbi); kfree(sbi); } int f2fs_sync_fs(struct super_block *sb, int sync) { struct f2fs_sb_info *sbi = F2FS_SB(sb); int err = 0; trace_f2fs_sync_fs(sb, sync); if (sync) { struct cp_control cpc; cpc.reason = __get_cp_reason(sbi); mutex_lock(&sbi->gc_mutex); err = write_checkpoint(sbi, &cpc); mutex_unlock(&sbi->gc_mutex); } f2fs_trace_ios(NULL, 1); return err; } static int f2fs_freeze(struct super_block *sb) { if (f2fs_readonly(sb)) return 0; /* IO error happened before */ if (unlikely(f2fs_cp_error(F2FS_SB(sb)))) return -EIO; /* must be clean, since sync_filesystem() was already called */ if (is_sbi_flag_set(F2FS_SB(sb), SBI_IS_DIRTY)) return -EINVAL; return 0; } static int f2fs_unfreeze(struct super_block *sb) { return 0; } static int f2fs_statfs(struct dentry *dentry, struct kstatfs *buf) { struct super_block *sb = dentry->d_sb; struct f2fs_sb_info *sbi = F2FS_SB(sb); u64 id = huge_encode_dev(sb->s_bdev->bd_dev); block_t total_count, user_block_count, start_count, ovp_count; total_count = le64_to_cpu(sbi->raw_super->block_count); user_block_count = sbi->user_block_count; start_count = le32_to_cpu(sbi->raw_super->segment0_blkaddr); ovp_count = SM_I(sbi)->ovp_segments << sbi->log_blocks_per_seg; buf->f_type = F2FS_SUPER_MAGIC; buf->f_bsize = sbi->blocksize; buf->f_blocks = total_count - start_count; buf->f_bfree = user_block_count - valid_user_blocks(sbi) + ovp_count; buf->f_bavail = user_block_count - valid_user_blocks(sbi); buf->f_files = sbi->total_node_count - F2FS_RESERVED_NODE_NUM; buf->f_ffree = min(buf->f_files - valid_node_count(sbi), buf->f_bavail); buf->f_namelen = F2FS_NAME_LEN; buf->f_fsid.val[0] = (u32)id; buf->f_fsid.val[1] = (u32)(id >> 32); return 0; } static int f2fs_show_options(struct seq_file *seq, struct dentry *root) { struct f2fs_sb_info *sbi = F2FS_SB(root->d_sb); if (!f2fs_readonly(sbi->sb) && test_opt(sbi, BG_GC)) { if (test_opt(sbi, FORCE_FG_GC)) seq_printf(seq, ",background_gc=%s", "sync"); else seq_printf(seq, ",background_gc=%s", "on"); } else { seq_printf(seq, ",background_gc=%s", "off"); } if (test_opt(sbi, DISABLE_ROLL_FORWARD)) seq_puts(seq, ",disable_roll_forward"); if (test_opt(sbi, DISCARD)) seq_puts(seq, ",discard"); if (test_opt(sbi, NOHEAP)) seq_puts(seq, ",no_heap"); else seq_puts(seq, ",heap"); #ifdef CONFIG_F2FS_FS_XATTR if (test_opt(sbi, XATTR_USER)) seq_puts(seq, ",user_xattr"); else seq_puts(seq, ",nouser_xattr"); if (test_opt(sbi, INLINE_XATTR)) seq_puts(seq, ",inline_xattr"); else seq_puts(seq, ",noinline_xattr"); #endif #ifdef CONFIG_F2FS_FS_POSIX_ACL if (test_opt(sbi, POSIX_ACL)) seq_puts(seq, ",acl"); else seq_puts(seq, ",noacl"); #endif if (test_opt(sbi, DISABLE_EXT_IDENTIFY)) seq_puts(seq, ",disable_ext_identify"); if (test_opt(sbi, INLINE_DATA)) seq_puts(seq, ",inline_data"); else seq_puts(seq, ",noinline_data"); if (test_opt(sbi, INLINE_DENTRY)) seq_puts(seq, ",inline_dentry"); else seq_puts(seq, ",noinline_dentry"); if (!f2fs_readonly(sbi->sb) && test_opt(sbi, FLUSH_MERGE)) seq_puts(seq, ",flush_merge"); if (test_opt(sbi, NOBARRIER)) seq_puts(seq, ",nobarrier"); if (test_opt(sbi, FASTBOOT)) seq_puts(seq, ",fastboot"); if (test_opt(sbi, EXTENT_CACHE)) seq_puts(seq, ",extent_cache"); else seq_puts(seq, ",noextent_cache"); if (test_opt(sbi, DATA_FLUSH)) seq_puts(seq, ",data_flush"); seq_puts(seq, ",mode="); if (test_opt(sbi, ADAPTIVE)) seq_puts(seq, "adaptive"); else if (test_opt(sbi, LFS)) seq_puts(seq, "lfs"); seq_printf(seq, ",active_logs=%u", sbi->active_logs); if (F2FS_IO_SIZE_BITS(sbi)) seq_printf(seq, ",io_size=%uKB", F2FS_IO_SIZE_KB(sbi)); #ifdef CONFIG_F2FS_FAULT_INJECTION if (test_opt(sbi, FAULT_INJECTION)) seq_puts(seq, ",fault_injection"); #endif return 0; } static int segment_info_seq_show(struct seq_file *seq, void *offset) { struct super_block *sb = seq->private; struct f2fs_sb_info *sbi = F2FS_SB(sb); unsigned int total_segs = le32_to_cpu(sbi->raw_super->segment_count_main); int i; seq_puts(seq, "format: segment_type|valid_blocks\n" "segment_type(0:HD, 1:WD, 2:CD, 3:HN, 4:WN, 5:CN)\n"); for (i = 0; i < total_segs; i++) { struct seg_entry *se = get_seg_entry(sbi, i); if ((i % 10) == 0) seq_printf(seq, "%-10d", i); seq_printf(seq, "%d|%-3u", se->type, get_valid_blocks(sbi, i, false)); if ((i % 10) == 9 || i == (total_segs - 1)) seq_putc(seq, '\n'); else seq_putc(seq, ' '); } return 0; } static int segment_bits_seq_show(struct seq_file *seq, void *offset) { struct super_block *sb = seq->private; struct f2fs_sb_info *sbi = F2FS_SB(sb); unsigned int total_segs = le32_to_cpu(sbi->raw_super->segment_count_main); int i, j; seq_puts(seq, "format: segment_type|valid_blocks|bitmaps\n" "segment_type(0:HD, 1:WD, 2:CD, 3:HN, 4:WN, 5:CN)\n"); for (i = 0; i < total_segs; i++) { struct seg_entry *se = get_seg_entry(sbi, i); seq_printf(seq, "%-10d", i); seq_printf(seq, "%d|%-3u|", se->type, get_valid_blocks(sbi, i, false)); for (j = 0; j < SIT_VBLOCK_MAP_SIZE; j++) seq_printf(seq, " %.2x", se->cur_valid_map[j]); seq_putc(seq, '\n'); } return 0; } #define F2FS_PROC_FILE_DEF(_name) \ static int _name##_open_fs(struct inode *inode, struct file *file) \ { \ return single_open(file, _name##_seq_show, PDE_DATA(inode)); \ } \ \ static const struct file_operations f2fs_seq_##_name##_fops = { \ .open = _name##_open_fs, \ .read = seq_read, \ .llseek = seq_lseek, \ .release = single_release, \ }; F2FS_PROC_FILE_DEF(segment_info); F2FS_PROC_FILE_DEF(segment_bits); static void default_options(struct f2fs_sb_info *sbi) { /* init some FS parameters */ sbi->active_logs = NR_CURSEG_TYPE; set_opt(sbi, BG_GC); set_opt(sbi, INLINE_XATTR); set_opt(sbi, INLINE_DATA); set_opt(sbi, INLINE_DENTRY); set_opt(sbi, EXTENT_CACHE); set_opt(sbi, NOHEAP); sbi->sb->s_flags |= MS_LAZYTIME; set_opt(sbi, FLUSH_MERGE); if (f2fs_sb_mounted_blkzoned(sbi->sb)) { set_opt_mode(sbi, F2FS_MOUNT_LFS); set_opt(sbi, DISCARD); } else { set_opt_mode(sbi, F2FS_MOUNT_ADAPTIVE); } #ifdef CONFIG_F2FS_FS_XATTR set_opt(sbi, XATTR_USER); #endif #ifdef CONFIG_F2FS_FS_POSIX_ACL set_opt(sbi, POSIX_ACL); #endif #ifdef CONFIG_F2FS_FAULT_INJECTION f2fs_build_fault_attr(sbi, 0); #endif } static int f2fs_remount(struct super_block *sb, int *flags, char *data) { struct f2fs_sb_info *sbi = F2FS_SB(sb); struct f2fs_mount_info org_mount_opt; int err, active_logs; bool need_restart_gc = false; bool need_stop_gc = false; bool no_extent_cache = !test_opt(sbi, EXTENT_CACHE); #ifdef CONFIG_F2FS_FAULT_INJECTION struct f2fs_fault_info ffi = sbi->fault_info; #endif /* * Save the old mount options in case we * need to restore them. */ org_mount_opt = sbi->mount_opt; active_logs = sbi->active_logs; /* recover superblocks we couldn't write due to previous RO mount */ if (!(*flags & MS_RDONLY) && is_sbi_flag_set(sbi, SBI_NEED_SB_WRITE)) { err = f2fs_commit_super(sbi, false); f2fs_msg(sb, KERN_INFO, "Try to recover all the superblocks, ret: %d", err); if (!err) clear_sbi_flag(sbi, SBI_NEED_SB_WRITE); } sbi->mount_opt.opt = 0; default_options(sbi); /* parse mount options */ err = parse_options(sb, data); if (err) goto restore_opts; /* * Previous and new state of filesystem is RO, * so skip checking GC and FLUSH_MERGE conditions. */ if (f2fs_readonly(sb) && (*flags & MS_RDONLY)) goto skip; /* disallow enable/disable extent_cache dynamically */ if (no_extent_cache == !!test_opt(sbi, EXTENT_CACHE)) { err = -EINVAL; f2fs_msg(sbi->sb, KERN_WARNING, "switch extent_cache option is not allowed"); goto restore_opts; } /* * We stop the GC thread if FS is mounted as RO * or if background_gc = off is passed in mount * option. Also sync the filesystem. */ if ((*flags & MS_RDONLY) || !test_opt(sbi, BG_GC)) { if (sbi->gc_thread) { stop_gc_thread(sbi); need_restart_gc = true; } } else if (!sbi->gc_thread) { err = start_gc_thread(sbi); if (err) goto restore_opts; need_stop_gc = true; } if (*flags & MS_RDONLY) { writeback_inodes_sb(sb, WB_REASON_SYNC); sync_inodes_sb(sb); set_sbi_flag(sbi, SBI_IS_DIRTY); set_sbi_flag(sbi, SBI_IS_CLOSE); f2fs_sync_fs(sb, 1); clear_sbi_flag(sbi, SBI_IS_CLOSE); } /* * We stop issue flush thread if FS is mounted as RO * or if flush_merge is not passed in mount option. */ if ((*flags & MS_RDONLY) || !test_opt(sbi, FLUSH_MERGE)) { clear_opt(sbi, FLUSH_MERGE); destroy_flush_cmd_control(sbi, false); } else { err = create_flush_cmd_control(sbi); if (err) goto restore_gc; } skip: /* Update the POSIXACL Flag */ sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | (test_opt(sbi, POSIX_ACL) ? MS_POSIXACL : 0); return 0; restore_gc: if (need_restart_gc) { if (start_gc_thread(sbi)) f2fs_msg(sbi->sb, KERN_WARNING, "background gc thread has stopped"); } else if (need_stop_gc) { stop_gc_thread(sbi); } restore_opts: sbi->mount_opt = org_mount_opt; sbi->active_logs = active_logs; #ifdef CONFIG_F2FS_FAULT_INJECTION sbi->fault_info = ffi; #endif return err; } static struct super_operations f2fs_sops = { .alloc_inode = f2fs_alloc_inode, .drop_inode = f2fs_drop_inode, .destroy_inode = f2fs_destroy_inode, .write_inode = f2fs_write_inode, .dirty_inode = f2fs_dirty_inode, .show_options = f2fs_show_options, .evict_inode = f2fs_evict_inode, .put_super = f2fs_put_super, .sync_fs = f2fs_sync_fs, .freeze_fs = f2fs_freeze, .unfreeze_fs = f2fs_unfreeze, .statfs = f2fs_statfs, .remount_fs = f2fs_remount, }; #ifdef CONFIG_F2FS_FS_ENCRYPTION static int f2fs_get_context(struct inode *inode, void *ctx, size_t len) { return f2fs_getxattr(inode, F2FS_XATTR_INDEX_ENCRYPTION, F2FS_XATTR_NAME_ENCRYPTION_CONTEXT, ctx, len, NULL); } static int f2fs_set_context(struct inode *inode, const void *ctx, size_t len, void *fs_data) { return f2fs_setxattr(inode, F2FS_XATTR_INDEX_ENCRYPTION, F2FS_XATTR_NAME_ENCRYPTION_CONTEXT, ctx, len, fs_data, XATTR_CREATE); } static unsigned f2fs_max_namelen(struct inode *inode) { return S_ISLNK(inode->i_mode) ? inode->i_sb->s_blocksize : F2FS_NAME_LEN; } static const struct fscrypt_operations f2fs_cryptops = { .key_prefix = "f2fs:", .get_context = f2fs_get_context, .set_context = f2fs_set_context, .is_encrypted = f2fs_encrypted_inode, .empty_dir = f2fs_empty_dir, .max_namelen = f2fs_max_namelen, }; #else static const struct fscrypt_operations f2fs_cryptops = { .is_encrypted = f2fs_encrypted_inode, }; #endif static struct inode *f2fs_nfs_get_inode(struct super_block *sb, u64 ino, u32 generation) { struct f2fs_sb_info *sbi = F2FS_SB(sb); struct inode *inode; if (check_nid_range(sbi, ino)) return ERR_PTR(-ESTALE); /* * f2fs_iget isn't quite right if the inode is currently unallocated! * However f2fs_iget currently does appropriate checks to handle stale * inodes so everything is OK. */ inode = f2fs_iget(sb, ino); if (IS_ERR(inode)) return ERR_CAST(inode); if (unlikely(generation && inode->i_generation != generation)) { /* we didn't find the right inode.. */ iput(inode); return ERR_PTR(-ESTALE); } return inode; } static struct dentry *f2fs_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, f2fs_nfs_get_inode); } static struct dentry *f2fs_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, f2fs_nfs_get_inode); } static const struct export_operations f2fs_export_ops = { .fh_to_dentry = f2fs_fh_to_dentry, .fh_to_parent = f2fs_fh_to_parent, .get_parent = f2fs_get_parent, }; static loff_t max_file_blocks(void) { loff_t result = (DEF_ADDRS_PER_INODE - F2FS_INLINE_XATTR_ADDRS); loff_t leaf_count = ADDRS_PER_BLOCK; /* two direct node blocks */ result += (leaf_count * 2); /* two indirect node blocks */ leaf_count *= NIDS_PER_BLOCK; result += (leaf_count * 2); /* one double indirect node block */ leaf_count *= NIDS_PER_BLOCK; result += leaf_count; return result; } static int __f2fs_commit_super(struct buffer_head *bh, struct f2fs_super_block *super) { lock_buffer(bh); if (super) memcpy(bh->b_data + F2FS_SUPER_OFFSET, super, sizeof(*super)); set_buffer_uptodate(bh); set_buffer_dirty(bh); unlock_buffer(bh); /* it's rare case, we can do fua all the time */ return __sync_dirty_buffer(bh, REQ_SYNC | REQ_PREFLUSH | REQ_FUA); } static inline bool sanity_check_area_boundary(struct f2fs_sb_info *sbi, struct buffer_head *bh) { struct f2fs_super_block *raw_super = (struct f2fs_super_block *) (bh->b_data + F2FS_SUPER_OFFSET); struct super_block *sb = sbi->sb; u32 segment0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr); u32 cp_blkaddr = le32_to_cpu(raw_super->cp_blkaddr); u32 sit_blkaddr = le32_to_cpu(raw_super->sit_blkaddr); u32 nat_blkaddr = le32_to_cpu(raw_super->nat_blkaddr); u32 ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr); u32 main_blkaddr = le32_to_cpu(raw_super->main_blkaddr); u32 segment_count_ckpt = le32_to_cpu(raw_super->segment_count_ckpt); u32 segment_count_sit = le32_to_cpu(raw_super->segment_count_sit); u32 segment_count_nat = le32_to_cpu(raw_super->segment_count_nat); u32 segment_count_ssa = le32_to_cpu(raw_super->segment_count_ssa); u32 segment_count_main = le32_to_cpu(raw_super->segment_count_main); u32 segment_count = le32_to_cpu(raw_super->segment_count); u32 log_blocks_per_seg = le32_to_cpu(raw_super->log_blocks_per_seg); u64 main_end_blkaddr = main_blkaddr + (segment_count_main << log_blocks_per_seg); u64 seg_end_blkaddr = segment0_blkaddr + (segment_count << log_blocks_per_seg); if (segment0_blkaddr != cp_blkaddr) { f2fs_msg(sb, KERN_INFO, "Mismatch start address, segment0(%u) cp_blkaddr(%u)", segment0_blkaddr, cp_blkaddr); return true; } if (cp_blkaddr + (segment_count_ckpt << log_blocks_per_seg) != sit_blkaddr) { f2fs_msg(sb, KERN_INFO, "Wrong CP boundary, start(%u) end(%u) blocks(%u)", cp_blkaddr, sit_blkaddr, segment_count_ckpt << log_blocks_per_seg); return true; } if (sit_blkaddr + (segment_count_sit << log_blocks_per_seg) != nat_blkaddr) { f2fs_msg(sb, KERN_INFO, "Wrong SIT boundary, start(%u) end(%u) blocks(%u)", sit_blkaddr, nat_blkaddr, segment_count_sit << log_blocks_per_seg); return true; } if (nat_blkaddr + (segment_count_nat << log_blocks_per_seg) != ssa_blkaddr) { f2fs_msg(sb, KERN_INFO, "Wrong NAT boundary, start(%u) end(%u) blocks(%u)", nat_blkaddr, ssa_blkaddr, segment_count_nat << log_blocks_per_seg); return true; } if (ssa_blkaddr + (segment_count_ssa << log_blocks_per_seg) != main_blkaddr) { f2fs_msg(sb, KERN_INFO, "Wrong SSA boundary, start(%u) end(%u) blocks(%u)", ssa_blkaddr, main_blkaddr, segment_count_ssa << log_blocks_per_seg); return true; } if (main_end_blkaddr > seg_end_blkaddr) { f2fs_msg(sb, KERN_INFO, "Wrong MAIN_AREA boundary, start(%u) end(%u) block(%u)", main_blkaddr, segment0_blkaddr + (segment_count << log_blocks_per_seg), segment_count_main << log_blocks_per_seg); return true; } else if (main_end_blkaddr < seg_end_blkaddr) { int err = 0; char *res; /* fix in-memory information all the time */ raw_super->segment_count = cpu_to_le32((main_end_blkaddr - segment0_blkaddr) >> log_blocks_per_seg); if (f2fs_readonly(sb) || bdev_read_only(sb->s_bdev)) { set_sbi_flag(sbi, SBI_NEED_SB_WRITE); res = "internally"; } else { err = __f2fs_commit_super(bh, NULL); res = err ? "failed" : "done"; } f2fs_msg(sb, KERN_INFO, "Fix alignment : %s, start(%u) end(%u) block(%u)", res, main_blkaddr, segment0_blkaddr + (segment_count << log_blocks_per_seg), segment_count_main << log_blocks_per_seg); if (err) return true; } return false; } static int sanity_check_raw_super(struct f2fs_sb_info *sbi, struct buffer_head *bh) { struct f2fs_super_block *raw_super = (struct f2fs_super_block *) (bh->b_data + F2FS_SUPER_OFFSET); struct super_block *sb = sbi->sb; unsigned int blocksize; if (F2FS_SUPER_MAGIC != le32_to_cpu(raw_super->magic)) { f2fs_msg(sb, KERN_INFO, "Magic Mismatch, valid(0x%x) - read(0x%x)", F2FS_SUPER_MAGIC, le32_to_cpu(raw_super->magic)); return 1; } /* Currently, support only 4KB page cache size */ if (F2FS_BLKSIZE != PAGE_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid page_cache_size (%lu), supports only 4KB\n", PAGE_SIZE); return 1; } /* Currently, support only 4KB block size */ blocksize = 1 << le32_to_cpu(raw_super->log_blocksize); if (blocksize != F2FS_BLKSIZE) { f2fs_msg(sb, KERN_INFO, "Invalid blocksize (%u), supports only 4KB\n", blocksize); return 1; } /* check log blocks per segment */ if (le32_to_cpu(raw_super->log_blocks_per_seg) != 9) { f2fs_msg(sb, KERN_INFO, "Invalid log blocks per segment (%u)\n", le32_to_cpu(raw_super->log_blocks_per_seg)); return 1; } /* Currently, support 512/1024/2048/4096 bytes sector size */ if (le32_to_cpu(raw_super->log_sectorsize) > F2FS_MAX_LOG_SECTOR_SIZE || le32_to_cpu(raw_super->log_sectorsize) < F2FS_MIN_LOG_SECTOR_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid log sectorsize (%u)", le32_to_cpu(raw_super->log_sectorsize)); return 1; } if (le32_to_cpu(raw_super->log_sectors_per_block) + le32_to_cpu(raw_super->log_sectorsize) != F2FS_MAX_LOG_SECTOR_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid log sectors per block(%u) log sectorsize(%u)", le32_to_cpu(raw_super->log_sectors_per_block), le32_to_cpu(raw_super->log_sectorsize)); return 1; } /* check reserved ino info */ if (le32_to_cpu(raw_super->node_ino) != 1 || le32_to_cpu(raw_super->meta_ino) != 2 || le32_to_cpu(raw_super->root_ino) != 3) { f2fs_msg(sb, KERN_INFO, "Invalid Fs Meta Ino: node(%u) meta(%u) root(%u)", le32_to_cpu(raw_super->node_ino), le32_to_cpu(raw_super->meta_ino), le32_to_cpu(raw_super->root_ino)); return 1; } if (le32_to_cpu(raw_super->segment_count) > F2FS_MAX_SEGMENT) { f2fs_msg(sb, KERN_INFO, "Invalid segment count (%u)", le32_to_cpu(raw_super->segment_count)); return 1; } /* check CP/SIT/NAT/SSA/MAIN_AREA area boundary */ if (sanity_check_area_boundary(sbi, bh)) return 1; return 0; } int sanity_check_ckpt(struct f2fs_sb_info *sbi) { unsigned int total, fsmeta; struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi); struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); unsigned int ovp_segments, reserved_segments; total = le32_to_cpu(raw_super->segment_count); fsmeta = le32_to_cpu(raw_super->segment_count_ckpt); fsmeta += le32_to_cpu(raw_super->segment_count_sit); fsmeta += le32_to_cpu(raw_super->segment_count_nat); fsmeta += le32_to_cpu(ckpt->rsvd_segment_count); fsmeta += le32_to_cpu(raw_super->segment_count_ssa); if (unlikely(fsmeta >= total)) return 1; ovp_segments = le32_to_cpu(ckpt->overprov_segment_count); reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count); if (unlikely(fsmeta < F2FS_MIN_SEGMENTS || ovp_segments == 0 || reserved_segments == 0)) { f2fs_msg(sbi->sb, KERN_ERR, "Wrong layout: check mkfs.f2fs version"); return 1; } if (unlikely(f2fs_cp_error(sbi))) { f2fs_msg(sbi->sb, KERN_ERR, "A bug case: need to run fsck"); return 1; } return 0; } static void init_sb_info(struct f2fs_sb_info *sbi) { struct f2fs_super_block *raw_super = sbi->raw_super; int i; sbi->log_sectors_per_block = le32_to_cpu(raw_super->log_sectors_per_block); sbi->log_blocksize = le32_to_cpu(raw_super->log_blocksize); sbi->blocksize = 1 << sbi->log_blocksize; sbi->log_blocks_per_seg = le32_to_cpu(raw_super->log_blocks_per_seg); sbi->blocks_per_seg = 1 << sbi->log_blocks_per_seg; sbi->segs_per_sec = le32_to_cpu(raw_super->segs_per_sec); sbi->secs_per_zone = le32_to_cpu(raw_super->secs_per_zone); sbi->total_sections = le32_to_cpu(raw_super->section_count); sbi->total_node_count = (le32_to_cpu(raw_super->segment_count_nat) / 2) * sbi->blocks_per_seg * NAT_ENTRY_PER_BLOCK; sbi->root_ino_num = le32_to_cpu(raw_super->root_ino); sbi->node_ino_num = le32_to_cpu(raw_super->node_ino); sbi->meta_ino_num = le32_to_cpu(raw_super->meta_ino); sbi->cur_victim_sec = NULL_SECNO; sbi->max_victim_search = DEF_MAX_VICTIM_SEARCH; sbi->dir_level = DEF_DIR_LEVEL; sbi->interval_time[CP_TIME] = DEF_CP_INTERVAL; sbi->interval_time[REQ_TIME] = DEF_IDLE_INTERVAL; clear_sbi_flag(sbi, SBI_NEED_FSCK); for (i = 0; i < NR_COUNT_TYPE; i++) atomic_set(&sbi->nr_pages[i], 0); atomic_set(&sbi->wb_sync_req, 0); INIT_LIST_HEAD(&sbi->s_list); mutex_init(&sbi->umount_mutex); mutex_init(&sbi->wio_mutex[NODE]); mutex_init(&sbi->wio_mutex[DATA]); spin_lock_init(&sbi->cp_lock); } static int init_percpu_info(struct f2fs_sb_info *sbi) { int err; err = percpu_counter_init(&sbi->alloc_valid_block_count, 0, GFP_KERNEL); if (err) return err; return percpu_counter_init(&sbi->total_valid_inode_count, 0, GFP_KERNEL); } #ifdef CONFIG_BLK_DEV_ZONED static int init_blkz_info(struct f2fs_sb_info *sbi, int devi) { struct block_device *bdev = FDEV(devi).bdev; sector_t nr_sectors = bdev->bd_part->nr_sects; sector_t sector = 0; struct blk_zone *zones; unsigned int i, nr_zones; unsigned int n = 0; int err = -EIO; if (!f2fs_sb_mounted_blkzoned(sbi->sb)) return 0; if (sbi->blocks_per_blkz && sbi->blocks_per_blkz != SECTOR_TO_BLOCK(bdev_zone_sectors(bdev))) return -EINVAL; sbi->blocks_per_blkz = SECTOR_TO_BLOCK(bdev_zone_sectors(bdev)); if (sbi->log_blocks_per_blkz && sbi->log_blocks_per_blkz != __ilog2_u32(sbi->blocks_per_blkz)) return -EINVAL; sbi->log_blocks_per_blkz = __ilog2_u32(sbi->blocks_per_blkz); FDEV(devi).nr_blkz = SECTOR_TO_BLOCK(nr_sectors) >> sbi->log_blocks_per_blkz; if (nr_sectors & (bdev_zone_sectors(bdev) - 1)) FDEV(devi).nr_blkz++; FDEV(devi).blkz_type = kmalloc(FDEV(devi).nr_blkz, GFP_KERNEL); if (!FDEV(devi).blkz_type) return -ENOMEM; #define F2FS_REPORT_NR_ZONES 4096 zones = kcalloc(F2FS_REPORT_NR_ZONES, sizeof(struct blk_zone), GFP_KERNEL); if (!zones) return -ENOMEM; /* Get block zones type */ while (zones && sector < nr_sectors) { nr_zones = F2FS_REPORT_NR_ZONES; err = blkdev_report_zones(bdev, sector, zones, &nr_zones, GFP_KERNEL); if (err) break; if (!nr_zones) { err = -EIO; break; } for (i = 0; i < nr_zones; i++) { FDEV(devi).blkz_type[n] = zones[i].type; sector += zones[i].len; n++; } } kfree(zones); return err; } #endif /* * Read f2fs raw super block. * Because we have two copies of super block, so read both of them * to get the first valid one. If any one of them is broken, we pass * them recovery flag back to the caller. */ static int read_raw_super_block(struct f2fs_sb_info *sbi, struct f2fs_super_block **raw_super, int *valid_super_block, int *recovery) { struct super_block *sb = sbi->sb; int block; struct buffer_head *bh; struct f2fs_super_block *super; int err = 0; super = kzalloc(sizeof(struct f2fs_super_block), GFP_KERNEL); if (!super) return -ENOMEM; for (block = 0; block < 2; block++) { bh = sb_bread(sb, block); if (!bh) { f2fs_msg(sb, KERN_ERR, "Unable to read %dth superblock", block + 1); err = -EIO; continue; } /* sanity checking of raw super */ if (sanity_check_raw_super(sbi, bh)) { f2fs_msg(sb, KERN_ERR, "Can't find valid F2FS filesystem in %dth superblock", block + 1); err = -EINVAL; brelse(bh); continue; } if (!*raw_super) { memcpy(super, bh->b_data + F2FS_SUPER_OFFSET, sizeof(*super)); *valid_super_block = block; *raw_super = super; } brelse(bh); } /* Fail to read any one of the superblocks*/ if (err < 0) *recovery = 1; /* No valid superblock */ if (!*raw_super) kfree(super); else err = 0; return err; } int f2fs_commit_super(struct f2fs_sb_info *sbi, bool recover) { struct buffer_head *bh; int err; if ((recover && f2fs_readonly(sbi->sb)) || bdev_read_only(sbi->sb->s_bdev)) { set_sbi_flag(sbi, SBI_NEED_SB_WRITE); return -EROFS; } /* write back-up superblock first */ bh = sb_getblk(sbi->sb, sbi->valid_super_block ? 0: 1); if (!bh) return -EIO; err = __f2fs_commit_super(bh, F2FS_RAW_SUPER(sbi)); brelse(bh); /* if we are in recovery path, skip writing valid superblock */ if (recover || err) return err; /* write current valid superblock */ bh = sb_getblk(sbi->sb, sbi->valid_super_block); if (!bh) return -EIO; err = __f2fs_commit_super(bh, F2FS_RAW_SUPER(sbi)); brelse(bh); return err; } static int f2fs_scan_devices(struct f2fs_sb_info *sbi) { struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi); unsigned int max_devices = MAX_DEVICES; int i; /* Initialize single device information */ if (!RDEV(0).path[0]) { if (!bdev_is_zoned(sbi->sb->s_bdev)) return 0; max_devices = 1; } /* * Initialize multiple devices information, or single * zoned block device information. */ sbi->devs = kcalloc(max_devices, sizeof(struct f2fs_dev_info), GFP_KERNEL); if (!sbi->devs) return -ENOMEM; for (i = 0; i < max_devices; i++) { if (i > 0 && !RDEV(i).path[0]) break; if (max_devices == 1) { /* Single zoned block device mount */ FDEV(0).bdev = blkdev_get_by_dev(sbi->sb->s_bdev->bd_dev, sbi->sb->s_mode, sbi->sb->s_type); } else { /* Multi-device mount */ memcpy(FDEV(i).path, RDEV(i).path, MAX_PATH_LEN); FDEV(i).total_segments = le32_to_cpu(RDEV(i).total_segments); if (i == 0) { FDEV(i).start_blk = 0; FDEV(i).end_blk = FDEV(i).start_blk + (FDEV(i).total_segments << sbi->log_blocks_per_seg) - 1 + le32_to_cpu(raw_super->segment0_blkaddr); } else { FDEV(i).start_blk = FDEV(i - 1).end_blk + 1; FDEV(i).end_blk = FDEV(i).start_blk + (FDEV(i).total_segments << sbi->log_blocks_per_seg) - 1; } FDEV(i).bdev = blkdev_get_by_path(FDEV(i).path, sbi->sb->s_mode, sbi->sb->s_type); } if (IS_ERR(FDEV(i).bdev)) return PTR_ERR(FDEV(i).bdev); /* to release errored devices */ sbi->s_ndevs = i + 1; #ifdef CONFIG_BLK_DEV_ZONED if (bdev_zoned_model(FDEV(i).bdev) == BLK_ZONED_HM && !f2fs_sb_mounted_blkzoned(sbi->sb)) { f2fs_msg(sbi->sb, KERN_ERR, "Zoned block device feature not enabled\n"); return -EINVAL; } if (bdev_zoned_model(FDEV(i).bdev) != BLK_ZONED_NONE) { if (init_blkz_info(sbi, i)) { f2fs_msg(sbi->sb, KERN_ERR, "Failed to initialize F2FS blkzone information"); return -EINVAL; } if (max_devices == 1) break; f2fs_msg(sbi->sb, KERN_INFO, "Mount Device [%2d]: %20s, %8u, %8x - %8x (zone: %s)", i, FDEV(i).path, FDEV(i).total_segments, FDEV(i).start_blk, FDEV(i).end_blk, bdev_zoned_model(FDEV(i).bdev) == BLK_ZONED_HA ? "Host-aware" : "Host-managed"); continue; } #endif f2fs_msg(sbi->sb, KERN_INFO, "Mount Device [%2d]: %20s, %8u, %8x - %8x", i, FDEV(i).path, FDEV(i).total_segments, FDEV(i).start_blk, FDEV(i).end_blk); } f2fs_msg(sbi->sb, KERN_INFO, "IO Block Size: %8d KB", F2FS_IO_SIZE_KB(sbi)); return 0; } static int f2fs_fill_super(struct super_block *sb, void *data, int silent) { struct f2fs_sb_info *sbi; struct f2fs_super_block *raw_super; struct inode *root; int err; bool retry = true, need_fsck = false; char *options = NULL; int recovery, i, valid_super_block; struct curseg_info *seg_i; try_onemore: err = -EINVAL; raw_super = NULL; valid_super_block = -1; recovery = 0; /* allocate memory for f2fs-specific super block info */ sbi = kzalloc(sizeof(struct f2fs_sb_info), GFP_KERNEL); if (!sbi) return -ENOMEM; sbi->sb = sb; /* Load the checksum driver */ sbi->s_chksum_driver = crypto_alloc_shash("crc32", 0, 0); if (IS_ERR(sbi->s_chksum_driver)) { f2fs_msg(sb, KERN_ERR, "Cannot load crc32 driver."); err = PTR_ERR(sbi->s_chksum_driver); sbi->s_chksum_driver = NULL; goto free_sbi; } /* set a block size */ if (unlikely(!sb_set_blocksize(sb, F2FS_BLKSIZE))) { f2fs_msg(sb, KERN_ERR, "unable to set blocksize"); goto free_sbi; } err = read_raw_super_block(sbi, &raw_super, &valid_super_block, &recovery); if (err) goto free_sbi; sb->s_fs_info = sbi; sbi->raw_super = raw_super; /* * The BLKZONED feature indicates that the drive was formatted with * zone alignment optimization. This is optional for host-aware * devices, but mandatory for host-managed zoned block devices. */ #ifndef CONFIG_BLK_DEV_ZONED if (f2fs_sb_mounted_blkzoned(sb)) { f2fs_msg(sb, KERN_ERR, "Zoned block device support is not enabled\n"); goto free_sb_buf; } #endif default_options(sbi); /* parse mount options */ options = kstrdup((const char *)data, GFP_KERNEL); if (data && !options) { err = -ENOMEM; goto free_sb_buf; } err = parse_options(sb, options); if (err) goto free_options; sbi->max_file_blocks = max_file_blocks(); sb->s_maxbytes = sbi->max_file_blocks << le32_to_cpu(raw_super->log_blocksize); sb->s_max_links = F2FS_LINK_MAX; get_random_bytes(&sbi->s_next_generation, sizeof(u32)); sb->s_op = &f2fs_sops; sb->s_cop = &f2fs_cryptops; sb->s_xattr = f2fs_xattr_handlers; sb->s_export_op = &f2fs_export_ops; sb->s_magic = F2FS_SUPER_MAGIC; sb->s_time_gran = 1; sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | (test_opt(sbi, POSIX_ACL) ? MS_POSIXACL : 0); memcpy(sb->s_uuid, raw_super->uuid, sizeof(raw_super->uuid)); /* init f2fs-specific super block info */ sbi->valid_super_block = valid_super_block; mutex_init(&sbi->gc_mutex); mutex_init(&sbi->cp_mutex); init_rwsem(&sbi->node_write); init_rwsem(&sbi->node_change); /* disallow all the data/node/meta page writes */ set_sbi_flag(sbi, SBI_POR_DOING); spin_lock_init(&sbi->stat_lock); init_rwsem(&sbi->read_io.io_rwsem); sbi->read_io.sbi = sbi; sbi->read_io.bio = NULL; for (i = 0; i < NR_PAGE_TYPE; i++) { init_rwsem(&sbi->write_io[i].io_rwsem); sbi->write_io[i].sbi = sbi; sbi->write_io[i].bio = NULL; } init_rwsem(&sbi->cp_rwsem); init_waitqueue_head(&sbi->cp_wait); init_sb_info(sbi); err = init_percpu_info(sbi); if (err) goto free_options; if (F2FS_IO_SIZE(sbi) > 1) { sbi->write_io_dummy = mempool_create_page_pool(2 * (F2FS_IO_SIZE(sbi) - 1), 0); if (!sbi->write_io_dummy) goto free_options; } /* get an inode for meta space */ sbi->meta_inode = f2fs_iget(sb, F2FS_META_INO(sbi)); if (IS_ERR(sbi->meta_inode)) { f2fs_msg(sb, KERN_ERR, "Failed to read F2FS meta data inode"); err = PTR_ERR(sbi->meta_inode); goto free_io_dummy; } err = get_valid_checkpoint(sbi); if (err) { f2fs_msg(sb, KERN_ERR, "Failed to get valid F2FS checkpoint"); goto free_meta_inode; } /* Initialize device list */ err = f2fs_scan_devices(sbi); if (err) { f2fs_msg(sb, KERN_ERR, "Failed to find devices"); goto free_devices; } sbi->total_valid_node_count = le32_to_cpu(sbi->ckpt->valid_node_count); percpu_counter_set(&sbi->total_valid_inode_count, le32_to_cpu(sbi->ckpt->valid_inode_count)); sbi->user_block_count = le64_to_cpu(sbi->ckpt->user_block_count); sbi->total_valid_block_count = le64_to_cpu(sbi->ckpt->valid_block_count); sbi->last_valid_block_count = sbi->total_valid_block_count; for (i = 0; i < NR_INODE_TYPE; i++) { INIT_LIST_HEAD(&sbi->inode_list[i]); spin_lock_init(&sbi->inode_lock[i]); } init_extent_cache_info(sbi); init_ino_entry_info(sbi); /* setup f2fs internal modules */ err = build_segment_manager(sbi); if (err) { f2fs_msg(sb, KERN_ERR, "Failed to initialize F2FS segment manager"); goto free_sm; } err = build_node_manager(sbi); if (err) { f2fs_msg(sb, KERN_ERR, "Failed to initialize F2FS node manager"); goto free_nm; } /* For write statistics */ if (sb->s_bdev->bd_part) sbi->sectors_written_start = (u64)part_stat_read(sb->s_bdev->bd_part, sectors[1]); /* Read accumulated write IO statistics if exists */ seg_i = CURSEG_I(sbi, CURSEG_HOT_NODE); if (__exist_node_summaries(sbi)) sbi->kbytes_written = le64_to_cpu(seg_i->journal->info.kbytes_written); build_gc_manager(sbi); /* get an inode for node space */ sbi->node_inode = f2fs_iget(sb, F2FS_NODE_INO(sbi)); if (IS_ERR(sbi->node_inode)) { f2fs_msg(sb, KERN_ERR, "Failed to read node inode"); err = PTR_ERR(sbi->node_inode); goto free_nm; } f2fs_join_shrinker(sbi); err = f2fs_build_stats(sbi); if (err) goto free_nm; /* if there are nt orphan nodes free them */ err = recover_orphan_inodes(sbi); if (err) goto free_node_inode; /* read root inode and dentry */ root = f2fs_iget(sb, F2FS_ROOT_INO(sbi)); if (IS_ERR(root)) { f2fs_msg(sb, KERN_ERR, "Failed to read root inode"); err = PTR_ERR(root); goto free_node_inode; } if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) { iput(root); err = -EINVAL; goto free_node_inode; } sb->s_root = d_make_root(root); /* allocate root dentry */ if (!sb->s_root) { err = -ENOMEM; goto free_root_inode; } if (f2fs_proc_root) sbi->s_proc = proc_mkdir(sb->s_id, f2fs_proc_root); if (sbi->s_proc) { proc_create_data("segment_info", S_IRUGO, sbi->s_proc, &f2fs_seq_segment_info_fops, sb); proc_create_data("segment_bits", S_IRUGO, sbi->s_proc, &f2fs_seq_segment_bits_fops, sb); } sbi->s_kobj.kset = f2fs_kset; init_completion(&sbi->s_kobj_unregister); err = kobject_init_and_add(&sbi->s_kobj, &f2fs_ktype, NULL, "%s", sb->s_id); if (err) goto free_proc; /* recover fsynced data */ if (!test_opt(sbi, DISABLE_ROLL_FORWARD)) { /* * mount should be failed, when device has readonly mode, and * previous checkpoint was not done by clean system shutdown. */ if (bdev_read_only(sb->s_bdev) && !is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) { err = -EROFS; goto free_kobj; } if (need_fsck) set_sbi_flag(sbi, SBI_NEED_FSCK); if (!retry) goto skip_recovery; err = recover_fsync_data(sbi, false); if (err < 0) { need_fsck = true; f2fs_msg(sb, KERN_ERR, "Cannot recover all fsync data errno=%d", err); goto free_kobj; } } else { err = recover_fsync_data(sbi, true); if (!f2fs_readonly(sb) && err > 0) { err = -EINVAL; f2fs_msg(sb, KERN_ERR, "Need to recover fsync data"); goto free_kobj; } } skip_recovery: /* recover_fsync_data() cleared this already */ clear_sbi_flag(sbi, SBI_POR_DOING); /* * If filesystem is not mounted as read-only then * do start the gc_thread. */ if (test_opt(sbi, BG_GC) && !f2fs_readonly(sb)) { /* After POR, we can run background GC thread.*/ err = start_gc_thread(sbi); if (err) goto free_kobj; } kfree(options); /* recover broken superblock */ if (recovery) { err = f2fs_commit_super(sbi, true); f2fs_msg(sb, KERN_INFO, "Try to recover %dth superblock, ret: %d", sbi->valid_super_block ? 1 : 2, err); } f2fs_msg(sbi->sb, KERN_NOTICE, "Mounted with checkpoint version = %llx", cur_cp_version(F2FS_CKPT(sbi))); f2fs_update_time(sbi, CP_TIME); f2fs_update_time(sbi, REQ_TIME); return 0; free_kobj: f2fs_sync_inode_meta(sbi); kobject_del(&sbi->s_kobj); kobject_put(&sbi->s_kobj); wait_for_completion(&sbi->s_kobj_unregister); free_proc: if (sbi->s_proc) { remove_proc_entry("segment_info", sbi->s_proc); remove_proc_entry("segment_bits", sbi->s_proc); remove_proc_entry(sb->s_id, f2fs_proc_root); } free_root_inode: dput(sb->s_root); sb->s_root = NULL; free_node_inode: truncate_inode_pages_final(NODE_MAPPING(sbi)); mutex_lock(&sbi->umount_mutex); release_ino_entry(sbi, true); f2fs_leave_shrinker(sbi); /* * Some dirty meta pages can be produced by recover_orphan_inodes() * failed by EIO. Then, iput(node_inode) can trigger balance_fs_bg() * followed by write_checkpoint() through f2fs_write_node_pages(), which * falls into an infinite loop in sync_meta_pages(). */ truncate_inode_pages_final(META_MAPPING(sbi)); iput(sbi->node_inode); mutex_unlock(&sbi->umount_mutex); f2fs_destroy_stats(sbi); free_nm: destroy_node_manager(sbi); free_sm: destroy_segment_manager(sbi); free_devices: destroy_device_list(sbi); kfree(sbi->ckpt); free_meta_inode: make_bad_inode(sbi->meta_inode); iput(sbi->meta_inode); free_io_dummy: mempool_destroy(sbi->write_io_dummy); free_options: destroy_percpu_info(sbi); kfree(options); free_sb_buf: kfree(raw_super); free_sbi: if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); kfree(sbi); /* give only one another chance */ if (retry) { retry = false; shrink_dcache_sb(sb); goto try_onemore; } return err; } static struct dentry *f2fs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_bdev(fs_type, flags, dev_name, data, f2fs_fill_super); } static void kill_f2fs_super(struct super_block *sb) { if (sb->s_root) set_sbi_flag(F2FS_SB(sb), SBI_IS_CLOSE); kill_block_super(sb); } static struct file_system_type f2fs_fs_type = { .owner = THIS_MODULE, .name = "f2fs", .mount = f2fs_mount, .kill_sb = kill_f2fs_super, .fs_flags = FS_REQUIRES_DEV, }; MODULE_ALIAS_FS("f2fs"); static int __init init_inodecache(void) { f2fs_inode_cachep = kmem_cache_create("f2fs_inode_cache", sizeof(struct f2fs_inode_info), 0, SLAB_RECLAIM_ACCOUNT|SLAB_ACCOUNT, NULL); if (!f2fs_inode_cachep) 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(f2fs_inode_cachep); } static int __init init_f2fs_fs(void) { int err; f2fs_build_trace_ios(); err = init_inodecache(); if (err) goto fail; err = create_node_manager_caches(); if (err) goto free_inodecache; err = create_segment_manager_caches(); if (err) goto free_node_manager_caches; err = create_checkpoint_caches(); if (err) goto free_segment_manager_caches; err = create_extent_cache(); if (err) goto free_checkpoint_caches; f2fs_kset = kset_create_and_add("f2fs", NULL, fs_kobj); if (!f2fs_kset) { err = -ENOMEM; goto free_extent_cache; } err = register_shrinker(&f2fs_shrinker_info); if (err) goto free_kset; err = register_filesystem(&f2fs_fs_type); if (err) goto free_shrinker; err = f2fs_create_root_stats(); if (err) goto free_filesystem; f2fs_proc_root = proc_mkdir("fs/f2fs", NULL); return 0; free_filesystem: unregister_filesystem(&f2fs_fs_type); free_shrinker: unregister_shrinker(&f2fs_shrinker_info); free_kset: kset_unregister(f2fs_kset); free_extent_cache: destroy_extent_cache(); free_checkpoint_caches: destroy_checkpoint_caches(); free_segment_manager_caches: destroy_segment_manager_caches(); free_node_manager_caches: destroy_node_manager_caches(); free_inodecache: destroy_inodecache(); fail: return err; } static void __exit exit_f2fs_fs(void) { remove_proc_entry("fs/f2fs", NULL); f2fs_destroy_root_stats(); unregister_filesystem(&f2fs_fs_type); unregister_shrinker(&f2fs_shrinker_info); kset_unregister(f2fs_kset); destroy_extent_cache(); destroy_checkpoint_caches(); destroy_segment_manager_caches(); destroy_node_manager_caches(); destroy_inodecache(); f2fs_destroy_trace_ios(); } module_init(init_f2fs_fs) module_exit(exit_f2fs_fs) MODULE_AUTHOR("Samsung Electronics's Praesto Team"); MODULE_DESCRIPTION("Flash Friendly File System"); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-129/c/bad_2552_0
crossvul-cpp_data_good_1431_0
/* * nf_nat_snmp_basic.c * * Basic SNMP Application Layer Gateway * * This IP NAT module is intended for use with SNMP network * discovery and monitoring applications where target networks use * conflicting private address realms. * * Static NAT is used to remap the networks from the view of the network * management system at the IP layer, and this module remaps some application * layer addresses to match. * * The simplest form of ALG is performed, where only tagged IP addresses * are modified. The module does not need to be MIB aware and only scans * messages at the ASN.1/BER level. * * Currently, only SNMPv1 and SNMPv2 are supported. * * More information on ALG and associated issues can be found in * RFC 2962 * * The ASB.1/BER parsing code is derived from the gxsnmp package by Gregory * McLean & Jochen Friedrich, stripped down for use in the kernel. * * Copyright (c) 2000 RP Internet (www.rpi.net.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. * 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/>. * * Author: James Morris <jmorris@intercode.com.au> * * Copyright (c) 2006-2010 Patrick McHardy <kaber@trash.net> */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/in.h> #include <linux/ip.h> #include <linux/udp.h> #include <net/checksum.h> #include <net/udp.h> #include <net/netfilter/nf_nat.h> #include <net/netfilter/nf_conntrack_expect.h> #include <net/netfilter/nf_conntrack_helper.h> #include <linux/netfilter/nf_conntrack_snmp.h> #include "nf_nat_snmp_basic.asn1.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("James Morris <jmorris@intercode.com.au>"); MODULE_DESCRIPTION("Basic SNMP Application Layer Gateway"); MODULE_ALIAS("ip_nat_snmp_basic"); MODULE_ALIAS_NFCT_HELPER("snmp_trap"); #define SNMP_PORT 161 #define SNMP_TRAP_PORT 162 static DEFINE_SPINLOCK(snmp_lock); struct snmp_ctx { unsigned char *begin; __sum16 *check; __be32 from; __be32 to; }; static void fast_csum(struct snmp_ctx *ctx, unsigned char offset) { unsigned char s[12] = {0,}; int size; if (offset & 1) { memcpy(&s[1], &ctx->from, 4); memcpy(&s[7], &ctx->to, 4); s[0] = ~0; s[1] = ~s[1]; s[2] = ~s[2]; s[3] = ~s[3]; s[4] = ~s[4]; s[5] = ~0; size = 12; } else { memcpy(&s[0], &ctx->from, 4); memcpy(&s[4], &ctx->to, 4); s[0] = ~s[0]; s[1] = ~s[1]; s[2] = ~s[2]; s[3] = ~s[3]; size = 8; } *ctx->check = csum_fold(csum_partial(s, size, ~csum_unfold(*ctx->check))); } int snmp_version(void *context, size_t hdrlen, unsigned char tag, const void *data, size_t datalen) { if (datalen != 1) return -EINVAL; if (*(unsigned char *)data > 1) return -ENOTSUPP; return 1; } int snmp_helper(void *context, size_t hdrlen, unsigned char tag, const void *data, size_t datalen) { struct snmp_ctx *ctx = (struct snmp_ctx *)context; __be32 *pdata; if (datalen != 4) return -EINVAL; pdata = (__be32 *)data; if (*pdata == ctx->from) { pr_debug("%s: %pI4 to %pI4\n", __func__, (void *)&ctx->from, (void *)&ctx->to); if (*ctx->check) fast_csum(ctx, (unsigned char *)data - ctx->begin); *pdata = ctx->to; } return 1; } static int snmp_translate(struct nf_conn *ct, int dir, struct sk_buff *skb) { struct iphdr *iph = ip_hdr(skb); struct udphdr *udph = (struct udphdr *)((__be32 *)iph + iph->ihl); u16 datalen = ntohs(udph->len) - sizeof(struct udphdr); char *data = (unsigned char *)udph + sizeof(struct udphdr); struct snmp_ctx ctx; int ret; if (dir == IP_CT_DIR_ORIGINAL) { ctx.from = ct->tuplehash[dir].tuple.src.u3.ip; ctx.to = ct->tuplehash[!dir].tuple.dst.u3.ip; } else { ctx.from = ct->tuplehash[!dir].tuple.src.u3.ip; ctx.to = ct->tuplehash[dir].tuple.dst.u3.ip; } if (ctx.from == ctx.to) return NF_ACCEPT; ctx.begin = (unsigned char *)udph + sizeof(struct udphdr); ctx.check = &udph->check; ret = asn1_ber_decoder(&nf_nat_snmp_basic_decoder, &ctx, data, datalen); if (ret < 0) { nf_ct_helper_log(skb, ct, "parser failed\n"); return NF_DROP; } return NF_ACCEPT; } /* We don't actually set up expectations, just adjust internal IP * addresses if this is being NATted */ static int help(struct sk_buff *skb, unsigned int protoff, struct nf_conn *ct, enum ip_conntrack_info ctinfo) { int dir = CTINFO2DIR(ctinfo); unsigned int ret; const struct iphdr *iph = ip_hdr(skb); const struct udphdr *udph = (struct udphdr *)((__be32 *)iph + iph->ihl); /* SNMP replies and originating SNMP traps get mangled */ if (udph->source == htons(SNMP_PORT) && dir != IP_CT_DIR_REPLY) return NF_ACCEPT; if (udph->dest == htons(SNMP_TRAP_PORT) && dir != IP_CT_DIR_ORIGINAL) return NF_ACCEPT; /* No NAT? */ if (!(ct->status & IPS_NAT_MASK)) return NF_ACCEPT; /* Make sure the packet length is ok. So far, we were only guaranteed * to have a valid length IP header plus 8 bytes, which means we have * enough room for a UDP header. Just verify the UDP length field so we * can mess around with the payload. */ if (ntohs(udph->len) != skb->len - (iph->ihl << 2)) { nf_ct_helper_log(skb, ct, "dropping malformed packet\n"); return NF_DROP; } if (!skb_make_writable(skb, skb->len)) { nf_ct_helper_log(skb, ct, "cannot mangle packet"); return NF_DROP; } spin_lock_bh(&snmp_lock); ret = snmp_translate(ct, dir, skb); spin_unlock_bh(&snmp_lock); return ret; } static const struct nf_conntrack_expect_policy snmp_exp_policy = { .max_expected = 0, .timeout = 180, }; static struct nf_conntrack_helper snmp_trap_helper __read_mostly = { .me = THIS_MODULE, .help = help, .expect_policy = &snmp_exp_policy, .name = "snmp_trap", .tuple.src.l3num = AF_INET, .tuple.src.u.udp.port = cpu_to_be16(SNMP_TRAP_PORT), .tuple.dst.protonum = IPPROTO_UDP, }; static int __init nf_nat_snmp_basic_init(void) { BUG_ON(nf_nat_snmp_hook != NULL); RCU_INIT_POINTER(nf_nat_snmp_hook, help); return nf_conntrack_helper_register(&snmp_trap_helper); } static void __exit nf_nat_snmp_basic_fini(void) { RCU_INIT_POINTER(nf_nat_snmp_hook, NULL); synchronize_rcu(); nf_conntrack_helper_unregister(&snmp_trap_helper); } module_init(nf_nat_snmp_basic_init); module_exit(nf_nat_snmp_basic_fini);
./CrossVul/dataset_final_sorted/CWE-129/c/good_1431_0
crossvul-cpp_data_good_217_0
/* * MOV, 3GP, MP4 muxer * Copyright (c) 2003 Thomas Raivio * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org> * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com> * * 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 <stdint.h> #include <inttypes.h> #include "movenc.h" #include "avformat.h" #include "avio_internal.h" #include "riff.h" #include "avio.h" #include "isom.h" #include "avc.h" #include "libavcodec/ac3_parser_internal.h" #include "libavcodec/dnxhddata.h" #include "libavcodec/flac.h" #include "libavcodec/get_bits.h" #include "libavcodec/internal.h" #include "libavcodec/put_bits.h" #include "libavcodec/vc1_common.h" #include "libavcodec/raw.h" #include "internal.h" #include "libavutil/avstring.h" #include "libavutil/intfloat.h" #include "libavutil/mathematics.h" #include "libavutil/libm.h" #include "libavutil/opt.h" #include "libavutil/dict.h" #include "libavutil/pixdesc.h" #include "libavutil/stereo3d.h" #include "libavutil/timecode.h" #include "libavutil/color_utils.h" #include "hevc.h" #include "rtpenc.h" #include "mov_chan.h" #include "vpcc.h" static const AVOption options[] = { { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 }, { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "negative_cts_offsets", "Use negative CTS offsets (reducing the need for edit lists)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags), { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM}, { "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "write_prft", "Write producer reference time box with specified time source", offsetof(MOVMuxContext, write_prft), AV_OPT_TYPE_INT, {.i64 = MOV_PRFT_NONE}, 0, MOV_PRFT_NB-1, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "empty_hdlr_name", "write zero-length name string in hdlr atoms within mdia and minf atoms", offsetof(MOVMuxContext, empty_hdlr_name), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { NULL }, }; #define MOV_CLASS(flavor)\ static const AVClass flavor ## _muxer_class = {\ .class_name = #flavor " muxer",\ .item_name = av_default_item_name,\ .option = options,\ .version = LIBAVUTIL_VERSION_INT,\ }; static int get_moov_size(AVFormatContext *s); static int utf8len(const uint8_t *b) { int len = 0; int val; while (*b) { GET_UTF8(val, *b++, return -1;) len++; } return len; } //FIXME support 64 bit variant with wide placeholders static int64_t update_size(AVIOContext *pb, int64_t pos) { int64_t curpos = avio_tell(pb); avio_seek(pb, pos, SEEK_SET); avio_wb32(pb, curpos - pos); /* rewrite size */ avio_seek(pb, curpos, SEEK_SET); return curpos - pos; } static int co64_required(const MOVTrack *track) { if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX) return 1; return 0; } static int is_cover_image(const AVStream *st) { /* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS * is encoded as sparse video track */ return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC; } static int rtp_hinting_needed(const AVStream *st) { /* Add hint tracks for each real audio and video stream */ if (is_cover_image(st)) return 0; return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO || st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO; } /* Chunk offset atom */ static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track) { int i; int mode64 = co64_required(track); // use 32 bit size variant if possible int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ if (mode64) ffio_wfourcc(pb, "co64"); else ffio_wfourcc(pb, "stco"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, track->chunkCount); /* entry count */ for (i = 0; i < track->entry; i++) { if (!track->cluster[i].chunkNum) continue; if (mode64 == 1) avio_wb64(pb, track->cluster[i].pos + track->data_offset); else avio_wb32(pb, track->cluster[i].pos + track->data_offset); } return update_size(pb, pos); } /* Sample size atom */ static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track) { int equalChunks = 1; int i, j, entries = 0, tst = -1, oldtst = -1; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsz"); avio_wb32(pb, 0); /* version & flags */ for (i = 0; i < track->entry; i++) { tst = track->cluster[i].size / track->cluster[i].entries; if (oldtst != -1 && tst != oldtst) equalChunks = 0; oldtst = tst; entries += track->cluster[i].entries; } if (equalChunks && track->entry) { int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0; sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0 avio_wb32(pb, sSize); // sample size avio_wb32(pb, entries); // sample count } else { avio_wb32(pb, 0); // sample size avio_wb32(pb, entries); // sample count for (i = 0; i < track->entry; i++) { for (j = 0; j < track->cluster[i].entries; j++) { avio_wb32(pb, track->cluster[i].size / track->cluster[i].entries); } } } return update_size(pb, pos); } /* Sample to chunk atom */ static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track) { int index = 0, oldval = -1, i; int64_t entryPos, curpos; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsc"); avio_wb32(pb, 0); // version & flags entryPos = avio_tell(pb); avio_wb32(pb, track->chunkCount); // entry count for (i = 0; i < track->entry; i++) { if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) { avio_wb32(pb, track->cluster[i].chunkNum); // first chunk avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk avio_wb32(pb, 0x1); // sample description index oldval = track->cluster[i].samples_in_chunk; index++; } } curpos = avio_tell(pb); avio_seek(pb, entryPos, SEEK_SET); avio_wb32(pb, index); // rewrite size avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } /* Sync sample atom */ static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag) { int64_t curpos, entryPos; int i, index = 0; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); // size ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps"); avio_wb32(pb, 0); // version & flags entryPos = avio_tell(pb); avio_wb32(pb, track->entry); // entry count for (i = 0; i < track->entry; i++) { if (track->cluster[i].flags & flag) { avio_wb32(pb, i + 1); index++; } } curpos = avio_tell(pb); avio_seek(pb, entryPos, SEEK_SET); avio_wb32(pb, index); // rewrite size avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } /* Sample dependency atom */ static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track) { int i; uint8_t leading, dependent, reference, redundancy; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); // size ffio_wfourcc(pb, "sdtp"); avio_wb32(pb, 0); // version & flags for (i = 0; i < track->entry; i++) { dependent = MOV_SAMPLE_DEPENDENCY_YES; leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN; if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) { reference = MOV_SAMPLE_DEPENDENCY_NO; } if (track->cluster[i].flags & MOV_SYNC_SAMPLE) { dependent = MOV_SAMPLE_DEPENDENCY_NO; } avio_w8(pb, (leading << 6) | (dependent << 4) | (reference << 2) | redundancy); } return update_size(pb, pos); } static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 0x11); /* size */ if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr"); else ffio_wfourcc(pb, "damr"); ffio_wfourcc(pb, "FFMP"); avio_w8(pb, 0); /* decoder version */ avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */ avio_w8(pb, 0x00); /* Mode change period (no restriction) */ avio_w8(pb, 0x01); /* Frames per sample */ return 0x11; } static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track) { GetBitContext gbc; PutBitContext pbc; uint8_t buf[3]; int fscod, bsid, bsmod, acmod, lfeon, frmsizecod; if (track->vos_len < 7) return -1; avio_wb32(pb, 11); ffio_wfourcc(pb, "dac3"); init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8); fscod = get_bits(&gbc, 2); frmsizecod = get_bits(&gbc, 6); bsid = get_bits(&gbc, 5); bsmod = get_bits(&gbc, 3); acmod = get_bits(&gbc, 3); if (acmod == 2) { skip_bits(&gbc, 2); // dsurmod } else { if ((acmod & 1) && acmod != 1) skip_bits(&gbc, 2); // cmixlev if (acmod & 4) skip_bits(&gbc, 2); // surmixlev } lfeon = get_bits1(&gbc); init_put_bits(&pbc, buf, sizeof(buf)); put_bits(&pbc, 2, fscod); put_bits(&pbc, 5, bsid); put_bits(&pbc, 3, bsmod); put_bits(&pbc, 3, acmod); put_bits(&pbc, 1, lfeon); put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code put_bits(&pbc, 5, 0); // reserved flush_put_bits(&pbc); avio_write(pb, buf, sizeof(buf)); return 11; } struct eac3_info { AVPacket pkt; uint8_t ec3_done; uint8_t num_blocks; /* Layout of the EC3SpecificBox */ /* maximum bitrate */ uint16_t data_rate; /* number of independent substreams */ uint8_t num_ind_sub; struct { /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */ uint8_t fscod; /* bit stream identification 5 bits */ uint8_t bsid; /* one bit reserved */ /* audio service mixing (not supported yet) 1 bit */ /* bit stream mode 3 bits */ uint8_t bsmod; /* audio coding mode 3 bits */ uint8_t acmod; /* sub woofer on 1 bit */ uint8_t lfeon; /* 3 bits reserved */ /* number of dependent substreams associated with this substream 4 bits */ uint8_t num_dep_sub; /* channel locations of the dependent substream(s), if any, 9 bits */ uint16_t chan_loc; /* if there is no dependent substream, then one bit reserved instead */ } substream[1]; /* TODO: support 8 independent substreams */ }; #if CONFIG_AC3_PARSER static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { //info->num_ind_sub++; avpriv_request_sample(track->par, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } else { if (hdr->substreamid != 0) { avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; } #endif static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track) { PutBitContext pbc; uint8_t *buf; struct eac3_info *info; int size, i; if (!track->eac3_priv) return AVERROR(EINVAL); info = track->eac3_priv; size = 2 + 4 * (info->num_ind_sub + 1); buf = av_malloc(size); if (!buf) { size = AVERROR(ENOMEM); goto end; } init_put_bits(&pbc, buf, size); put_bits(&pbc, 13, info->data_rate); put_bits(&pbc, 3, info->num_ind_sub); for (i = 0; i <= info->num_ind_sub; i++) { put_bits(&pbc, 2, info->substream[i].fscod); put_bits(&pbc, 5, info->substream[i].bsid); put_bits(&pbc, 1, 0); /* reserved */ put_bits(&pbc, 1, 0); /* asvc */ put_bits(&pbc, 3, info->substream[i].bsmod); put_bits(&pbc, 3, info->substream[i].acmod); put_bits(&pbc, 1, info->substream[i].lfeon); put_bits(&pbc, 5, 0); /* reserved */ put_bits(&pbc, 4, info->substream[i].num_dep_sub); if (!info->substream[i].num_dep_sub) { put_bits(&pbc, 1, 0); /* reserved */ size--; } else { put_bits(&pbc, 9, info->substream[i].chan_loc); } } flush_put_bits(&pbc); avio_wb32(pb, size + 8); ffio_wfourcc(pb, "dec3"); avio_write(pb, buf, size); av_free(buf); end: av_packet_unref(&info->pkt); av_freep(&track->eac3_priv); return size; } /** * This function writes extradata "as is". * Extradata must be formatted like a valid atom (with size and tag). */ static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track) { avio_write(pb, track->par->extradata, track->par->extradata_size); return track->par->extradata_size; } static int mov_write_enda_tag(AVIOContext *pb) { avio_wb32(pb, 10); ffio_wfourcc(pb, "enda"); avio_wb16(pb, 1); /* little endian */ return 10; } static int mov_write_enda_tag_be(AVIOContext *pb) { avio_wb32(pb, 10); ffio_wfourcc(pb, "enda"); avio_wb16(pb, 0); /* big endian */ return 10; } static void put_descr(AVIOContext *pb, int tag, unsigned int size) { int i = 3; avio_w8(pb, tag); for (; i > 0; i--) avio_w8(pb, (size >> (7 * i)) | 0x80); avio_w8(pb, size & 0x7F); } static unsigned compute_avg_bitrate(MOVTrack *track) { uint64_t size = 0; int i; if (!track->track_duration) return 0; for (i = 0; i < track->entry; i++) size += track->cluster[i].size; return size * 8 * track->timescale / track->track_duration; } static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic { AVCPBProperties *props; int64_t pos = avio_tell(pb); int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0; unsigned avg_bitrate; avio_wb32(pb, 0); // size ffio_wfourcc(pb, "esds"); avio_wb32(pb, 0); // Version // ES descriptor put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1); avio_wb16(pb, track->track_id); avio_w8(pb, 0x00); // flags (= no flags) // DecoderConfig descriptor put_descr(pb, 0x04, 13 + decoder_specific_info_len); // Object type indication if ((track->par->codec_id == AV_CODEC_ID_MP2 || track->par->codec_id == AV_CODEC_ID_MP3) && track->par->sample_rate > 24000) avio_w8(pb, 0x6B); // 11172-3 else avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id)); // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio) // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved) if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream) else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) avio_w8(pb, 0x15); // flags (= Audiostream) else avio_w8(pb, 0x11); // flags (= Visualstream) props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL); avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB avg_bitrate = compute_avg_bitrate(track); avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window) avio_wb32(pb, avg_bitrate); if (track->vos_len) { // DecoderSpecific info descriptor put_descr(pb, 0x05, track->vos_len); avio_write(pb, track->vos_data, track->vos_len); } // SL descriptor put_descr(pb, 0x06, 1); avio_w8(pb, 0x02); return update_size(pb, pos); } static int mov_pcm_le_gt16(enum AVCodecID codec_id) { return codec_id == AV_CODEC_ID_PCM_S24LE || codec_id == AV_CODEC_ID_PCM_S32LE || codec_id == AV_CODEC_ID_PCM_F32LE || codec_id == AV_CODEC_ID_PCM_F64LE; } static int mov_pcm_be_gt16(enum AVCodecID codec_id) { return codec_id == AV_CODEC_ID_PCM_S24BE || codec_id == AV_CODEC_ID_PCM_S32BE || codec_id == AV_CODEC_ID_PCM_F32BE || codec_id == AV_CODEC_ID_PCM_F64BE; } static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int ret; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); avio_wl32(pb, track->tag); // store it byteswapped track->par->codec_tag = av_bswap16(track->tag >> 16); if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0) return ret; return update_size(pb, pos); } static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int ret; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "wfex"); if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0) return ret; return update_size(pb, pos); } static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "dfLa"); avio_w8(pb, 0); /* version */ avio_wb24(pb, 0); /* flags */ /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */ if (track->par->extradata_size != FLAC_STREAMINFO_SIZE) return AVERROR_INVALIDDATA; /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */ avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */ avio_wb24(pb, track->par->extradata_size); /* Length */ avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */ return update_size(pb, pos); } static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "dOps"); avio_w8(pb, 0); /* Version */ if (track->par->extradata_size < 19) { av_log(pb, AV_LOG_ERROR, "invalid extradata size\n"); return AVERROR_INVALIDDATA; } /* extradata contains an Ogg OpusHead, other than byte-ordering and OpusHead's preceeding magic/version, OpusSpecificBox is currently identical. */ avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */ avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */ avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */ avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */ /* Write the rest of the header out without byte-swapping. */ avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18); return update_size(pb, pos); } static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { uint32_t layout_tag, bitmap; int64_t pos = avio_tell(pb); layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id, track->par->channel_layout, &bitmap); if (!layout_tag) { av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to " "lack of channel information\n"); return 0; } if (track->multichannel_as_mono) return 0; avio_wb32(pb, 0); // Size ffio_wfourcc(pb, "chan"); // Type avio_w8(pb, 0); // Version avio_wb24(pb, 0); // Flags avio_wb32(pb, layout_tag); // mChannelLayoutTag avio_wb32(pb, bitmap); // mChannelBitmap avio_wb32(pb, 0); // mNumberChannelDescriptions return update_size(pb, pos); } static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "wave"); if (track->par->codec_id != AV_CODEC_ID_QDM2) { avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "frma"); avio_wl32(pb, track->tag); } if (track->par->codec_id == AV_CODEC_ID_AAC) { /* useless atom needed by mplayer, ipod, not needed by quicktime */ avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "mp4a"); avio_wb32(pb, 0); mov_write_esds_tag(pb, track); } else if (mov_pcm_le_gt16(track->par->codec_id)) { mov_write_enda_tag(pb); } else if (mov_pcm_be_gt16(track->par->codec_id)) { mov_write_enda_tag_be(pb); } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) { mov_write_amr_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_AC3) { mov_write_ac3_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_EAC3) { mov_write_eac3_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_ALAC || track->par->codec_id == AV_CODEC_ID_QDM2) { mov_write_extradata_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) { mov_write_ms_tag(s, pb, track); } avio_wb32(pb, 8); /* size */ avio_wb32(pb, 0); /* null tag */ return update_size(pb, pos); } static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf) { uint8_t *unescaped; const uint8_t *start, *next, *end = track->vos_data + track->vos_len; int unescaped_size, seq_found = 0; int level = 0, interlace = 0; int packet_seq = track->vc1_info.packet_seq; int packet_entry = track->vc1_info.packet_entry; int slices = track->vc1_info.slices; PutBitContext pbc; if (track->start_dts == AV_NOPTS_VALUE) { /* No packets written yet, vc1_info isn't authoritative yet. */ /* Assume inline sequence and entry headers. */ packet_seq = packet_entry = 1; av_log(NULL, AV_LOG_WARNING, "moov atom written before any packets, unable to write correct " "dvc1 atom. Set the delay_moov flag to fix this.\n"); } unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE); if (!unescaped) return AVERROR(ENOMEM); start = find_next_marker(track->vos_data, end); for (next = start; next < end; start = next) { GetBitContext gb; int size; next = find_next_marker(start + 4, end); size = next - start - 4; if (size <= 0) continue; unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped); init_get_bits(&gb, unescaped, 8 * unescaped_size); if (AV_RB32(start) == VC1_CODE_SEQHDR) { int profile = get_bits(&gb, 2); if (profile != PROFILE_ADVANCED) { av_free(unescaped); return AVERROR(ENOSYS); } seq_found = 1; level = get_bits(&gb, 3); /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag, * width, height */ skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12); skip_bits(&gb, 1); /* broadcast */ interlace = get_bits1(&gb); skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */ } } if (!seq_found) { av_free(unescaped); return AVERROR(ENOSYS); } init_put_bits(&pbc, buf, 7); /* VC1DecSpecStruc */ put_bits(&pbc, 4, 12); /* profile - advanced */ put_bits(&pbc, 3, level); put_bits(&pbc, 1, 0); /* reserved */ /* VC1AdvDecSpecStruc */ put_bits(&pbc, 3, level); put_bits(&pbc, 1, 0); /* cbr */ put_bits(&pbc, 6, 0); /* reserved */ put_bits(&pbc, 1, !interlace); /* no interlace */ put_bits(&pbc, 1, !packet_seq); /* no multiple seq */ put_bits(&pbc, 1, !packet_entry); /* no multiple entry */ put_bits(&pbc, 1, !slices); /* no slice code */ put_bits(&pbc, 1, 0); /* no bframe */ put_bits(&pbc, 1, 0); /* reserved */ /* framerate */ if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0) put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den); else put_bits32(&pbc, 0xffffffff); flush_put_bits(&pbc); av_free(unescaped); return 0; } static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track) { uint8_t buf[7] = { 0 }; int ret; if ((ret = mov_write_dvc1_structs(track, buf)) < 0) return ret; avio_wb32(pb, track->vos_len + 8 + sizeof(buf)); ffio_wfourcc(pb, "dvc1"); avio_write(pb, buf, sizeof(buf)); avio_write(pb, track->vos_data, track->vos_len); return 0; } static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, track->vos_len + 8); ffio_wfourcc(pb, "glbl"); avio_write(pb, track->vos_data, track->vos_len); return 8 + track->vos_len; } /** * Compute flags for 'lpcm' tag. * See CoreAudioTypes and AudioStreamBasicDescription at Apple. */ static int mov_get_lpcm_flags(enum AVCodecID codec_id) { switch (codec_id) { case AV_CODEC_ID_PCM_F32BE: case AV_CODEC_ID_PCM_F64BE: return 11; case AV_CODEC_ID_PCM_F32LE: case AV_CODEC_ID_PCM_F64LE: return 9; case AV_CODEC_ID_PCM_U8: return 10; case AV_CODEC_ID_PCM_S16BE: case AV_CODEC_ID_PCM_S24BE: case AV_CODEC_ID_PCM_S32BE: return 14; case AV_CODEC_ID_PCM_S8: case AV_CODEC_ID_PCM_S16LE: case AV_CODEC_ID_PCM_S24LE: case AV_CODEC_ID_PCM_S32LE: return 12; default: return 0; } } static int get_cluster_duration(MOVTrack *track, int cluster_idx) { int64_t next_dts; if (cluster_idx >= track->entry) return 0; if (cluster_idx + 1 == track->entry) next_dts = track->track_duration + track->start_dts; else next_dts = track->cluster[cluster_idx + 1].dts; next_dts -= track->cluster[cluster_idx].dts; av_assert0(next_dts >= 0); av_assert0(next_dts <= INT_MAX); return next_dts; } static int get_samples_per_packet(MOVTrack *track) { int i, first_duration; // return track->par->frame_size; /* use 1 for raw PCM */ if (!track->audio_vbr) return 1; /* check to see if duration is constant for all clusters */ if (!track->entry) return 0; first_duration = get_cluster_duration(track, 0); for (i = 1; i < track->entry; i++) { if (get_cluster_duration(track, i) != first_duration) return 0; } return first_duration; } static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int version = 0; uint32_t tag = track->tag; if (track->mode == MODE_MOV) { if (track->timescale > UINT16_MAX) { if (mov_get_lpcm_flags(track->par->codec_id)) tag = AV_RL32("lpcm"); version = 2; } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) || mov_pcm_be_gt16(track->par->codec_id) || track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || track->par->codec_id == AV_CODEC_ID_QDM2) { version = 1; } } avio_wb32(pb, 0); /* size */ if (mov->encryption_scheme != MOV_ENC_NONE) { ffio_wfourcc(pb, "enca"); } else { avio_wl32(pb, tag); // store it byteswapped } avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */ /* SoundDescription */ avio_wb16(pb, version); /* Version */ avio_wb16(pb, 0); /* Revision level */ avio_wb32(pb, 0); /* Reserved */ if (version == 2) { avio_wb16(pb, 3); avio_wb16(pb, 16); avio_wb16(pb, 0xfffe); avio_wb16(pb, 0); avio_wb32(pb, 0x00010000); avio_wb32(pb, 72); avio_wb64(pb, av_double2int(track->par->sample_rate)); avio_wb32(pb, track->par->channels); avio_wb32(pb, 0x7F000000); avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id)); avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id)); avio_wb32(pb, track->sample_size); avio_wb32(pb, get_samples_per_packet(track)); } else { if (track->mode == MODE_MOV) { avio_wb16(pb, track->par->channels); if (track->par->codec_id == AV_CODEC_ID_PCM_U8 || track->par->codec_id == AV_CODEC_ID_PCM_S8) avio_wb16(pb, 8); /* bits per sample */ else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726) avio_wb16(pb, track->par->bits_per_coded_sample); else avio_wb16(pb, 16); avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */ } else { /* reserved for mp4/3gp */ if (track->par->codec_id == AV_CODEC_ID_FLAC || track->par->codec_id == AV_CODEC_ID_OPUS) { avio_wb16(pb, track->par->channels); } else { avio_wb16(pb, 2); } if (track->par->codec_id == AV_CODEC_ID_FLAC) { avio_wb16(pb, track->par->bits_per_raw_sample); } else { avio_wb16(pb, 16); } avio_wb16(pb, 0); } avio_wb16(pb, 0); /* packet size (= 0) */ if (track->par->codec_id == AV_CODEC_ID_OPUS) avio_wb16(pb, 48000); else avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ? track->par->sample_rate : 0); avio_wb16(pb, 0); /* Reserved */ } if (version == 1) { /* SoundDescription V1 extended info */ if (mov_pcm_le_gt16(track->par->codec_id) || mov_pcm_be_gt16(track->par->codec_id)) avio_wb32(pb, 1); /* must be 1 for uncompressed formats */ else avio_wb32(pb, track->par->frame_size); /* Samples per packet */ avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */ avio_wb32(pb, track->sample_size); /* Bytes per frame */ avio_wb32(pb, 2); /* Bytes per sample */ } if (track->mode == MODE_MOV && (track->par->codec_id == AV_CODEC_ID_AAC || track->par->codec_id == AV_CODEC_ID_AC3 || track->par->codec_id == AV_CODEC_ID_EAC3 || track->par->codec_id == AV_CODEC_ID_AMR_NB || track->par->codec_id == AV_CODEC_ID_ALAC || track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || track->par->codec_id == AV_CODEC_ID_QDM2 || (mov_pcm_le_gt16(track->par->codec_id) && version==1) || (mov_pcm_be_gt16(track->par->codec_id) && version==1))) mov_write_wave_tag(s, pb, track); else if (track->tag == MKTAG('m','p','4','a')) mov_write_esds_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) mov_write_amr_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_AC3) mov_write_ac3_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_EAC3) mov_write_eac3_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_ALAC) mov_write_extradata_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) mov_write_wfex_tag(s, pb, track); else if (track->par->codec_id == AV_CODEC_ID_FLAC) mov_write_dfla_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_OPUS) mov_write_dops_tag(pb, track); else if (track->vos_len > 0) mov_write_glbl_tag(pb, track); if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_chan_tag(s, pb, track); if (mov->encryption_scheme != MOV_ENC_NONE) { ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid); } return update_size(pb, pos); } static int mov_write_d263_tag(AVIOContext *pb) { avio_wb32(pb, 0xf); /* size */ ffio_wfourcc(pb, "d263"); ffio_wfourcc(pb, "FFMP"); avio_w8(pb, 0); /* decoder version */ /* FIXME use AVCodecContext level/profile, when encoder will set values */ avio_w8(pb, 0xa); /* level */ avio_w8(pb, 0); /* profile */ return 0xf; } static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "avcC"); ff_isom_write_avcc(pb, track->vos_data, track->vos_len); return update_size(pb, pos); } static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "vpcC"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); /* flags */ ff_isom_write_vpcc(s, pb, track->par); return update_size(pb, pos); } static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "hvcC"); if (track->tag == MKTAG('h','v','c','1')) ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1); else ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0); return update_size(pb, pos); } /* also used by all avid codecs (dv, imx, meridien) and their variants */ static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track) { int i; int interlaced; int cid; int display_width = track->par->width; if (track->vos_data && track->vos_len > 0x29) { if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) { /* looks like a DNxHD bit stream */ interlaced = (track->vos_data[5] & 2); cid = AV_RB32(track->vos_data + 0x28); } else { av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n"); return 0; } } else { av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n"); return 0; } avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "ACLR"); ffio_wfourcc(pb, "ACLR"); ffio_wfourcc(pb, "0001"); if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */ track->par->color_range == AVCOL_RANGE_UNSPECIFIED) { avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */ } else { /* Full range (0-255) */ avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */ } avio_wb32(pb, 0); /* unknown */ if (track->tag == MKTAG('A','V','d','h')) { avio_wb32(pb, 32); ffio_wfourcc(pb, "ADHR"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, cid); avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 0); /* unknown */ return 0; } avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "APRG"); ffio_wfourcc(pb, "APRG"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 120); /* size */ ffio_wfourcc(pb, "ARES"); ffio_wfourcc(pb, "ARES"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, cid); /* dnxhd cid, some id ? */ if ( track->par->sample_aspect_ratio.num > 0 && track->par->sample_aspect_ratio.den > 0) display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den; avio_wb32(pb, display_width); /* values below are based on samples created with quicktime and avid codecs */ if (interlaced) { avio_wb32(pb, track->par->height / 2); avio_wb32(pb, 2); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 4); /* unknown */ } else { avio_wb32(pb, track->par->height); avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ if (track->par->height == 1080) avio_wb32(pb, 5); /* unknown */ else avio_wb32(pb, 6); /* unknown */ } /* padding */ for (i = 0; i < 10; i++) avio_wb64(pb, 0); return 0; } static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 12); ffio_wfourcc(pb, "DpxE"); if (track->par->extradata_size >= 12 && !memcmp(&track->par->extradata[4], "DpxE", 4)) { avio_wb32(pb, track->par->extradata[11]); } else { avio_wb32(pb, 1); } return 0; } static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag; if (track->par->width == 720) { /* SD */ if (track->par->height == 480) { /* NTSC */ if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n'); else tag = MKTAG('d','v','c',' '); }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p'); else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p'); else tag = MKTAG('d','v','p','p'); } else if (track->par->height == 720) { /* HD 720 line */ if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q'); else tag = MKTAG('d','v','h','p'); } else if (track->par->height == 1080) { /* HD 1080 line */ if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5'); else tag = MKTAG('d','v','h','6'); } else { av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n"); return 0; } return tag; } static AVRational find_fps(AVFormatContext *s, AVStream *st) { AVRational rate = st->avg_frame_rate; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS rate = av_inv_q(st->codec->time_base); if (av_timecode_check_frame_rate(rate) < 0) { av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n", rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den); rate = st->avg_frame_rate; } FF_ENABLE_DEPRECATION_WARNINGS #endif return rate; } static int defined_frame_rate(AVFormatContext *s, AVStream *st) { AVRational rational_framerate = find_fps(s, st); int rate = 0; if (rational_framerate.den != 0) rate = av_q2d(rational_framerate); return rate; } static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(s, st); if (!tag) tag = MKTAG('m', '2', 'v', '1'); //fallback tag if (track->par->format == AV_PIX_FMT_YUV420P) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','4'); else if (rate == 25) tag = MKTAG('x','d','v','5'); else if (rate == 30) tag = MKTAG('x','d','v','1'); else if (rate == 50) tag = MKTAG('x','d','v','a'); else if (rate == 60) tag = MKTAG('x','d','v','9'); } } else if (track->par->width == 1440 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','6'); else if (rate == 25) tag = MKTAG('x','d','v','7'); else if (rate == 30) tag = MKTAG('x','d','v','8'); } else { if (rate == 25) tag = MKTAG('x','d','v','3'); else if (rate == 30) tag = MKTAG('x','d','v','2'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','d'); else if (rate == 25) tag = MKTAG('x','d','v','e'); else if (rate == 30) tag = MKTAG('x','d','v','f'); } else { if (rate == 25) tag = MKTAG('x','d','v','c'); else if (rate == 30) tag = MKTAG('x','d','v','b'); } } } else if (track->par->format == AV_PIX_FMT_YUV422P) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','5','4'); else if (rate == 25) tag = MKTAG('x','d','5','5'); else if (rate == 30) tag = MKTAG('x','d','5','1'); else if (rate == 50) tag = MKTAG('x','d','5','a'); else if (rate == 60) tag = MKTAG('x','d','5','9'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','5','d'); else if (rate == 25) tag = MKTAG('x','d','5','e'); else if (rate == 30) tag = MKTAG('x','d','5','f'); } else { if (rate == 25) tag = MKTAG('x','d','5','c'); else if (rate == 30) tag = MKTAG('x','d','5','b'); } } } return tag; } static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(s, st); if (!tag) tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag if (track->par->format == AV_PIX_FMT_YUV420P10) { if (track->par->width == 960 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','5','p'); else if (rate == 25) tag = MKTAG('a','i','5','q'); else if (rate == 30) tag = MKTAG('a','i','5','p'); else if (rate == 50) tag = MKTAG('a','i','5','q'); else if (rate == 60) tag = MKTAG('a','i','5','p'); } } else if (track->par->width == 1440 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','5','3'); else if (rate == 25) tag = MKTAG('a','i','5','2'); else if (rate == 30) tag = MKTAG('a','i','5','3'); } else { if (rate == 50) tag = MKTAG('a','i','5','5'); else if (rate == 60) tag = MKTAG('a','i','5','6'); } } } else if (track->par->format == AV_PIX_FMT_YUV422P10) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','1','p'); else if (rate == 25) tag = MKTAG('a','i','1','q'); else if (rate == 30) tag = MKTAG('a','i','1','p'); else if (rate == 50) tag = MKTAG('a','i','1','q'); else if (rate == 60) tag = MKTAG('a','i','1','p'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','1','3'); else if (rate == 25) tag = MKTAG('a','i','1','2'); else if (rate == 30) tag = MKTAG('a','i','1','3'); } else { if (rate == 25) tag = MKTAG('a','i','1','5'); else if (rate == 50) tag = MKTAG('a','i','1','5'); else if (rate == 60) tag = MKTAG('a','i','1','6'); } } else if ( track->par->width == 4096 && track->par->height == 2160 || track->par->width == 3840 && track->par->height == 2160 || track->par->width == 2048 && track->par->height == 1080) { tag = MKTAG('a','i','v','x'); } } return tag; } static const struct { enum AVPixelFormat pix_fmt; uint32_t tag; unsigned bps; } mov_pix_fmt_tags[] = { { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 }, { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 }, { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 }, { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 }, { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 }, { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 }, { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 }, { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 }, { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 }, { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 }, { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 }, { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 }, { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 }, { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 }, { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 }, }; static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = MKTAG('A','V','d','n'); if (track->par->profile != FF_PROFILE_UNKNOWN && track->par->profile != FF_PROFILE_DNXHD) tag = MKTAG('A','V','d','h'); return tag; } static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int i; enum AVPixelFormat pix_fmt; for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) { if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) { tag = mov_pix_fmt_tags[i].tag; track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps; if (track->par->codec_tag == mov_pix_fmt_tags[i].tag) break; } } pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov, track->par->bits_per_coded_sample); if (tag == MKTAG('r','a','w',' ') && track->par->format != pix_fmt && track->par->format != AV_PIX_FMT_GRAY8 && track->par->format != AV_PIX_FMT_NONE) av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n", av_get_pix_fmt_name(track->par->format)); return tag; } static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL && (track->par->codec_id == AV_CODEC_ID_DVVIDEO || track->par->codec_id == AV_CODEC_ID_RAWVIDEO || track->par->codec_id == AV_CODEC_ID_H263 || track->par->codec_id == AV_CODEC_ID_H264 || track->par->codec_id == AV_CODEC_ID_DNXHD || track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO || av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio if (track->par->codec_id == AV_CODEC_ID_DVVIDEO) tag = mov_get_dv_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) tag = mov_get_rawvideo_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO) tag = mov_get_mpeg2_xdcam_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_H264) tag = mov_get_h264_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_DNXHD) tag = mov_get_dnxhd_codec_tag(s, track); else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id); if (!tag) { // if no mac fcc found, try with Microsoft tags tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id); if (tag) av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, " "the file may be unplayable!\n"); } } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id); if (!tag) { // if no mac fcc found, try with Microsoft tags int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id); if (ms_tag) { tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff)); av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, " "the file may be unplayable!\n"); } } } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id); } return tag; } static const AVCodecTag codec_cover_image_tags[] = { { AV_CODEC_ID_MJPEG, 0xD }, { AV_CODEC_ID_PNG, 0xE }, { AV_CODEC_ID_BMP, 0x1B }, { AV_CODEC_ID_NONE, 0 }, }; static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag; if (is_cover_image(track->st)) return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id); if (track->mode == MODE_MP4 || track->mode == MODE_PSP) tag = track->par->codec_tag; else if (track->mode == MODE_ISM) tag = track->par->codec_tag; else if (track->mode == MODE_IPOD) { if (!av_match_ext(s->url, "m4a") && !av_match_ext(s->url, "m4v") && !av_match_ext(s->url, "m4b")) av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v " "Quicktime/Ipod might not play the file\n"); tag = track->par->codec_tag; } else if (track->mode & MODE_3GP) tag = track->par->codec_tag; else if (track->mode == MODE_F4V) tag = track->par->codec_tag; else tag = mov_get_codec_tag(s, track); return tag; } /** Write uuid atom. * Needed to make file play in iPods running newest firmware * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1 */ static int mov_write_uuid_tag_ipod(AVIOContext *pb) { avio_wb32(pb, 28); ffio_wfourcc(pb, "uuid"); avio_wb32(pb, 0x6b6840f2); avio_wb32(pb, 0x5f244fc5); avio_wb32(pb, 0xba39a51b); avio_wb32(pb, 0xcf0323f3); avio_wb32(pb, 0x0); return 28; } static const uint16_t fiel_data[] = { 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e }; static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order) { unsigned mov_field_order = 0; if (field_order < FF_ARRAY_ELEMS(fiel_data)) mov_field_order = fiel_data[field_order]; else return 0; avio_wb32(pb, 10); ffio_wfourcc(pb, "fiel"); avio_wb16(pb, mov_field_order); return 10; } static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ avio_wl32(pb, track->tag); // store it byteswapped avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) mov_write_esds_tag(pb, track); else if (track->par->extradata_size) avio_write(pb, track->par->extradata, track->par->extradata_size); return update_size(pb, pos); } static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d) { int8_t stereo_mode; if (stereo_3d->flags != 0) { av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags); return 0; } switch (stereo_3d->type) { case AV_STEREO3D_2D: stereo_mode = 0; break; case AV_STEREO3D_TOPBOTTOM: stereo_mode = 1; break; case AV_STEREO3D_SIDEBYSIDE: stereo_mode = 2; break; default: av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type)); return 0; } avio_wb32(pb, 13); /* size */ ffio_wfourcc(pb, "st3d"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_w8(pb, stereo_mode); return 13; } static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping) { int64_t sv3d_pos, svhd_pos, proj_pos; const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT; if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR && spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE && spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) { av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection); return 0; } sv3d_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "sv3d"); svhd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "svhd"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_put_str(pb, metadata_source); update_size(pb, svhd_pos); proj_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "proj"); avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "prhd"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, spherical_mapping->yaw); avio_wb32(pb, spherical_mapping->pitch); avio_wb32(pb, spherical_mapping->roll); switch (spherical_mapping->projection) { case AV_SPHERICAL_EQUIRECTANGULAR: case AV_SPHERICAL_EQUIRECTANGULAR_TILE: avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "equi"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, spherical_mapping->bound_top); avio_wb32(pb, spherical_mapping->bound_bottom); avio_wb32(pb, spherical_mapping->bound_left); avio_wb32(pb, spherical_mapping->bound_right); break; case AV_SPHERICAL_CUBEMAP: avio_wb32(pb, 20); /* size */ ffio_wfourcc(pb, "cbmp"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, 0); /* layout */ avio_wb32(pb, spherical_mapping->padding); /* padding */ break; } update_size(pb, proj_pos); return update_size(pb, sv3d_pos); } static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 40); ffio_wfourcc(pb, "clap"); avio_wb32(pb, track->par->width); /* apertureWidth_N */ avio_wb32(pb, 1); /* apertureWidth_D (= 1) */ avio_wb32(pb, track->height); /* apertureHeight_N */ avio_wb32(pb, 1); /* apertureHeight_D (= 1) */ avio_wb32(pb, 0); /* horizOff_N (= 0) */ avio_wb32(pb, 1); /* horizOff_D (= 1) */ avio_wb32(pb, 0); /* vertOff_N (= 0) */ avio_wb32(pb, 1); /* vertOff_D (= 1) */ return 40; } static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track) { AVRational sar; av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num, track->par->sample_aspect_ratio.den, INT_MAX); avio_wb32(pb, 16); ffio_wfourcc(pb, "pasp"); avio_wb32(pb, sar.num); avio_wb32(pb, sar.den); return 16; } static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma) { uint32_t gama = 0; if (gamma <= 0.0) { gamma = avpriv_get_gamma_from_trc(track->par->color_trc); } av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma); if (gamma > 1e-6) { gama = (uint32_t)lrint((double)(1<<16) * gamma); av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama); av_assert0(track->mode == MODE_MOV); avio_wb32(pb, 12); ffio_wfourcc(pb, "gama"); avio_wb32(pb, gama); return 12; } else { av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n"); } return 0; } static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track) { // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9 // Ref (MP4): ISO/IEC 14496-12:2012 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED && track->par->color_trc == AVCOL_TRC_UNSPECIFIED && track->par->color_space == AVCOL_SPC_UNSPECIFIED) { if ((track->par->width >= 1920 && track->par->height >= 1080) || (track->par->width == 1280 && track->par->height == 720)) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n"); track->par->color_primaries = AVCOL_PRI_BT709; } else if (track->par->width == 720 && track->height == 576) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n"); track->par->color_primaries = AVCOL_PRI_BT470BG; } else if (track->par->width == 720 && (track->height == 486 || track->height == 480)) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n"); track->par->color_primaries = AVCOL_PRI_SMPTE170M; } else { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n"); } switch (track->par->color_primaries) { case AVCOL_PRI_BT709: track->par->color_trc = AVCOL_TRC_BT709; track->par->color_space = AVCOL_SPC_BT709; break; case AVCOL_PRI_SMPTE170M: case AVCOL_PRI_BT470BG: track->par->color_trc = AVCOL_TRC_BT709; track->par->color_space = AVCOL_SPC_SMPTE170M; break; } } /* We should only ever be called by MOV or MP4. */ av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4); avio_wb32(pb, 18 + (track->mode == MODE_MP4)); ffio_wfourcc(pb, "colr"); if (track->mode == MODE_MP4) ffio_wfourcc(pb, "nclx"); else ffio_wfourcc(pb, "nclc"); switch (track->par->color_primaries) { case AVCOL_PRI_BT709: avio_wb16(pb, 1); break; case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break; case AVCOL_PRI_SMPTE170M: case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break; case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break; case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break; case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break; default: avio_wb16(pb, 2); } switch (track->par->color_trc) { case AVCOL_TRC_BT709: avio_wb16(pb, 1); break; case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break; case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break; case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break; case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break; default: avio_wb16(pb, 2); } switch (track->par->color_space) { case AVCOL_SPC_BT709: avio_wb16(pb, 1); break; case AVCOL_SPC_BT470BG: case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break; case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break; case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break; default: avio_wb16(pb, 2); } if (track->mode == MODE_MP4) { int full_range = track->par->color_range == AVCOL_RANGE_JPEG; avio_w8(pb, full_range << 7); return 19; } else { return 18; } } static void find_compressor(char * compressor_name, int len, MOVTrack *track) { AVDictionaryEntry *encoder; int xdcam_res = (track->par->width == 1280 && track->par->height == 720) || (track->par->width == 1440 && track->par->height == 1080) || (track->par->width == 1920 && track->par->height == 1080); if (track->mode == MODE_MOV && (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) { av_strlcpy(compressor_name, encoder->value, 32); } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) { int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(NULL, st); av_strlcatf(compressor_name, len, "XDCAM"); if (track->par->format == AV_PIX_FMT_YUV422P) { av_strlcatf(compressor_name, len, " HD422"); } else if(track->par->width == 1440) { av_strlcatf(compressor_name, len, " HD"); } else av_strlcatf(compressor_name, len, " EX"); av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p'); av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1)); } } static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); char compressor_name[32] = { 0 }; int avid = 0; int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422) || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422) || track->par->codec_id == AV_CODEC_ID_V308 || track->par->codec_id == AV_CODEC_ID_V408 || track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210); avio_wb32(pb, 0); /* size */ if (mov->encryption_scheme != MOV_ENC_NONE) { ffio_wfourcc(pb, "encv"); } else { avio_wl32(pb, track->tag); // store it byteswapped } avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ if (uncompressed_ycbcr) { avio_wb16(pb, 2); /* Codec stream version */ } else { avio_wb16(pb, 0); /* Codec stream version */ } avio_wb16(pb, 0); /* Codec stream revision (=0) */ if (track->mode == MODE_MOV) { ffio_wfourcc(pb, "FFMP"); /* Vendor */ if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) { avio_wb32(pb, 0); /* Temporal Quality */ avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/ } else { avio_wb32(pb, 0x200); /* Temporal Quality = normal */ avio_wb32(pb, 0x200); /* Spatial Quality = normal */ } } else { avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 0); /* Reserved */ } avio_wb16(pb, track->par->width); /* Video width */ avio_wb16(pb, track->height); /* Video height */ avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */ avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */ avio_wb32(pb, 0); /* Data size (= 0) */ avio_wb16(pb, 1); /* Frame count (= 1) */ /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */ find_compressor(compressor_name, 32, track); avio_w8(pb, strlen(compressor_name)); avio_write(pb, compressor_name, 31); if (track->mode == MODE_MOV && (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210)) avio_wb16(pb, 0x18); else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample) avio_wb16(pb, track->par->bits_per_coded_sample | (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0)); else avio_wb16(pb, 0x18); /* Reserved */ if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) { int pal_size = 1 << track->par->bits_per_coded_sample; int i; avio_wb16(pb, 0); /* Color table ID */ avio_wb32(pb, 0); /* Color table seed */ avio_wb16(pb, 0x8000); /* Color table flags */ avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */ for (i = 0; i < pal_size; i++) { uint32_t rgb = track->palette[i]; uint16_t r = (rgb >> 16) & 0xff; uint16_t g = (rgb >> 8) & 0xff; uint16_t b = rgb & 0xff; avio_wb16(pb, 0); avio_wb16(pb, (r << 8) | r); avio_wb16(pb, (g << 8) | g); avio_wb16(pb, (b << 8) | b); } } else avio_wb16(pb, 0xffff); /* Reserved */ if (track->tag == MKTAG('m','p','4','v')) mov_write_esds_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_H263) mov_write_d263_tag(pb); else if (track->par->codec_id == AV_CODEC_ID_AVUI || track->par->codec_id == AV_CODEC_ID_SVQ3) { mov_write_extradata_tag(pb, track); avio_wb32(pb, 0); } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) { mov_write_avid_tag(pb, track); avid = 1; } else if (track->par->codec_id == AV_CODEC_ID_HEVC) mov_write_hvcc_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) { mov_write_avcc_tag(pb, track); if (track->mode == MODE_IPOD) mov_write_uuid_tag_ipod(pb); } else if (track->par->codec_id == AV_CODEC_ID_VP9) { mov_write_vpcc_tag(mov->fc, pb, track); } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0) mov_write_dvc1_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_VP6F || track->par->codec_id == AV_CODEC_ID_VP6A) { /* Don't write any potential extradata here - the cropping * is signalled via the normal width/height fields. */ } else if (track->par->codec_id == AV_CODEC_ID_R10K) { if (track->par->codec_tag == MKTAG('R','1','0','k')) mov_write_dpxe_tag(pb, track); } else if (track->vos_len > 0) mov_write_glbl_tag(pb, track); if (track->par->codec_id != AV_CODEC_ID_H264 && track->par->codec_id != AV_CODEC_ID_MPEG4 && track->par->codec_id != AV_CODEC_ID_DNXHD) { int field_order = track->par->field_order; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN) field_order = track->st->codec->field_order; FF_ENABLE_DEPRECATION_WARNINGS #endif if (field_order != AV_FIELD_UNKNOWN) mov_write_fiel_tag(pb, track, field_order); } if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) { if (track->mode == MODE_MOV) mov_write_gama_tag(pb, track, mov->gamma); else av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n"); } if (mov->flags & FF_MOV_FLAG_WRITE_COLR) { if (track->mode == MODE_MOV || track->mode == MODE_MP4) mov_write_colr_tag(pb, track); else av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n"); } if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) { AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL); AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL); if (stereo_3d) mov_write_st3d_tag(pb, stereo_3d); if (spherical_mapping) mov_write_sv3d_tag(mov->fc, pb, spherical_mapping); } if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) { mov_write_pasp_tag(pb, track); } if (uncompressed_ycbcr){ mov_write_clap_tag(pb, track); } if (mov->encryption_scheme != MOV_ENC_NONE) { ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid); } /* extra padding for avid stsd */ /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */ if (avid) avio_wb32(pb, 0); return update_size(pb, pos); } static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "rtp "); avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ avio_wb16(pb, 1); /* Hint track version */ avio_wb16(pb, 1); /* Highest compatible version */ avio_wb32(pb, track->max_packet_size); /* Max packet size */ avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "tims"); avio_wb32(pb, track->timescale); return update_size(pb, pos); } static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name) { uint64_t str_size =strlen(reel_name); int64_t pos = avio_tell(pb); if (str_size >= UINT16_MAX){ av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size); avio_wb16(pb, 0); return AVERROR(EINVAL); } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "name"); /* Data format */ avio_wb16(pb, str_size); /* string size */ avio_wb16(pb, track->language); /* langcode */ avio_write(pb, reel_name, str_size); /* reel name */ return update_size(pb,pos); } static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); #if 1 int frame_duration; int nb_frames; AVDictionaryEntry *t = NULL; if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) { #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den); nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num); FF_ENABLE_DEPRECATION_WARNINGS #else av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n"); return AVERROR(EINVAL); #endif } else { frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den); nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num); } if (nb_frames > 255) { av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames); return AVERROR(EINVAL); } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); /* Data format */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 1); /* Data reference index */ avio_wb32(pb, 0); /* Flags */ avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */ avio_wb32(pb, track->timescale); /* Timescale */ avio_wb32(pb, frame_duration); /* Frame duration */ avio_w8(pb, nb_frames); /* Number of frames */ avio_w8(pb, 0); /* Reserved */ t = av_dict_get(track->st->metadata, "reel_name", NULL, 0); if (t && utf8len(t->value) && track->mode != MODE_MP4) mov_write_source_reference_tag(pb, track, t->value); else avio_wb16(pb, 0); /* zero size */ #else avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); /* Data format */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 1); /* Data reference index */ if (track->par->extradata_size) avio_write(pb, track->par->extradata, track->par->extradata_size); #endif return update_size(pb, pos); } static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gpmd"); avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ avio_wb32(pb, 0); /* Reserved */ return update_size(pb, pos); } static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsd"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, 1); /* entry count */ if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) mov_write_video_tag(pb, mov, track); else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_audio_tag(s, pb, mov, track); else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) mov_write_subtitle_tag(pb, track); else if (track->par->codec_tag == MKTAG('r','t','p',' ')) mov_write_rtp_tag(pb, track); else if (track->par->codec_tag == MKTAG('t','m','c','d')) mov_write_tmcd_tag(pb, track); else if (track->par->codec_tag == MKTAG('g','p','m','d')) mov_write_gpmd_tag(pb, track); return update_size(pb, pos); } static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; MOVStts *ctts_entries; uint32_t entries = 0; uint32_t atom_size; int i; ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */ if (!ctts_entries) return AVERROR(ENOMEM); ctts_entries[0].count = 1; ctts_entries[0].duration = track->cluster[0].cts; for (i = 1; i < track->entry; i++) { if (track->cluster[i].cts == ctts_entries[entries].duration) { ctts_entries[entries].count++; /* compress */ } else { entries++; ctts_entries[entries].duration = track->cluster[i].cts; ctts_entries[entries].count = 1; } } entries++; /* last one */ atom_size = 16 + (entries * 8); avio_wb32(pb, atom_size); /* size */ ffio_wfourcc(pb, "ctts"); if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) avio_w8(pb, 1); /* version */ else avio_w8(pb, 0); /* version */ avio_wb24(pb, 0); /* flags */ avio_wb32(pb, entries); /* entry count */ for (i = 0; i < entries; i++) { avio_wb32(pb, ctts_entries[i].count); avio_wb32(pb, ctts_entries[i].duration); } av_free(ctts_entries); return atom_size; } /* Time to sample atom */ static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track) { MOVStts *stts_entries = NULL; uint32_t entries = -1; uint32_t atom_size; int i; if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) { stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */ if (!stts_entries) return AVERROR(ENOMEM); stts_entries[0].count = track->sample_count; stts_entries[0].duration = 1; entries = 1; } else { if (track->entry) { stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */ if (!stts_entries) return AVERROR(ENOMEM); } for (i = 0; i < track->entry; i++) { int duration = get_cluster_duration(track, i); if (i && duration == stts_entries[entries].duration) { stts_entries[entries].count++; /* compress */ } else { entries++; stts_entries[entries].duration = duration; stts_entries[entries].count = 1; } } entries++; /* last one */ } atom_size = 16 + (entries * 8); avio_wb32(pb, atom_size); /* size */ ffio_wfourcc(pb, "stts"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, entries); /* entry count */ for (i = 0; i < entries; i++) { avio_wb32(pb, stts_entries[i].count); avio_wb32(pb, stts_entries[i].duration); } av_free(stts_entries); return atom_size; } static int mov_write_dref_tag(AVIOContext *pb) { avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "dref"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, 1); /* entry count */ avio_wb32(pb, 0xc); /* size */ //FIXME add the alis and rsrc atom ffio_wfourcc(pb, "url "); avio_wb32(pb, 1); /* version & flags */ return 28; } static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track) { struct sgpd_entry { int count; int16_t roll_distance; int group_description_index; }; struct sgpd_entry *sgpd_entries = NULL; int entries = -1; int group = 0; int i, j; const int OPUS_SEEK_PREROLL_MS = 80; int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS, (AVRational){1, 1000}, (AVRational){1, 48000}); if (!track->entry) return 0; sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries)); if (!sgpd_entries) return AVERROR(ENOMEM); av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC); if (track->par->codec_id == AV_CODEC_ID_OPUS) { for (i = 0; i < track->entry; i++) { int roll_samples_remaining = roll_samples; int distance = 0; for (j = i - 1; j >= 0; j--) { roll_samples_remaining -= get_cluster_duration(track, j); distance++; if (roll_samples_remaining <= 0) break; } /* We don't have enough preceeding samples to compute a valid roll_distance here, so this sample can't be independently decoded. */ if (roll_samples_remaining > 0) distance = 0; /* Verify distance is a minimum of 2 (60ms) packets and a maximum of 32 (2.5ms) packets. */ av_assert0(distance == 0 || (distance >= 2 && distance <= 32)); if (i && distance == sgpd_entries[entries].roll_distance) { sgpd_entries[entries].count++; } else { entries++; sgpd_entries[entries].count = 1; sgpd_entries[entries].roll_distance = distance; sgpd_entries[entries].group_description_index = distance ? ++group : 0; } } } else { entries++; sgpd_entries[entries].count = track->sample_count; sgpd_entries[entries].roll_distance = 1; sgpd_entries[entries].group_description_index = ++group; } entries++; if (!group) { av_free(sgpd_entries); return 0; } /* Write sgpd tag */ avio_wb32(pb, 24 + (group * 2)); /* size */ ffio_wfourcc(pb, "sgpd"); avio_wb32(pb, 1 << 24); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, 2); /* default_length */ avio_wb32(pb, group); /* entry_count */ for (i = 0; i < entries; i++) { if (sgpd_entries[i].group_description_index) { avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */ } } /* Write sbgp tag */ avio_wb32(pb, 20 + (entries * 8)); /* size */ ffio_wfourcc(pb, "sbgp"); avio_wb32(pb, 0); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, entries); /* entry_count */ for (i = 0; i < entries; i++) { avio_wb32(pb, sgpd_entries[i].count); /* sample_count */ avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */ } av_free(sgpd_entries); return 0; } static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stbl"); mov_write_stsd_tag(s, pb, mov, track); mov_write_stts_tag(pb, track); if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO || track->par->codec_tag == MKTAG('r','t','p',' ')) && track->has_keyframes && track->has_keyframes < track->entry) mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable) mov_write_sdtp_tag(pb, track); if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS) mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->flags & MOV_TRACK_CTTS && track->entry) { if ((ret = mov_write_ctts_tag(s, pb, track)) < 0) return ret; } mov_write_stsc_tag(pb, track); mov_write_stsz_tag(pb, track); mov_write_stco_tag(pb, track); if (track->cenc.aes_ctr) { ff_mov_cenc_write_stbl_atoms(&track->cenc, pb); } if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) { mov_preroll_write_stbl_atoms(pb, track); } return update_size(pb, pos); } static int mov_write_dinf_tag(AVIOContext *pb) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "dinf"); mov_write_dref_tag(pb); return update_size(pb, pos); } static int mov_write_nmhd_tag(AVIOContext *pb) { avio_wb32(pb, 12); ffio_wfourcc(pb, "nmhd"); avio_wb32(pb, 0); return 12; } static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); const char *font = "Lucida Grande"; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */ avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0); /* text font */ avio_wb16(pb, 0); /* text face */ avio_wb16(pb, 12); /* text size */ avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */ avio_wb16(pb, 0x0000); /* text color (red) */ avio_wb16(pb, 0x0000); /* text color (green) */ avio_wb16(pb, 0x0000); /* text color (blue) */ avio_wb16(pb, 0xffff); /* background color (red) */ avio_wb16(pb, 0xffff); /* background color (green) */ avio_wb16(pb, 0xffff); /* background color (blue) */ avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */ avio_write(pb, font, strlen(font)); /* font name */ return update_size(pb, pos); } static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gmhd"); avio_wb32(pb, 0x18); /* gmin size */ ffio_wfourcc(pb, "gmin");/* generic media info */ avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0x40); /* graphics mode = */ avio_wb16(pb, 0x8000); /* opColor (r?) */ avio_wb16(pb, 0x8000); /* opColor (g?) */ avio_wb16(pb, 0x8000); /* opColor (b?) */ avio_wb16(pb, 0); /* balance */ avio_wb16(pb, 0); /* reserved */ /* * This special text atom is required for * Apple Quicktime chapters. The contents * don't appear to be documented, so the * bytes are copied verbatim. */ if (track->tag != MKTAG('c','6','0','8')) { avio_wb32(pb, 0x2C); /* size */ ffio_wfourcc(pb, "text"); avio_wb16(pb, 0x01); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x01); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00004000); avio_wb16(pb, 0x0000); } if (track->par->codec_tag == MKTAG('t','m','c','d')) { int64_t tmcd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); mov_write_tcmi_tag(pb, track); update_size(pb, tmcd_pos); } else if (track->par->codec_tag == MKTAG('g','p','m','d')) { int64_t gpmd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gpmd"); avio_wb32(pb, 0); /* version */ update_size(pb, gpmd_pos); } return update_size(pb, pos); } static int mov_write_smhd_tag(AVIOContext *pb) { avio_wb32(pb, 16); /* size */ ffio_wfourcc(pb, "smhd"); avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0); /* reserved (balance, normally = 0) */ avio_wb16(pb, 0); /* reserved */ return 16; } static int mov_write_vmhd_tag(AVIOContext *pb) { avio_wb32(pb, 0x14); /* size (always 0x14) */ ffio_wfourcc(pb, "vmhd"); avio_wb32(pb, 0x01); /* version & flags */ avio_wb64(pb, 0); /* reserved (graphics mode = copy) */ return 0x14; } static int is_clcp_track(MOVTrack *track) { return track->tag == MKTAG('c','7','0','8') || track->tag == MKTAG('c','6','0','8'); } static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; const char *hdlr, *descr = NULL, *hdlr_type = NULL; int64_t pos = avio_tell(pb); hdlr = "dhlr"; hdlr_type = "url "; descr = "DataHandler"; if (track) { hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0"; if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { hdlr_type = "vide"; descr = "VideoHandler"; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { hdlr_type = "soun"; descr = "SoundHandler"; } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) { if (is_clcp_track(track)) { hdlr_type = "clcp"; descr = "ClosedCaptionHandler"; } else { if (track->tag == MKTAG('t','x','3','g')) { hdlr_type = "sbtl"; } else if (track->tag == MKTAG('m','p','4','s')) { hdlr_type = "subp"; } else { hdlr_type = "text"; } descr = "SubtitleHandler"; } } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) { hdlr_type = "hint"; descr = "HintHandler"; } else if (track->par->codec_tag == MKTAG('t','m','c','d')) { hdlr_type = "tmcd"; descr = "TimeCodeHandler"; } else if (track->par->codec_tag == MKTAG('g','p','m','d')) { hdlr_type = "meta"; descr = "GoPro MET"; // GoPro Metadata } else { av_log(s, AV_LOG_WARNING, "Unknown hldr_type for %s, writing dummy values\n", av_fourcc2str(track->par->codec_tag)); } if (track->st) { // hdlr.name is used by some players to identify the content title // of the track. So if an alternate handler description is // specified, use it. AVDictionaryEntry *t; t = av_dict_get(track->st->metadata, "handler_name", NULL, 0); if (t && utf8len(t->value)) descr = t->value; } } if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */ descr = ""; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); /* Version & flags */ avio_write(pb, hdlr, 4); /* handler */ ffio_wfourcc(pb, hdlr_type); /* handler type */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ if (!track || track->mode == MODE_MOV) avio_w8(pb, strlen(descr)); /* pascal string */ avio_write(pb, descr, strlen(descr)); /* handler description */ if (track && track->mode != MODE_MOV) avio_w8(pb, 0); /* c string */ return update_size(pb, pos); } static int mov_write_hmhd_tag(AVIOContext *pb) { /* This atom must be present, but leaving the values at zero * seems harmless. */ avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "hmhd"); avio_wb32(pb, 0); /* version, flags */ avio_wb16(pb, 0); /* maxPDUsize */ avio_wb16(pb, 0); /* avgPDUsize */ avio_wb32(pb, 0); /* maxbitrate */ avio_wb32(pb, 0); /* avgbitrate */ avio_wb32(pb, 0); /* reserved */ return 28; } static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "minf"); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) mov_write_vmhd_tag(pb); else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_smhd_tag(pb); else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) { if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) { mov_write_gmhd_tag(pb, track); } else { mov_write_nmhd_tag(pb); } } else if (track->tag == MKTAG('r','t','p',' ')) { mov_write_hmhd_tag(pb); } else if (track->tag == MKTAG('t','m','c','d')) { if (track->mode != MODE_MOV) mov_write_nmhd_tag(pb); else mov_write_gmhd_tag(pb, track); } else if (track->tag == MKTAG('g','p','m','d')) { mov_write_gmhd_tag(pb, track); } if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */ mov_write_hdlr_tag(s, pb, NULL); mov_write_dinf_tag(pb); if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0) return ret; return update_size(pb, pos); } static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int version = track->track_duration < INT32_MAX ? 0 : 1; if (track->mode == MODE_ISM) version = 1; (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */ ffio_wfourcc(pb, "mdhd"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ if (version == 1) { avio_wb64(pb, track->time); avio_wb64(pb, track->time); } else { avio_wb32(pb, track->time); /* creation time */ avio_wb32(pb, track->time); /* modification time */ } avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */ if (!track->entry && mov->mode == MODE_ISM) (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff); else if (!track->entry) (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0); else (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */ avio_wb16(pb, track->language); /* language */ avio_wb16(pb, 0); /* reserved (quality) */ if (version != 0 && track->mode == MODE_MOV) { av_log(NULL, AV_LOG_ERROR, "FATAL error, file duration too long for timebase, this file will not be\n" "playable with quicktime. Choose a different timebase or a different\n" "container format\n"); } return 32; } static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "mdia"); mov_write_mdhd_tag(pb, mov, track); mov_write_hdlr_tag(s, pb, track); if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0) return ret; return update_size(pb, pos); } /* transformation matrix |a b u| |c d v| |tx ty w| */ static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c, int16_t d, int16_t tx, int16_t ty) { avio_wb32(pb, a << 16); /* 16.16 format */ avio_wb32(pb, b << 16); /* 16.16 format */ avio_wb32(pb, 0); /* u in 2.30 format */ avio_wb32(pb, c << 16); /* 16.16 format */ avio_wb32(pb, d << 16); /* 16.16 format */ avio_wb32(pb, 0); /* v in 2.30 format */ avio_wb32(pb, tx << 16); /* 16.16 format */ avio_wb32(pb, ty << 16); /* 16.16 format */ avio_wb32(pb, 1 << 30); /* w in 2.30 format */ } static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, AVStream *st) { int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE, track->timescale, AV_ROUND_UP); int version = duration < INT32_MAX ? 0 : 1; int flags = MOV_TKHD_FLAG_IN_MOVIE; int rotation = 0; int group = 0; uint32_t *display_matrix = NULL; int display_matrix_size, i; if (st) { if (mov->per_stream_grouping) group = st->index; else group = st->codecpar->codec_type; display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &display_matrix_size); if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix)) display_matrix = NULL; } if (track->flags & MOV_TRACK_ENABLED) flags |= MOV_TKHD_FLAG_ENABLED; if (track->mode == MODE_ISM) version = 1; (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */ ffio_wfourcc(pb, "tkhd"); avio_w8(pb, version); avio_wb24(pb, flags); if (version == 1) { avio_wb64(pb, track->time); avio_wb64(pb, track->time); } else { avio_wb32(pb, track->time); /* creation time */ avio_wb32(pb, track->time); /* modification time */ } avio_wb32(pb, track->track_id); /* track-id */ avio_wb32(pb, 0); /* reserved */ if (!track->entry && mov->mode == MODE_ISM) (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff); else if (!track->entry) (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0); else (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration); avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb16(pb, 0); /* layer */ avio_wb16(pb, group); /* alternate group) */ /* Volume, only for audio */ if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) avio_wb16(pb, 0x0100); else avio_wb16(pb, 0); avio_wb16(pb, 0); /* reserved */ /* Matrix structure */ #if FF_API_OLD_ROTATE_API if (st && st->metadata) { AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0); rotation = (rot && rot->value) ? atoi(rot->value) : 0; } #endif if (display_matrix) { for (i = 0; i < 9; i++) avio_wb32(pb, display_matrix[i]); #if FF_API_OLD_ROTATE_API } else if (rotation == 90) { write_matrix(pb, 0, 1, -1, 0, track->par->height, 0); } else if (rotation == 180) { write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height); } else if (rotation == 270) { write_matrix(pb, 0, -1, 1, 0, 0, track->par->width); #endif } else { write_matrix(pb, 1, 0, 0, 1, 0, 0); } /* Track width and height, for visual only */ if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO || track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) { int64_t track_width_1616; if (track->mode == MODE_MOV) { track_width_1616 = track->par->width * 0x10000ULL; } else { track_width_1616 = av_rescale(st->sample_aspect_ratio.num, track->par->width * 0x10000LL, st->sample_aspect_ratio.den); if (!track_width_1616 || track->height != track->par->height || track_width_1616 > UINT32_MAX) track_width_1616 = track->par->width * 0x10000ULL; } if (track_width_1616 > UINT32_MAX) { av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n"); track_width_1616 = 0; } avio_wb32(pb, track_width_1616); if (track->height > 0xFFFF) { av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n"); avio_wb32(pb, 0); } else avio_wb32(pb, track->height * 0x10000U); } else { avio_wb32(pb, 0); avio_wb32(pb, 0); } return 0x5c; } static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track) { int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width, track->par->sample_aspect_ratio.den); int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tapt"); avio_wb32(pb, 20); ffio_wfourcc(pb, "clef"); avio_wb32(pb, 0); avio_wb32(pb, width << 16); avio_wb32(pb, track->par->height << 16); avio_wb32(pb, 20); ffio_wfourcc(pb, "prof"); avio_wb32(pb, 0); avio_wb32(pb, width << 16); avio_wb32(pb, track->par->height << 16); avio_wb32(pb, 20); ffio_wfourcc(pb, "enof"); avio_wb32(pb, 0); avio_wb32(pb, track->par->width << 16); avio_wb32(pb, track->par->height << 16); return update_size(pb, pos); } // This box seems important for the psp playback ... without it the movie seems to hang static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE, track->timescale, AV_ROUND_UP); int version = duration < INT32_MAX ? 0 : 1; int entry_size, entry_count, size; int64_t delay, start_ct = track->start_cts; int64_t start_dts = track->start_dts; if (track->entry) { if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) { av_log(mov->fc, AV_LOG_DEBUG, "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n", track->cluster[0].dts, track->cluster[0].cts, start_dts, start_ct, track->track_id); start_dts = track->cluster[0].dts; start_ct = track->cluster[0].cts; } } delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN); version |= delay < INT32_MAX ? 0 : 1; entry_size = (version == 1) ? 20 : 12; entry_count = 1 + (delay > 0); size = 24 + entry_count * entry_size; /* write the atom data */ avio_wb32(pb, size); ffio_wfourcc(pb, "edts"); avio_wb32(pb, size - 8); ffio_wfourcc(pb, "elst"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ avio_wb32(pb, entry_count); if (delay > 0) { /* add an empty edit to delay presentation */ /* In the positive delay case, the delay includes the cts * offset, and the second edit list entry below trims out * the same amount from the actual content. This makes sure * that the offset last sample is included in the edit * list duration as well. */ if (version == 1) { avio_wb64(pb, delay); avio_wb64(pb, -1); } else { avio_wb32(pb, delay); avio_wb32(pb, -1); } avio_wb32(pb, 0x00010000); } else { /* Avoid accidentally ending up with start_ct = -1 which has got a * special meaning. Normally start_ct should end up positive or zero * here, but use FFMIN in case dts is a small positive integer * rounded to 0 when represented in MOV_TIMESCALE units. */ av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0); start_ct = -FFMIN(start_dts, 0); /* Note, this delay is calculated from the pts of the first sample, * ensuring that we don't reduce the duration for cases with * dts<0 pts=0. */ duration += delay; } /* For fragmented files, we don't know the full length yet. Setting * duration to 0 allows us to only specify the offset, including * the rest of the content (from all future fragments) without specifying * an explicit duration. */ if (mov->flags & FF_MOV_FLAG_FRAGMENT) duration = 0; /* duration */ if (version == 1) { avio_wb64(pb, duration); avio_wb64(pb, start_ct); } else { avio_wb32(pb, duration); avio_wb32(pb, start_ct); } avio_wb32(pb, 0x00010000); return size; } static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 20); // size ffio_wfourcc(pb, "tref"); avio_wb32(pb, 12); // size (subatom) avio_wl32(pb, track->tref_tag); avio_wb32(pb, track->tref_id); return 20; } // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it) static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov) { avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "USMT"); avio_wb32(pb, 0x21d24fce); avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); avio_wb32(pb, 0x1c); // another size here! ffio_wfourcc(pb, "MTDT"); avio_wb32(pb, 0x00010012); avio_wb32(pb, 0x0a); avio_wb32(pb, 0x55c40000); avio_wb32(pb, 0x1); avio_wb32(pb, 0x0); return 0x34; } static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track) { AVFormatContext *ctx = track->rtp_ctx; char buf[1000] = ""; int len; ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track, NULL, NULL, 0, 0, ctx); av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id); len = strlen(buf); avio_wb32(pb, len + 24); ffio_wfourcc(pb, "udta"); avio_wb32(pb, len + 16); ffio_wfourcc(pb, "hnti"); avio_wb32(pb, len + 8); ffio_wfourcc(pb, "sdp "); avio_write(pb, buf, len); return len + 24; } static int mov_write_track_metadata(AVIOContext *pb, AVStream *st, const char *tag, const char *str) { int64_t pos = avio_tell(pb); AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0); if (!t || !utf8len(t->value)) return 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, tag); /* type */ avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */ return update_size(pb, pos); } static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov, AVStream *st) { AVIOContext *pb_buf; int ret, size; uint8_t *buf; if (!st) return 0; ret = avio_open_dyn_buf(&pb_buf); if (ret < 0) return ret; if (mov->mode & (MODE_MP4|MODE_MOV)) mov_write_track_metadata(pb_buf, st, "name", "title"); if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) { avio_wb32(pb, size + 8); ffio_wfourcc(pb, "udta"); avio_write(pb, buf, size); } av_free(buf); return 0; } static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, AVStream *st) { int64_t pos = avio_tell(pb); int entry_backup = track->entry; int chunk_backup = track->chunkCount; int ret; /* If we want to have an empty moov, but some samples already have been * buffered (delay_moov), pretend that no samples have been written yet. */ if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) track->chunkCount = track->entry = 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "trak"); mov_write_tkhd_tag(pb, mov, track, st); av_assert2(mov->use_editlist >= 0); if (track->start_dts != AV_NOPTS_VALUE) { if (mov->use_editlist) mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track)) av_log(mov->fc, AV_LOG_WARNING, "Not writing any edit list even though one would have been required\n"); } if (track->tref_tag) mov_write_tref_tag(pb, track); if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0) return ret; if (track->mode == MODE_PSP) mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box if (track->tag == MKTAG('r','t','p',' ')) mov_write_udta_sdp(pb, track); if (track->mode == MODE_MOV) { if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio); if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) { mov_write_tapt_tag(pb, track); } } if (is_clcp_track(track) && st->sample_aspect_ratio.num) { mov_write_tapt_tag(pb, track); } } mov_write_track_udta_tag(pb, mov, st); track->entry = entry_backup; track->chunkCount = chunk_backup; return update_size(pb, pos); } static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov) { int i, has_audio = 0, has_video = 0; int64_t pos = avio_tell(pb); int audio_profile = mov->iods_audio_profile; int video_profile = mov->iods_video_profile; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO; has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO; } } if (audio_profile < 0) audio_profile = 0xFF - has_audio; if (video_profile < 0) video_profile = 0xFF - has_video; avio_wb32(pb, 0x0); /* size */ ffio_wfourcc(pb, "iods"); avio_wb32(pb, 0); /* version & flags */ put_descr(pb, 0x10, 7); avio_wb16(pb, 0x004f); avio_w8(pb, 0xff); avio_w8(pb, 0xff); avio_w8(pb, audio_profile); avio_w8(pb, video_profile); avio_w8(pb, 0xff); return update_size(pb, pos); } static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 0x20); /* size */ ffio_wfourcc(pb, "trex"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, track->track_id); /* track ID */ avio_wb32(pb, 1); /* default sample description index */ avio_wb32(pb, 0); /* default sample duration */ avio_wb32(pb, 0); /* default sample size */ avio_wb32(pb, 0); /* default sample flags */ return 0; } static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0x0); /* size */ ffio_wfourcc(pb, "mvex"); for (i = 0; i < mov->nb_streams; i++) mov_write_trex_tag(pb, &mov->tracks[i]); return update_size(pb, pos); } static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov) { int max_track_id = 1, i; int64_t max_track_len = 0; int version; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) { int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration, MOV_TIMESCALE, mov->tracks[i].timescale, AV_ROUND_UP); if (max_track_len < max_track_len_temp) max_track_len = max_track_len_temp; if (max_track_id < mov->tracks[i].track_id) max_track_id = mov->tracks[i].track_id; } } /* If using delay_moov, make sure the output is the same as if no * samples had been written yet. */ if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { max_track_len = 0; max_track_id = 1; } version = max_track_len < UINT32_MAX ? 0 : 1; avio_wb32(pb, version == 1 ? 120 : 108); /* size */ ffio_wfourcc(pb, "mvhd"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ if (version == 1) { avio_wb64(pb, mov->time); avio_wb64(pb, mov->time); } else { avio_wb32(pb, mov->time); /* creation time */ avio_wb32(pb, mov->time); /* modification time */ } avio_wb32(pb, MOV_TIMESCALE); (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */ avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */ avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */ avio_wb16(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ /* Matrix structure */ write_matrix(pb, 1, 0, 0, 1, 0, 0); avio_wb32(pb, 0); /* reserved (preview time) */ avio_wb32(pb, 0); /* reserved (preview duration) */ avio_wb32(pb, 0); /* reserved (poster time) */ avio_wb32(pb, 0); /* reserved (selection time) */ avio_wb32(pb, 0); /* reserved (selection duration) */ avio_wb32(pb, 0); /* reserved (current time) */ avio_wb32(pb, max_track_id + 1); /* Next track id */ return 0x6c; } static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { avio_wb32(pb, 33); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); avio_wb32(pb, 0); ffio_wfourcc(pb, "mdir"); ffio_wfourcc(pb, "appl"); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_w8(pb, 0); return 33; } /* helper function to write a data tag with the specified string as data */ static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style) { if (long_style) { int size = 16 + strlen(data); avio_wb32(pb, size); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 1); avio_wb32(pb, 0); avio_write(pb, data, strlen(data)); return size; } else { if (!lang) lang = ff_mov_iso639_to_lang("und", 1); avio_wb16(pb, strlen(data)); /* string length */ avio_wb16(pb, lang); avio_write(pb, data, strlen(data)); return strlen(data) + 4; } } static int mov_write_string_tag(AVIOContext *pb, const char *name, const char *value, int lang, int long_style) { int size = 0; if (value && value[0]) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, name); mov_write_string_data_tag(pb, value, lang, long_style); size = update_size(pb, pos); } return size; } static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s, const char *tag, int *lang) { int l, len, len2; AVDictionaryEntry *t, *t2 = NULL; char tag2[16]; *lang = 0; if (!(t = av_dict_get(s->metadata, tag, NULL, 0))) return NULL; len = strlen(t->key); snprintf(tag2, sizeof(tag2), "%s-", tag); while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) { len2 = strlen(t2->key); if (len2 == len + 4 && !strcmp(t->value, t2->value) && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) { *lang = l; return t; } } return t; } static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb, const char *name, const char *tag, int long_style) { int lang; AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang); if (!t) return 0; return mov_write_string_tag(pb, name, t->value, lang, long_style); } /* iTunes bpm number */ static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s) { AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0); int size = 0, tmpo = t ? atoi(t->value) : 0; if (tmpo) { size = 26; avio_wb32(pb, size); ffio_wfourcc(pb, "tmpo"); avio_wb32(pb, size-8); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 0x15); //type specifier avio_wb32(pb, 0); avio_wb16(pb, tmpo); // data } return size; } /* 3GPP TS 26.244 */ static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb) { int lang; int64_t pos = avio_tell(pb); double latitude, longitude, altitude; int32_t latitude_fix, longitude_fix, altitude_fix; AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang); const char *ptr, *place = ""; char *end; static const char *astronomical_body = "earth"; if (!t) return 0; ptr = t->value; longitude = strtod(ptr, &end); if (end == ptr) { av_log(s, AV_LOG_WARNING, "malformed location metadata\n"); return 0; } ptr = end; latitude = strtod(ptr, &end); if (end == ptr) { av_log(s, AV_LOG_WARNING, "malformed location metadata\n"); return 0; } ptr = end; altitude = strtod(ptr, &end); /* If no altitude was present, the default 0 should be fine */ if (*end == '/') place = end + 1; latitude_fix = (int32_t) ((1 << 16) * latitude); longitude_fix = (int32_t) ((1 << 16) * longitude); altitude_fix = (int32_t) ((1 << 16) * altitude); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "loci"); /* type */ avio_wb32(pb, 0); /* version + flags */ avio_wb16(pb, lang); avio_write(pb, place, strlen(place) + 1); avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */ avio_wb32(pb, latitude_fix); avio_wb32(pb, longitude_fix); avio_wb32(pb, altitude_fix); avio_write(pb, astronomical_body, strlen(astronomical_body) + 1); avio_w8(pb, 0); /* additional notes, null terminated string */ return update_size(pb, pos); } /* iTunes track or disc number */ static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s, int disc) { AVDictionaryEntry *t = av_dict_get(s->metadata, disc ? "disc" : "track", NULL, 0); int size = 0, track = t ? atoi(t->value) : 0; if (track) { int tracks = 0; char *slash = strchr(t->value, '/'); if (slash) tracks = atoi(slash + 1); avio_wb32(pb, 32); /* size */ ffio_wfourcc(pb, disc ? "disk" : "trkn"); avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 0); // 8 bytes empty avio_wb32(pb, 0); avio_wb16(pb, 0); // empty avio_wb16(pb, track); // track / disc number avio_wb16(pb, tracks); // total track / disc number avio_wb16(pb, 0); // empty size = 32; } return size; } static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb, const char *name, const char *tag, int len) { AVDictionaryEntry *t = NULL; uint8_t num; int size = 24 + len; if (len != 1 && len != 4) return -1; if (!(t = av_dict_get(s->metadata, tag, NULL, 0))) return 0; num = atoi(t->value); avio_wb32(pb, size); ffio_wfourcc(pb, name); avio_wb32(pb, size - 8); ffio_wfourcc(pb, "data"); avio_wb32(pb, 0x15); avio_wb32(pb, 0); if (len==4) avio_wb32(pb, num); else avio_w8 (pb, num); return size; } static int mov_write_covr(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int64_t pos = 0; int i; for (i = 0; i < s->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; if (!is_cover_image(trk->st) || trk->cover_image.size <= 0) continue; if (!pos) { pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "covr"); } avio_wb32(pb, 16 + trk->cover_image.size); ffio_wfourcc(pb, "data"); avio_wb32(pb, trk->tag); avio_wb32(pb , 0); avio_write(pb, trk->cover_image.data, trk->cover_image.size); } return pos ? update_size(pb, pos) : 0; } /* iTunes meta data list */ static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ilst"); mov_write_string_metadata(s, pb, "\251nam", "title" , 1); mov_write_string_metadata(s, pb, "\251ART", "artist" , 1); mov_write_string_metadata(s, pb, "aART", "album_artist", 1); mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1); mov_write_string_metadata(s, pb, "\251alb", "album" , 1); mov_write_string_metadata(s, pb, "\251day", "date" , 1); if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) { if (!(s->flags & AVFMT_FLAG_BITEXACT)) mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1); } mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1); mov_write_string_metadata(s, pb, "\251gen", "genre" , 1); mov_write_string_metadata(s, pb, "cprt", "copyright", 1); mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1); mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1); mov_write_string_metadata(s, pb, "desc", "description",1); mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1); mov_write_string_metadata(s, pb, "tvsh", "show" , 1); mov_write_string_metadata(s, pb, "tven", "episode_id",1); mov_write_string_metadata(s, pb, "tvnn", "network" , 1); mov_write_string_metadata(s, pb, "keyw", "keywords" , 1); mov_write_int8_metadata (s, pb, "tves", "episode_sort",4); mov_write_int8_metadata (s, pb, "tvsn", "season_number",4); mov_write_int8_metadata (s, pb, "stik", "media_type",1); mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1); mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1); mov_write_int8_metadata (s, pb, "cpil", "compilation", 1); mov_write_covr(pb, s); mov_write_trkn_tag(pb, mov, s, 0); // track number mov_write_trkn_tag(pb, mov, s, 1); // disc number mov_write_tmpo_tag(pb, s); return update_size(pb, pos); } static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { avio_wb32(pb, 33); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); avio_wb32(pb, 0); ffio_wfourcc(pb, "mdta"); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_w8(pb, 0); return 33; } static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVDictionaryEntry *t = NULL; int64_t pos = avio_tell(pb); int64_t curpos, entry_pos; int count = 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "keys"); avio_wb32(pb, 0); entry_pos = avio_tell(pb); avio_wb32(pb, 0); /* entry count */ while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) { avio_wb32(pb, strlen(t->key) + 8); ffio_wfourcc(pb, "mdta"); avio_write(pb, t->key, strlen(t->key)); count += 1; } curpos = avio_tell(pb); avio_seek(pb, entry_pos, SEEK_SET); avio_wb32(pb, count); // rewrite entry count avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVDictionaryEntry *t = NULL; int64_t pos = avio_tell(pb); int count = 1; /* keys are 1-index based */ avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ilst"); while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) { int64_t entry_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ avio_wb32(pb, count); /* key */ mov_write_string_data_tag(pb, t->value, 0, 1); update_size(pb, entry_pos); count += 1; } return update_size(pb, pos); } /* meta data tags */ static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int size = 0; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "meta"); avio_wb32(pb, 0); if (mov->flags & FF_MOV_FLAG_USE_MDTA) { mov_write_mdta_hdlr_tag(pb, mov, s); mov_write_mdta_keys_tag(pb, mov, s); mov_write_mdta_ilst_tag(pb, mov, s); } else { /* iTunes metadata tag */ mov_write_itunes_hdlr_tag(pb, mov, s); mov_write_ilst_tag(pb, mov, s); } size = update_size(pb, pos); return size; } static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb, const char *name, const char *key) { int len; AVDictionaryEntry *t; if (!(t = av_dict_get(s->metadata, key, NULL, 0))) return 0; len = strlen(t->value); if (len > 0) { int size = len + 8; avio_wb32(pb, size); ffio_wfourcc(pb, name); avio_write(pb, t->value, len); return size; } return 0; } static int ascii_to_wc(AVIOContext *pb, const uint8_t *b) { int val; while (*b) { GET_UTF8(val, *b++, return -1;) avio_wb16(pb, val); } avio_wb16(pb, 0x00); return 0; } static uint16_t language_code(const char *str) { return (((str[0] - 0x60) & 0x1F) << 10) + (((str[1] - 0x60) & 0x1F) << 5) + (( str[2] - 0x60) & 0x1F); } static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s, const char *tag, const char *str) { int64_t pos = avio_tell(pb); AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0); if (!t || !utf8len(t->value)) return 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, tag); /* type */ avio_wb32(pb, 0); /* version + flags */ if (!strcmp(tag, "yrrc")) avio_wb16(pb, atoi(t->value)); else { avio_wb16(pb, language_code("eng")); /* language */ avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */ if (!strcmp(tag, "albm") && (t = av_dict_get(s->metadata, "track", NULL, 0))) avio_w8(pb, atoi(t->value)); } return update_size(pb, pos); } static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s) { int64_t pos = avio_tell(pb); int i, nb_chapters = FFMIN(s->nb_chapters, 255); avio_wb32(pb, 0); // size ffio_wfourcc(pb, "chpl"); avio_wb32(pb, 0x01000000); // version + flags avio_wb32(pb, 0); // unknown avio_w8(pb, nb_chapters); for (i = 0; i < nb_chapters; i++) { AVChapter *c = s->chapters[i]; AVDictionaryEntry *t; avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000})); if ((t = av_dict_get(c->metadata, "title", NULL, 0))) { int len = FFMIN(strlen(t->value), 255); avio_w8(pb, len); avio_write(pb, t->value, len); } else avio_w8(pb, 0); } return update_size(pb, pos); } static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVIOContext *pb_buf; int ret, size; uint8_t *buf; ret = avio_open_dyn_buf(&pb_buf); if (ret < 0) return ret; if (mov->mode & MODE_3GP) { mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist"); mov_write_3gp_udta_tag(pb_buf, s, "titl", "title"); mov_write_3gp_udta_tag(pb_buf, s, "auth", "author"); mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre"); mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment"); mov_write_3gp_udta_tag(pb_buf, s, "albm", "album"); mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright"); mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date"); mov_write_loci_tag(s, pb_buf); } else if (mov->mode == MODE_MOV && !(mov->flags & FF_MOV_FLAG_USE_MDTA)) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0); mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0); mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0); mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0); mov_write_string_metadata(s, pb_buf, "\251day", "date", 0); mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0); // currently ignored by mov.c mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0); // add support for libquicktime, this atom is also actually read by mov.c mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0); mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0); mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0); mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0); mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0); mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0); mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0); mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp"); } else { /* iTunes meta data */ mov_write_meta_tag(pb_buf, mov, s); mov_write_loci_tag(s, pb_buf); } if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL)) mov_write_chpl_tag(pb_buf, s); if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) { avio_wb32(pb, size + 8); ffio_wfourcc(pb, "udta"); avio_write(pb, buf, size); } av_free(buf); return 0; } static void mov_write_psp_udta_tag(AVIOContext *pb, const char *str, const char *lang, int type) { int len = utf8len(str) + 1; if (len <= 0) return; avio_wb16(pb, len * 2 + 10); /* size */ avio_wb32(pb, type); /* type */ avio_wb16(pb, language_code(lang)); /* language */ avio_wb16(pb, 0x01); /* ? */ ascii_to_wc(pb, str); } static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s) { AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0); int64_t pos, pos2; if (title) { pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "USMT"); avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */ avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); pos2 = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "MTDT"); avio_wb16(pb, 4); // ? avio_wb16(pb, 0x0C); /* size */ avio_wb32(pb, 0x0B); /* type */ avio_wb16(pb, language_code("und")); /* language */ avio_wb16(pb, 0x0); /* ? */ avio_wb16(pb, 0x021C); /* data */ if (!(s->flags & AVFMT_FLAG_BITEXACT)) mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04); mov_write_psp_udta_tag(pb, title->value, "eng", 0x01); mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03); update_size(pb, pos2); return update_size(pb, pos); } return 0; } static void build_chunks(MOVTrack *trk) { int i; MOVIentry *chunk = &trk->cluster[0]; uint64_t chunkSize = chunk->size; chunk->chunkNum = 1; if (trk->chunkCount) return; trk->chunkCount = 1; for (i = 1; i<trk->entry; i++){ if (chunk->pos + chunkSize == trk->cluster[i].pos && chunkSize + trk->cluster[i].size < (1<<20)){ chunkSize += trk->cluster[i].size; chunk->samples_in_chunk += trk->cluster[i].entries; } else { trk->cluster[i].chunkNum = chunk->chunkNum+1; chunk=&trk->cluster[i]; chunkSize = chunk->size; trk->chunkCount++; } } } /** * Assign track ids. If option "use_stream_ids_as_track_ids" is set, * the stream ids are used as track ids. * * This assumes mov->tracks and s->streams are in the same order and * there are no gaps in either of them (so mov->tracks[n] refers to * s->streams[n]). * * As an exception, there can be more entries in * s->streams than in mov->tracks, in which case new track ids are * generated (starting after the largest found stream id). */ static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s) { int i; if (mov->track_ids_ok) return 0; if (mov->use_stream_ids_as_track_ids) { int next_generated_track_id = 0; for (i = 0; i < s->nb_streams; i++) { if (s->streams[i]->id > next_generated_track_id) next_generated_track_id = s->streams[i]->id; } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id; } } else { for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].track_id = i + 1; } } mov->track_ids_ok = 1; return 0; } static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int i; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "moov"); mov_setup_track_ids(mov, s); for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].time = mov->time; if (mov->tracks[i].entry) build_chunks(&mov->tracks[i]); } if (mov->chapter_track) for (i = 0; i < s->nb_streams; i++) { mov->tracks[i].tref_tag = MKTAG('c','h','a','p'); mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id; } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->tag == MKTAG('r','t','p',' ')) { track->tref_tag = MKTAG('h','i','n','t'); track->tref_id = mov->tracks[track->src_track].track_id; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { int * fallback, size; fallback = (int*)av_stream_get_side_data(track->st, AV_PKT_DATA_FALLBACK_TRACK, &size); if (fallback != NULL && size == sizeof(int)) { if (*fallback >= 0 && *fallback < mov->nb_streams) { track->tref_tag = MKTAG('f','a','l','l'); track->tref_id = mov->tracks[*fallback].track_id; } } } } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].tag == MKTAG('t','m','c','d')) { int src_trk = mov->tracks[i].src_track; mov->tracks[src_trk].tref_tag = mov->tracks[i].tag; mov->tracks[src_trk].tref_id = mov->tracks[i].track_id; //src_trk may have a different timescale than the tmcd track mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration, mov->tracks[i].timescale, mov->tracks[src_trk].timescale); } } mov_write_mvhd_tag(pb, mov); if (mov->mode != MODE_MOV && !mov->iods_skip) mov_write_iods_tag(pb, mov); for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) { int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL); if (ret < 0) return ret; } } if (mov->flags & FF_MOV_FLAG_FRAGMENT) mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */ if (mov->mode == MODE_PSP) mov_write_uuidusmt_tag(pb, s); else mov_write_udta_tag(pb, mov, s); return update_size(pb, pos); } static void param_write_int(AVIOContext *pb, const char *name, int value) { avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value); } static void param_write_string(AVIOContext *pb, const char *name, const char *value) { avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value); } static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len) { char buf[150]; len = FFMIN(sizeof(buf) / 2 - 1, len); ff_data_to_hex(buf, value, len, 0); buf[2 * len] = '\0'; avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf); } static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int64_t pos = avio_tell(pb); int i; int64_t manifest_bit_rate = 0; AVCPBProperties *props = NULL; static const uint8_t uuid[] = { 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd, 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }; avio_wb32(pb, 0); ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_wb32(pb, 0); avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n"); avio_printf(pb, "<head>\n"); if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT)) avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n", LIBAVFORMAT_IDENT); avio_printf(pb, "</head>\n"); avio_printf(pb, "<body>\n"); avio_printf(pb, "<switch>\n"); mov_setup_track_ids(mov, s); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; const char *type; int track_id = track->track_id; char track_name_buf[32] = { 0 }; AVStream *st = track->st; AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) { type = "video"; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { type = "audio"; } else { continue; } props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL); if (track->par->bit_rate) { manifest_bit_rate = track->par->bit_rate; } else if (props) { manifest_bit_rate = props->max_bitrate; } avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type, manifest_bit_rate); param_write_int(pb, "systemBitrate", manifest_bit_rate); param_write_int(pb, "trackID", track_id); param_write_string(pb, "systemLanguage", lang ? lang->value : "und"); /* Build track name piece by piece: */ /* 1. track type */ av_strlcat(track_name_buf, type, sizeof(track_name_buf)); /* 2. track language, if available */ if (lang) av_strlcatf(track_name_buf, sizeof(track_name_buf), "_%s", lang->value); /* 3. special type suffix */ /* "_cc" = closed captions, "_ad" = audio_description */ if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED) av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf)); else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED) av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf)); param_write_string(pb, "trackName", track_name_buf); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { if (track->par->codec_id == AV_CODEC_ID_H264) { uint8_t *ptr; int size = track->par->extradata_size; if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr, &size)) { param_write_hex(pb, "CodecPrivateData", ptr ? ptr : track->par->extradata, size); av_free(ptr); } param_write_string(pb, "FourCC", "H264"); } else if (track->par->codec_id == AV_CODEC_ID_VC1) { param_write_string(pb, "FourCC", "WVC1"); param_write_hex(pb, "CodecPrivateData", track->par->extradata, track->par->extradata_size); } param_write_int(pb, "MaxWidth", track->par->width); param_write_int(pb, "MaxHeight", track->par->height); param_write_int(pb, "DisplayWidth", track->par->width); param_write_int(pb, "DisplayHeight", track->par->height); } else { if (track->par->codec_id == AV_CODEC_ID_AAC) { switch (track->par->profile) { case FF_PROFILE_AAC_HE_V2: param_write_string(pb, "FourCC", "AACP"); break; case FF_PROFILE_AAC_HE: param_write_string(pb, "FourCC", "AACH"); break; default: param_write_string(pb, "FourCC", "AACL"); } } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) { param_write_string(pb, "FourCC", "WMAP"); } param_write_hex(pb, "CodecPrivateData", track->par->extradata, track->par->extradata_size); param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id)); param_write_int(pb, "Channels", track->par->channels); param_write_int(pb, "SamplingRate", track->par->sample_rate); param_write_int(pb, "BitsPerSample", 16); param_write_int(pb, "PacketSize", track->par->block_align ? track->par->block_align : 4); } avio_printf(pb, "</%s>\n", type); } avio_printf(pb, "</switch>\n"); avio_printf(pb, "</body>\n"); avio_printf(pb, "</smil>\n"); return update_size(pb, pos); } static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov) { avio_wb32(pb, 16); ffio_wfourcc(pb, "mfhd"); avio_wb32(pb, 0); avio_wb32(pb, mov->fragments); return 0; } static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry) { return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO : (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC); } static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int64_t moof_offset) { int64_t pos = avio_tell(pb); uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION | MOV_TFHD_BASE_DATA_OFFSET; if (!track->entry) { flags |= MOV_TFHD_DURATION_IS_EMPTY; } else { flags |= MOV_TFHD_DEFAULT_FLAGS; } if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET) flags &= ~MOV_TFHD_BASE_DATA_OFFSET; if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) { flags &= ~MOV_TFHD_BASE_DATA_OFFSET; flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF; } /* Don't set a default sample size, the silverlight player refuses * to play files with that set. Don't set a default sample duration, * WMP freaks out if it is set. Don't set a base data offset, PIFF * file format says it MUST NOT be set. */ if (track->mode == MODE_ISM) flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION | MOV_TFHD_BASE_DATA_OFFSET); avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "tfhd"); avio_w8(pb, 0); /* version */ avio_wb24(pb, flags); avio_wb32(pb, track->track_id); /* track-id */ if (flags & MOV_TFHD_BASE_DATA_OFFSET) avio_wb64(pb, moof_offset); if (flags & MOV_TFHD_DEFAULT_DURATION) { track->default_duration = get_cluster_duration(track, 0); avio_wb32(pb, track->default_duration); } if (flags & MOV_TFHD_DEFAULT_SIZE) { track->default_size = track->entry ? track->cluster[0].size : 1; avio_wb32(pb, track->default_size); } else track->default_size = -1; if (flags & MOV_TFHD_DEFAULT_FLAGS) { /* Set the default flags based on the second sample, if available. * If the first sample is different, that can be signaled via a separate field. */ if (track->entry > 1) track->default_sample_flags = get_sample_flags(track, &track->cluster[1]); else track->default_sample_flags = track->par->codec_type == AVMEDIA_TYPE_VIDEO ? (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) : MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO; avio_wb32(pb, track->default_sample_flags); } return update_size(pb, pos); } static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int moof_size, int first, int end) { int64_t pos = avio_tell(pb); uint32_t flags = MOV_TRUN_DATA_OFFSET; int i; for (i = first; i < end; i++) { if (get_cluster_duration(track, i) != track->default_duration) flags |= MOV_TRUN_SAMPLE_DURATION; if (track->cluster[i].size != track->default_size) flags |= MOV_TRUN_SAMPLE_SIZE; if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags) flags |= MOV_TRUN_SAMPLE_FLAGS; } if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 && get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags) flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS; if (track->flags & MOV_TRACK_CTTS) flags |= MOV_TRUN_SAMPLE_CTS; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "trun"); if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) avio_w8(pb, 1); /* version */ else avio_w8(pb, 0); /* version */ avio_wb24(pb, flags); avio_wb32(pb, end - first); /* sample count */ if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET && !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) && !mov->first_trun) avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */ else avio_wb32(pb, moof_size + 8 + track->data_offset + track->cluster[first].pos); /* data offset */ if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) avio_wb32(pb, get_sample_flags(track, &track->cluster[first])); for (i = first; i < end; i++) { if (flags & MOV_TRUN_SAMPLE_DURATION) avio_wb32(pb, get_cluster_duration(track, i)); if (flags & MOV_TRUN_SAMPLE_SIZE) avio_wb32(pb, track->cluster[i].size); if (flags & MOV_TRUN_SAMPLE_FLAGS) avio_wb32(pb, get_sample_flags(track, &track->cluster[i])); if (flags & MOV_TRUN_SAMPLE_CTS) avio_wb32(pb, track->cluster[i].cts); } mov->first_trun = 0; return update_size(pb, pos); } static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); static const uint8_t uuid[] = { 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6, 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2 }; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_w8(pb, 1); avio_wb24(pb, 0); avio_wb64(pb, track->start_dts + track->frag_start + track->cluster[0].cts); avio_wb64(pb, track->end_pts - (track->cluster[0].dts + track->cluster[0].cts)); return update_size(pb, pos); } static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int entry) { int n = track->nb_frag_info - 1 - entry, i; int size = 8 + 16 + 4 + 1 + 16*n; static const uint8_t uuid[] = { 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95, 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f }; if (entry < 0) return 0; avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET); avio_wb32(pb, size); ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_w8(pb, 1); avio_wb24(pb, 0); avio_w8(pb, n); for (i = 0; i < n; i++) { int index = entry + 1 + i; avio_wb64(pb, track->frag_info[index].time); avio_wb64(pb, track->frag_info[index].duration); } if (n < mov->ism_lookahead) { int free_size = 16 * (mov->ism_lookahead - n); avio_wb32(pb, free_size); ffio_wfourcc(pb, "free"); ffio_fill(pb, 0, free_size - 8); } return 0; } static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int i; for (i = 0; i < mov->ism_lookahead; i++) { /* Update the tfrf tag for the last ism_lookahead fragments, * nb_frag_info - 1 is the next fragment to be written. */ mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i); } avio_seek(pb, pos, SEEK_SET); return 0; } static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks, int size) { int i; for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; MOVFragmentInfo *info; if ((tracks >= 0 && i != tracks) || !track->entry) continue; track->nb_frag_info++; if (track->nb_frag_info >= track->frag_info_capacity) { unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT; if (av_reallocp_array(&track->frag_info, new_capacity, sizeof(*track->frag_info))) return AVERROR(ENOMEM); track->frag_info_capacity = new_capacity; } info = &track->frag_info[track->nb_frag_info - 1]; info->offset = avio_tell(pb); info->size = size; // Try to recreate the original pts for the first packet // from the fields we have stored info->time = track->start_dts + track->frag_start + track->cluster[0].cts; info->duration = track->end_pts - (track->cluster[0].dts + track->cluster[0].cts); // If the pts is less than zero, we will have trimmed // away parts of the media track using an edit list, // and the corresponding start presentation time is zero. if (info->time < 0) { info->duration += info->time; info->time = 0; } info->tfrf_offset = 0; mov_write_tfrf_tags(pb, mov, track); } return 0; } static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max) { int i; for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if ((tracks >= 0 && i != tracks) || !track->entry) continue; if (track->nb_frag_info > max) { memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info)); track->nb_frag_info = max; } } } static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tfdt"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb64(pb, track->frag_start); return update_size(pb, pos); } static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int64_t moof_offset, int moof_size) { int64_t pos = avio_tell(pb); int i, start = 0; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "traf"); mov_write_tfhd_tag(pb, mov, track, moof_offset); if (mov->mode != MODE_ISM) mov_write_tfdt_tag(pb, track); for (i = 1; i < track->entry; i++) { if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) { mov_write_trun_tag(pb, mov, track, moof_size, start, i); start = i; } } mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry); if (mov->mode == MODE_ISM) { mov_write_tfxd_tag(pb, track); if (mov->ism_lookahead) { int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead; if (track->nb_frag_info > 0) { MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1]; if (!info->tfrf_offset) info->tfrf_offset = avio_tell(pb); } avio_wb32(pb, 8 + size); ffio_wfourcc(pb, "free"); for (i = 0; i < size; i++) avio_w8(pb, 0); } } return update_size(pb, pos); } static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov, int tracks, int moof_size) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "moof"); mov->first_trun = 1; mov_write_mfhd_tag(pb, mov); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (tracks >= 0 && i != tracks) continue; if (!track->entry) continue; mov_write_traf_tag(pb, mov, track, pos, moof_size); } return update_size(pb, pos); } static int mov_write_sidx_tag(AVIOContext *pb, MOVTrack *track, int ref_size, int total_sidx_size) { int64_t pos = avio_tell(pb), offset_pos, end_pos; int64_t presentation_time, duration, offset; int starts_with_SAP, i, entries; if (track->entry) { entries = 1; presentation_time = track->start_dts + track->frag_start + track->cluster[0].cts; duration = track->end_pts - (track->cluster[0].dts + track->cluster[0].cts); starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE; // pts<0 should be cut away using edts if (presentation_time < 0) { duration += presentation_time; presentation_time = 0; } } else { entries = track->nb_frag_info; if (entries <= 0) return 0; presentation_time = track->frag_info[0].time; } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "sidx"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb32(pb, track->track_id); /* reference_ID */ avio_wb32(pb, track->timescale); /* timescale */ avio_wb64(pb, presentation_time); /* earliest_presentation_time */ offset_pos = avio_tell(pb); avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */ avio_wb16(pb, 0); /* reserved */ avio_wb16(pb, entries); /* reference_count */ for (i = 0; i < entries; i++) { if (!track->entry) { if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) { av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n"); } duration = track->frag_info[i].duration; ref_size = track->frag_info[i].size; starts_with_SAP = 1; } avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */ avio_wb32(pb, duration); /* subsegment_duration */ avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */ } end_pos = avio_tell(pb); offset = pos + total_sidx_size - end_pos; avio_seek(pb, offset_pos, SEEK_SET); avio_wb64(pb, offset); avio_seek(pb, end_pos, SEEK_SET); return update_size(pb, pos); } static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov, int tracks, int ref_size) { int i, round, ret; AVIOContext *avio_buf; int total_size = 0; for (round = 0; round < 2; round++) { // First run one round to calculate the total size of all // sidx atoms. // This would be much simpler if we'd only write one sidx // atom, for the first track in the moof. if (round == 0) { if ((ret = ffio_open_null_buf(&avio_buf)) < 0) return ret; } else { avio_buf = pb; } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (tracks >= 0 && i != tracks) continue; // When writing a sidx for the full file, entry is 0, but // we want to include all tracks. ref_size is 0 in this case, // since we read it from frag_info instead. if (!track->entry && ref_size > 0) continue; total_size -= mov_write_sidx_tag(avio_buf, track, ref_size, total_size); } if (round == 0) total_size = ffio_close_null_buf(avio_buf); } return 0; } static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks) { int64_t pos = avio_tell(pb), pts_us, ntp_ts; MOVTrack *first_track; /* PRFT should be associated with at most one track. So, choosing only the * first track. */ if (tracks > 0) return 0; first_track = &(mov->tracks[0]); if (!first_track->entry) { av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n"); return 0; } if (first_track->cluster[0].pts == AV_NOPTS_VALUE) { av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n"); return 0; } if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) { ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time()); } else if (mov->write_prft == MOV_PRFT_SRC_PTS) { pts_us = av_rescale_q(first_track->cluster[0].pts, first_track->st->time_base, AV_TIME_BASE_Q); ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US); } else { av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n", mov->write_prft); return 0; } avio_wb32(pb, 0); // Size place holder ffio_wfourcc(pb, "prft"); // Type avio_w8(pb, 1); // Version avio_wb24(pb, 0); // Flags avio_wb32(pb, first_track->track_id); // reference track ID avio_wb64(pb, ntp_ts); // NTP time stamp avio_wb64(pb, first_track->cluster[0].pts); //media time return update_size(pb, pos); } static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks, int64_t mdat_size) { AVIOContext *avio_buf; int ret, moof_size; if ((ret = ffio_open_null_buf(&avio_buf)) < 0) return ret; mov_write_moof_tag_internal(avio_buf, mov, tracks, 0); moof_size = ffio_close_null_buf(avio_buf); if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size); if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB) mov_write_prft_tag(pb, mov, tracks); if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX || !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) || mov->ism_lookahead) { if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0) return ret; if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) && mov->flags & FF_MOV_FLAG_SKIP_TRAILER) { mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1); } } return mov_write_moof_tag_internal(pb, mov, tracks, moof_size); } static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "tfra"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb32(pb, track->track_id); avio_wb32(pb, 0); /* length of traf/trun/sample num */ avio_wb32(pb, track->nb_frag_info); for (i = 0; i < track->nb_frag_info; i++) { avio_wb64(pb, track->frag_info[i].time); avio_wb64(pb, track->frag_info[i].offset + track->data_offset); avio_w8(pb, 1); /* traf number */ avio_w8(pb, 1); /* trun number */ avio_w8(pb, 1); /* sample number */ } return update_size(pb, pos); } static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "mfra"); /* An empty mfra atom is enough to indicate to the publishing point that * the stream has ended. */ if (mov->flags & FF_MOV_FLAG_ISML) return update_size(pb, pos); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->nb_frag_info) mov_write_tfra_tag(pb, track); } avio_wb32(pb, 16); ffio_wfourcc(pb, "mfro"); avio_wb32(pb, 0); /* version + flags */ avio_wb32(pb, avio_tell(pb) + 4 - pos); return update_size(pb, pos); } static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov) { avio_wb32(pb, 8); // placeholder for extended size field (64 bit) ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free"); mov->mdat_pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "mdat"); return 0; } /* TODO: This needs to be more general */ static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int64_t pos = avio_tell(pb); int has_h264 = 0, has_video = 0; int minor = 0x200; int i; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (is_cover_image(st)) continue; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) has_video = 1; if (st->codecpar->codec_id == AV_CODEC_ID_H264) has_h264 = 1; } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ftyp"); if (mov->major_brand && strlen(mov->major_brand) >= 4) ffio_wfourcc(pb, mov->major_brand); else if (mov->mode == MODE_3GP) { ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4"); minor = has_h264 ? 0x100 : 0x200; } else if (mov->mode & MODE_3G2) { ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a"); minor = has_h264 ? 0x20000 : 0x10000; } else if (mov->mode == MODE_PSP) ffio_wfourcc(pb, "MSNV"); else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) ffio_wfourcc(pb, "iso4"); else if (mov->mode == MODE_MP4) ffio_wfourcc(pb, "isom"); else if (mov->mode == MODE_IPOD) ffio_wfourcc(pb, has_video ? "M4V ":"M4A "); else if (mov->mode == MODE_ISM) ffio_wfourcc(pb, "isml"); else if (mov->mode == MODE_F4V) ffio_wfourcc(pb, "f4v "); else ffio_wfourcc(pb, "qt "); avio_wb32(pb, minor); if (mov->mode == MODE_MOV) ffio_wfourcc(pb, "qt "); else if (mov->mode == MODE_ISM) { ffio_wfourcc(pb, "piff"); } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) { ffio_wfourcc(pb, "isom"); ffio_wfourcc(pb, "iso2"); if (has_h264) ffio_wfourcc(pb, "avc1"); } // We add tfdt atoms when fragmenting, signal this with the iso6 compatible // brand. This is compatible with users that don't understand tfdt. if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM) ffio_wfourcc(pb, "iso6"); if (mov->mode == MODE_3GP) ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4"); else if (mov->mode & MODE_3G2) ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a"); else if (mov->mode == MODE_PSP) ffio_wfourcc(pb, "MSNV"); else if (mov->mode == MODE_MP4) ffio_wfourcc(pb, "mp41"); if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) ffio_wfourcc(pb, "dash"); return update_size(pb, pos); } static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s) { AVStream *video_st = s->streams[0]; AVCodecParameters *video_par = s->streams[0]->codecpar; AVCodecParameters *audio_par = s->streams[1]->codecpar; int audio_rate = audio_par->sample_rate; int64_t frame_rate = video_st->avg_frame_rate.den ? (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den : 0; int audio_kbitrate = audio_par->bit_rate / 1000; int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate); if (frame_rate < 0 || frame_rate > INT32_MAX) { av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000); return AVERROR(EINVAL); } avio_wb32(pb, 0x94); /* size */ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "PROF"); avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */ avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x3); /* 3 sections ? */ avio_wb32(pb, 0x14); /* size */ ffio_wfourcc(pb, "FPRF"); avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x2c); /* size */ ffio_wfourcc(pb, "APRF"); /* audio */ avio_wb32(pb, 0x0); avio_wb32(pb, 0x2); /* TrackID */ ffio_wfourcc(pb, "mp4a"); avio_wb32(pb, 0x20f); avio_wb32(pb, 0x0); avio_wb32(pb, audio_kbitrate); avio_wb32(pb, audio_kbitrate); avio_wb32(pb, audio_rate); avio_wb32(pb, audio_par->channels); avio_wb32(pb, 0x34); /* size */ ffio_wfourcc(pb, "VPRF"); /* video */ avio_wb32(pb, 0x0); avio_wb32(pb, 0x1); /* TrackID */ if (video_par->codec_id == AV_CODEC_ID_H264) { ffio_wfourcc(pb, "avc1"); avio_wb16(pb, 0x014D); avio_wb16(pb, 0x0015); } else { ffio_wfourcc(pb, "mp4v"); avio_wb16(pb, 0x0000); avio_wb16(pb, 0x0103); } avio_wb32(pb, 0x0); avio_wb32(pb, video_kbitrate); avio_wb32(pb, video_kbitrate); avio_wb32(pb, frame_rate); avio_wb32(pb, frame_rate); avio_wb16(pb, video_par->width); avio_wb16(pb, video_par->height); avio_wb32(pb, 0x010001); /* ? */ return 0; } static int mov_write_identification(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; mov_write_ftyp_tag(pb,s); if (mov->mode == MODE_PSP) { int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (is_cover_image(st)) continue; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) video_streams_nb++; else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) audio_streams_nb++; else other_streams_nb++; } if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) { av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n"); return AVERROR(EINVAL); } return mov_write_uuidprof_tag(pb, s); } return 0; } static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags) { uint32_t c = -1; int i, closed_gop = 0; for (i = 0; i < pkt->size - 4; i++) { c = (c << 8) + pkt->data[i]; if (c == 0x1b8) { // gop closed_gop = pkt->data[i + 4] >> 6 & 0x01; } else if (c == 0x100) { // pic int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6); if (!temp_ref || closed_gop) // I picture is not reordered *flags = MOV_SYNC_SAMPLE; else *flags = MOV_PARTIAL_SYNC_SAMPLE; break; } } return 0; } static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk) { const uint8_t *start, *next, *end = pkt->data + pkt->size; int seq = 0, entry = 0; int key = pkt->flags & AV_PKT_FLAG_KEY; start = find_next_marker(pkt->data, end); for (next = start; next < end; start = next) { next = find_next_marker(start + 4, end); switch (AV_RB32(start)) { case VC1_CODE_SEQHDR: seq = 1; break; case VC1_CODE_ENTRYPOINT: entry = 1; break; case VC1_CODE_SLICE: trk->vc1_info.slices = 1; break; } } if (!trk->entry && trk->vc1_info.first_packet_seen) trk->vc1_info.first_frag_written = 1; if (!trk->entry && !trk->vc1_info.first_frag_written) { /* First packet in first fragment */ trk->vc1_info.first_packet_seq = seq; trk->vc1_info.first_packet_entry = entry; trk->vc1_info.first_packet_seen = 1; } else if ((seq && !trk->vc1_info.packet_seq) || (entry && !trk->vc1_info.packet_entry)) { int i; for (i = 0; i < trk->entry; i++) trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE; trk->has_keyframes = 0; if (seq) trk->vc1_info.packet_seq = 1; if (entry) trk->vc1_info.packet_entry = 1; if (!trk->vc1_info.first_frag_written) { /* First fragment */ if ((!seq || trk->vc1_info.first_packet_seq) && (!entry || trk->vc1_info.first_packet_entry)) { /* First packet had the same headers as this one, readd the * sync sample flag. */ trk->cluster[0].flags |= MOV_SYNC_SAMPLE; trk->has_keyframes = 1; } } } if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry) key = seq && entry; else if (trk->vc1_info.packet_seq) key = seq; else if (trk->vc1_info.packet_entry) key = entry; if (key) { trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE; trk->has_keyframes++; } } static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; int ret, buf_size; uint8_t *buf; int i, offset; if (!track->mdat_buf) return 0; if (!mov->mdat_buf) { if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0) return ret; } buf_size = avio_close_dyn_buf(track->mdat_buf, &buf); track->mdat_buf = NULL; offset = avio_tell(mov->mdat_buf); avio_write(mov->mdat_buf, buf, buf_size); av_free(buf); for (i = track->entries_flushed; i < track->entry; i++) track->cluster[i].pos += offset; track->entries_flushed = track->entry; return 0; } static int mov_flush_fragment(AVFormatContext *s, int force) { MOVMuxContext *mov = s->priv_data; int i, first_track = -1; int64_t mdat_size = 0; int ret; int has_video = 0, starts_with_key = 0, first_video_track = 1; if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) return 0; // Try to fill in the duration of the last packet in each stream // from queued packets in the interleave queues. If the flushing // of fragments was triggered automatically by an AVPacket, we // already have reliable info for the end of that track, but other // tracks may need to be filled in. for (i = 0; i < s->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (!track->end_reliable) { AVPacket pkt; if (!ff_interleaved_peek(s, i, &pkt, 1)) { if (track->dts_shift != AV_NOPTS_VALUE) pkt.dts += track->dts_shift; track->track_duration = pkt.dts - track->start_dts; if (pkt.pts != AV_NOPTS_VALUE) track->end_pts = pkt.pts; else track->end_pts = pkt.dts; } } } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->entry <= 1) continue; // Sample durations are calculated as the diff of dts values, // but for the last sample in a fragment, we don't know the dts // of the first sample in the next fragment, so we have to rely // on what was set as duration in the AVPacket. Not all callers // set this though, so we might want to replace it with an // estimate if it currently is zero. if (get_cluster_duration(track, track->entry - 1) != 0) continue; // Use the duration (i.e. dts diff) of the second last sample for // the last one. This is a wild guess (and fatal if it turns out // to be too long), but probably the best we can do - having a zero // duration is bad as well. track->track_duration += get_cluster_duration(track, track->entry - 2); track->end_pts += get_cluster_duration(track, track->entry - 2); if (!mov->missing_duration_warned) { av_log(s, AV_LOG_WARNING, "Estimating the duration of the last packet in a " "fragment, consider setting the duration field in " "AVPacket instead.\n"); mov->missing_duration_warned = 1; } } if (!mov->moov_written) { int64_t pos = avio_tell(s->pb); uint8_t *buf; int buf_size, moov_size; for (i = 0; i < mov->nb_streams; i++) if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st)) break; /* Don't write the initial moov unless all tracks have data */ if (i < mov->nb_streams && !force) return 0; moov_size = get_moov_size(s); for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset = pos + moov_size + 8; avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER); if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) mov_write_identification(s->pb, s); if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0) return ret; if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) { if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(s->pb); avio_flush(s->pb); mov->moov_written = 1; return 0; } buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf); mov->mdat_buf = NULL; avio_wb32(s->pb, buf_size + 8); ffio_wfourcc(s->pb, "mdat"); avio_write(s->pb, buf, buf_size); av_free(buf); if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(s->pb); mov->moov_written = 1; mov->mdat_size = 0; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry) mov->tracks[i].frag_start += mov->tracks[i].start_dts + mov->tracks[i].track_duration - mov->tracks[i].cluster[0].dts; mov->tracks[i].entry = 0; mov->tracks[i].end_reliable = 0; } avio_flush(s->pb); return 0; } if (mov->frag_interleave) { for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; int ret; if ((ret = mov_flush_fragment_interleaving(s, track)) < 0) return ret; } if (!mov->mdat_buf) return 0; mdat_size = avio_tell(mov->mdat_buf); } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave) track->data_offset = 0; else track->data_offset = mdat_size; if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { has_video = 1; if (first_video_track) { if (track->entry) starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE; first_video_track = 0; } } if (!track->entry) continue; if (track->mdat_buf) mdat_size += avio_tell(track->mdat_buf); if (first_track < 0) first_track = i; } if (!mdat_size) return 0; avio_write_marker(s->pb, av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale), (has_video ? starts_with_key : mov->tracks[first_track].cluster[0].flags & MOV_SYNC_SAMPLE) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; int buf_size, write_moof = 1, moof_tracks = -1; uint8_t *buf; int64_t duration = 0; if (track->entry) duration = track->start_dts + track->track_duration - track->cluster[0].dts; if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) { if (!track->mdat_buf) continue; mdat_size = avio_tell(track->mdat_buf); moof_tracks = i; } else { write_moof = i == first_track; } if (write_moof) { avio_flush(s->pb); mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size); mov->fragments++; avio_wb32(s->pb, mdat_size + 8); ffio_wfourcc(s->pb, "mdat"); } if (track->entry) track->frag_start += duration; track->entry = 0; track->entries_flushed = 0; track->end_reliable = 0; if (!mov->frag_interleave) { if (!track->mdat_buf) continue; buf_size = avio_close_dyn_buf(track->mdat_buf, &buf); track->mdat_buf = NULL; } else { if (!mov->mdat_buf) continue; buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf); mov->mdat_buf = NULL; } avio_write(s->pb, buf, buf_size); av_free(buf); } mov->mdat_size = 0; avio_flush(s->pb); return 0; } static int mov_auto_flush_fragment(AVFormatContext *s, int force) { MOVMuxContext *mov = s->priv_data; int had_moov = mov->moov_written; int ret = mov_flush_fragment(s, force); if (ret < 0) return ret; // If using delay_moov, the first flush only wrote the moov, // not the actual moof+mdat pair, thus flush once again. if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV) ret = mov_flush_fragment(s, force); return ret; } static int check_pkt(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk = &mov->tracks[pkt->stream_index]; int64_t ref; uint64_t duration; if (trk->entry) { ref = trk->cluster[trk->entry - 1].dts; } else if ( trk->start_dts != AV_NOPTS_VALUE && !trk->frag_discont) { ref = trk->start_dts + trk->track_duration; } else ref = pkt->dts; // Skip tests for the first packet if (trk->dts_shift != AV_NOPTS_VALUE) { /* With negative CTS offsets we have set an offset to the DTS, * reverse this for the check. */ ref -= trk->dts_shift; } duration = pkt->dts - ref; if (pkt->dts < ref || duration >= INT_MAX) { av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n", duration, pkt->dts ); pkt->dts = ref + 1; pkt->pts = AV_NOPTS_VALUE; } if (pkt->duration < 0 || pkt->duration > INT_MAX) { av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration); return AVERROR(EINVAL); } return 0; } int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; AVIOContext *pb = s->pb; MOVTrack *trk = &mov->tracks[pkt->stream_index]; AVCodecParameters *par = trk->par; unsigned int samples_in_chunk = 0; int size = pkt->size, ret = 0; uint8_t *reformatted_data = NULL; ret = check_pkt(s, pkt); if (ret < 0) return ret; if (mov->flags & FF_MOV_FLAG_FRAGMENT) { int ret; if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { if (mov->frag_interleave && mov->fragments > 0) { if (trk->entry - trk->entries_flushed >= mov->frag_interleave) { if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0) return ret; } } if (!trk->mdat_buf) { if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0) return ret; } pb = trk->mdat_buf; } else { if (!mov->mdat_buf) { if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0) return ret; } pb = mov->mdat_buf; } } if (par->codec_id == AV_CODEC_ID_AMR_NB) { /* We must find out how many AMR blocks there are in one packet */ static const uint16_t packed_size[16] = {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1}; int len = 0; while (len < size && samples_in_chunk < 100) { len += packed_size[(pkt->data[len] >> 3) & 0x0F]; samples_in_chunk++; } if (samples_in_chunk > 1) { av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n"); return -1; } } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS || par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) { samples_in_chunk = trk->par->frame_size; } else if (trk->sample_size) samples_in_chunk = size / trk->sample_size; else samples_in_chunk = 1; /* copy extradata if it exists */ if (trk->vos_len == 0 && par->extradata_size > 0 && !TAG_IS_AVCI(trk->tag) && (par->codec_id != AV_CODEC_ID_DNXHD)) { trk->vos_len = par->extradata_size; trk->vos_data = av_malloc(trk->vos_len); if (!trk->vos_data) { ret = AVERROR(ENOMEM); goto err; } memcpy(trk->vos_data, par->extradata, trk->vos_len); } if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { if (!s->streams[pkt->stream_index]->nb_frames) { av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: " "use the audio bitstream filter 'aac_adtstoasc' to fix it " "('-bsf:a aac_adtstoasc' option with ffmpeg)\n"); return -1; } av_log(s, AV_LOG_WARNING, "aac bitstream error\n"); } if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) { /* from x264 or from bytestream H.264 */ /* NAL reformatting needed */ if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) { ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data, &size); avio_write(pb, reformatted_data, size); } else { if (trk->cenc.aes_ctr) { size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size); if (size < 0) { ret = size; goto err; } } else { size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size); } } } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 && (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) { /* extradata is Annex B, assume the bitstream is too and convert it */ if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) { ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL); avio_write(pb, reformatted_data, size); } else { size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL); } #if CONFIG_AC3_PARSER } else if (par->codec_id == AV_CODEC_ID_EAC3) { size = handle_eac3(mov, pkt, trk); if (size < 0) return size; else if (!size) goto end; avio_write(pb, pkt->data, size); #endif } else { if (trk->cenc.aes_ctr) { if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) { int nal_size_length = (par->extradata[4] & 0x3) + 1; ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size); } else { ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size); } if (ret) { goto err; } } else { avio_write(pb, pkt->data, size); } } if ((par->codec_id == AV_CODEC_ID_DNXHD || par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) { /* copy frame to create needed atoms */ trk->vos_len = size; trk->vos_data = av_malloc(size); if (!trk->vos_data) { ret = AVERROR(ENOMEM); goto err; } memcpy(trk->vos_data, pkt->data, size); } if (trk->entry >= trk->cluster_capacity) { unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE); if (av_reallocp_array(&trk->cluster, new_capacity, sizeof(*trk->cluster))) { ret = AVERROR(ENOMEM); goto err; } trk->cluster_capacity = new_capacity; } trk->cluster[trk->entry].pos = avio_tell(pb) - size; trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk; trk->cluster[trk->entry].chunkNum = 0; trk->cluster[trk->entry].size = size; trk->cluster[trk->entry].entries = samples_in_chunk; trk->cluster[trk->entry].dts = pkt->dts; trk->cluster[trk->entry].pts = pkt->pts; if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) { if (!trk->frag_discont) { /* First packet of a new fragment. We already wrote the duration * of the last packet of the previous fragment based on track_duration, * which might not exactly match our dts. Therefore adjust the dts * of this packet to be what the previous packets duration implies. */ trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration; /* We also may have written the pts and the corresponding duration * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with * the next fragment. This means the cts of the first sample must * be the same in all fragments, unless end_pts was updated by * the packet causing the fragment to be written. */ if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) || mov->mode == MODE_ISM) pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts; } else { /* New fragment, but discontinuous from previous fragments. * Pretend the duration sum of the earlier fragments is * pkt->dts - trk->start_dts. */ trk->frag_start = pkt->dts - trk->start_dts; trk->end_pts = AV_NOPTS_VALUE; trk->frag_discont = 0; } } if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) { /* Not using edit lists and shifting the first track to start from zero. * If the other streams start from a later timestamp, we won't be able * to signal the difference in starting time without an edit list. * Thus move the timestamp for this first sample to 0, increasing * its duration instead. */ trk->cluster[trk->entry].dts = trk->start_dts = 0; } if (trk->start_dts == AV_NOPTS_VALUE) { trk->start_dts = pkt->dts; if (trk->frag_discont) { if (mov->use_editlist) { /* Pretend the whole stream started at pts=0, with earlier fragments * already written. If the stream started at pts=0, the duration sum * of earlier fragments would have been pkt->pts. */ trk->frag_start = pkt->pts; trk->start_dts = pkt->dts - pkt->pts; } else { /* Pretend the whole stream started at dts=0, with earlier fragments * already written, with a duration summing up to pkt->dts. */ trk->frag_start = pkt->dts; trk->start_dts = 0; } trk->frag_discont = 0; } else if (pkt->dts && mov->moov_written) av_log(s, AV_LOG_WARNING, "Track %d starts with a nonzero dts %"PRId64", while the moov " "already has been written. Set the delay_moov flag to handle " "this case.\n", pkt->stream_index, pkt->dts); } trk->track_duration = pkt->dts - trk->start_dts + pkt->duration; trk->last_sample_is_subtitle_end = 0; if (pkt->pts == AV_NOPTS_VALUE) { av_log(s, AV_LOG_WARNING, "pts has no value\n"); pkt->pts = pkt->dts; } if (pkt->dts != pkt->pts) trk->flags |= MOV_TRACK_CTTS; trk->cluster[trk->entry].cts = pkt->pts - pkt->dts; trk->cluster[trk->entry].flags = 0; if (trk->start_cts == AV_NOPTS_VALUE) trk->start_cts = pkt->pts - pkt->dts; if (trk->end_pts == AV_NOPTS_VALUE) trk->end_pts = trk->cluster[trk->entry].dts + trk->cluster[trk->entry].cts + pkt->duration; else trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts + trk->cluster[trk->entry].cts + pkt->duration); if (par->codec_id == AV_CODEC_ID_VC1) { mov_parse_vc1_frame(pkt, trk); } else if (pkt->flags & AV_PKT_FLAG_KEY) { if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO && trk->entry > 0) { // force sync sample for the first key frame mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags); if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE) trk->flags |= MOV_TRACK_STPS; } else { trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE; } if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE) trk->has_keyframes++; } if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) { trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE; trk->has_disposable++; } trk->entry++; trk->sample_count += samples_in_chunk; mov->mdat_size += size; if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry, reformatted_data, size); end: err: av_free(reformatted_data); return ret; } static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk = &mov->tracks[pkt->stream_index]; AVCodecParameters *par = trk->par; int64_t frag_duration = 0; int size = pkt->size; int ret = check_pkt(s, pkt); if (ret < 0) return ret; if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) { int i; for (i = 0; i < s->nb_streams; i++) mov->tracks[i].frag_discont = 1; mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT; } if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) { if (trk->dts_shift == AV_NOPTS_VALUE) trk->dts_shift = pkt->pts - pkt->dts; pkt->dts += trk->dts_shift; } if (trk->par->codec_id == AV_CODEC_ID_MP4ALS || trk->par->codec_id == AV_CODEC_ID_AAC || trk->par->codec_id == AV_CODEC_ID_FLAC) { int side_size = 0; uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size); if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) { void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!newextra) return AVERROR(ENOMEM); av_free(par->extradata); par->extradata = newextra; memcpy(par->extradata, side, side_size); par->extradata_size = side_size; if (!pkt->size) // Flush packet mov->need_rewrite_extradata = 1; } } if (!pkt->size) { if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) { trk->start_dts = pkt->dts; if (pkt->pts != AV_NOPTS_VALUE) trk->start_cts = pkt->pts - pkt->dts; else trk->start_cts = 0; } return 0; /* Discard 0 sized packets */ } if (trk->entry && pkt->stream_index < s->nb_streams) frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts, s->streams[pkt->stream_index]->time_base, AV_TIME_BASE_Q); if ((mov->max_fragment_duration && frag_duration >= mov->max_fragment_duration) || (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) || (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME && par->codec_type == AVMEDIA_TYPE_VIDEO && trk->entry && pkt->flags & AV_PKT_FLAG_KEY) || (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) { if (frag_duration >= mov->min_fragment_duration) { // Set the duration of this track to line up with the next // sample in this track. This avoids relying on AVPacket // duration, but only helps for this particular track, not // for the other ones that are flushed at the same time. trk->track_duration = pkt->dts - trk->start_dts; if (pkt->pts != AV_NOPTS_VALUE) trk->end_pts = pkt->pts; else trk->end_pts = pkt->dts; trk->end_reliable = 1; mov_auto_flush_fragment(s, 0); } } return ff_mov_write_packet(s, pkt); } static int mov_write_subtitle_end_packet(AVFormatContext *s, int stream_index, int64_t dts) { AVPacket end; uint8_t data[2] = {0}; int ret; av_init_packet(&end); end.size = sizeof(data); end.data = data; end.pts = dts; end.dts = dts; end.duration = 0; end.stream_index = stream_index; ret = mov_write_single_packet(s, &end); av_packet_unref(&end); return ret; } static int mov_write_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk; if (!pkt) { mov_flush_fragment(s, 1); return 1; } trk = &mov->tracks[pkt->stream_index]; if (is_cover_image(trk->st)) { int ret; if (trk->st->nb_frames >= 1) { if (trk->st->nb_frames == 1) av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d," " ignoring.\n", pkt->stream_index); return 0; } if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0) return ret; return 0; } else { int i; if (!pkt->size) return mov_write_single_packet(s, pkt); /* Passthrough. */ /* * Subtitles require special handling. * * 1) For full complaince, every track must have a sample at * dts == 0, which is rarely true for subtitles. So, as soon * as we see any packet with dts > 0, write an empty subtitle * at dts == 0 for any subtitle track with no samples in it. * * 2) For each subtitle track, check if the current packet's * dts is past the duration of the last subtitle sample. If * so, we now need to write an end sample for that subtitle. * * This must be done conditionally to allow for subtitles that * immediately replace each other, in which case an end sample * is not needed, and is, in fact, actively harmful. * * 3) See mov_write_trailer for how the final end sample is * handled. */ for (i = 0; i < mov->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; int ret; if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT && trk->track_duration < pkt->dts && (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) { ret = mov_write_subtitle_end_packet(s, i, trk->track_duration); if (ret < 0) return ret; trk->last_sample_is_subtitle_end = 1; } } if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) { AVPacket *opkt = pkt; int reshuffle_ret, ret; if (trk->is_unaligned_qt_rgb) { int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16; int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2; reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride); if (reshuffle_ret < 0) return reshuffle_ret; } else reshuffle_ret = 0; if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) { ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette); if (ret < 0) goto fail; if (ret) trk->pal_done++; } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO && (trk->par->format == AV_PIX_FMT_GRAY8 || trk->par->format == AV_PIX_FMT_MONOBLACK)) { for (i = 0; i < pkt->size; i++) pkt->data[i] = ~pkt->data[i]; } if (reshuffle_ret) { ret = mov_write_single_packet(s, pkt); fail: if (reshuffle_ret) av_packet_free(&pkt); return ret; } } return mov_write_single_packet(s, pkt); } } // QuickTime chapters involve an additional text track with the chapter names // as samples, and a tref pointing from the other tracks to the chapter one. static int mov_create_chapter_track(AVFormatContext *s, int tracknum) { AVIOContext *pb; MOVMuxContext *mov = s->priv_data; MOVTrack *track = &mov->tracks[tracknum]; AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY }; int i, len; track->mode = mov->mode; track->tag = MKTAG('t','e','x','t'); track->timescale = MOV_TIMESCALE; track->par = avcodec_parameters_alloc(); if (!track->par) return AVERROR(ENOMEM); track->par->codec_type = AVMEDIA_TYPE_SUBTITLE; #if 0 // These properties are required to make QT recognize the chapter track uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, }; if (ff_alloc_extradata(track->par, sizeof(chapter_properties))) return AVERROR(ENOMEM); memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties)); #else if (avio_open_dyn_buf(&pb) >= 0) { int size; uint8_t *buf; /* Stub header (usually for Quicktime chapter track) */ // TextSampleEntry avio_wb32(pb, 0x01); // displayFlags avio_w8(pb, 0x00); // horizontal justification avio_w8(pb, 0x00); // vertical justification avio_w8(pb, 0x00); // bgColourRed avio_w8(pb, 0x00); // bgColourGreen avio_w8(pb, 0x00); // bgColourBlue avio_w8(pb, 0x00); // bgColourAlpha // BoxRecord avio_wb16(pb, 0x00); // defTextBoxTop avio_wb16(pb, 0x00); // defTextBoxLeft avio_wb16(pb, 0x00); // defTextBoxBottom avio_wb16(pb, 0x00); // defTextBoxRight // StyleRecord avio_wb16(pb, 0x00); // startChar avio_wb16(pb, 0x00); // endChar avio_wb16(pb, 0x01); // fontID avio_w8(pb, 0x00); // fontStyleFlags avio_w8(pb, 0x00); // fontSize avio_w8(pb, 0x00); // fgColourRed avio_w8(pb, 0x00); // fgColourGreen avio_w8(pb, 0x00); // fgColourBlue avio_w8(pb, 0x00); // fgColourAlpha // FontTableBox avio_wb32(pb, 0x0D); // box size ffio_wfourcc(pb, "ftab"); // box atom name avio_wb16(pb, 0x01); // entry count // FontRecord avio_wb16(pb, 0x01); // font ID avio_w8(pb, 0x00); // font name length if ((size = avio_close_dyn_buf(pb, &buf)) > 0) { track->par->extradata = buf; track->par->extradata_size = size; } else { av_freep(&buf); } } #endif for (i = 0; i < s->nb_chapters; i++) { AVChapter *c = s->chapters[i]; AVDictionaryEntry *t; int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE}); pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE}); pkt.duration = end - pkt.dts; if ((t = av_dict_get(c->metadata, "title", NULL, 0))) { static const char encd[12] = { 0x00, 0x00, 0x00, 0x0C, 'e', 'n', 'c', 'd', 0x00, 0x00, 0x01, 0x00 }; len = strlen(t->value); pkt.size = len + 2 + 12; pkt.data = av_malloc(pkt.size); if (!pkt.data) return AVERROR(ENOMEM); AV_WB16(pkt.data, len); memcpy(pkt.data + 2, t->value, len); memcpy(pkt.data + len + 2, encd, sizeof(encd)); ff_mov_write_packet(s, &pkt); av_freep(&pkt.data); } } return 0; } static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr) { int ret; /* compute the frame number */ ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s); return ret; } static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc) { int ret; MOVMuxContext *mov = s->priv_data; MOVTrack *track = &mov->tracks[index]; AVStream *src_st = s->streams[src_index]; AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4}; AVRational rate = find_fps(s, src_st); /* tmcd track based on video stream */ track->mode = mov->mode; track->tag = MKTAG('t','m','c','d'); track->src_track = src_index; track->timescale = mov->tracks[src_index].timescale; if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME) track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME; /* set st to src_st for metadata access*/ track->st = src_st; /* encode context: tmcd data stream */ track->par = avcodec_parameters_alloc(); if (!track->par) return AVERROR(ENOMEM); track->par->codec_type = AVMEDIA_TYPE_DATA; track->par->codec_tag = track->tag; track->st->avg_frame_rate = av_inv_q(rate); /* the tmcd track just contains one packet with the frame number */ pkt.data = av_malloc(pkt.size); if (!pkt.data) return AVERROR(ENOMEM); AV_WB32(pkt.data, tc.start); ret = ff_mov_write_packet(s, &pkt); av_free(pkt.data); return ret; } /* * st->disposition controls the "enabled" flag in the tkhd tag. * QuickTime will not play a track if it is not enabled. So make sure * that one track of each type (audio, video, subtitle) is enabled. * * Subtitles are special. For audio and video, setting "enabled" also * makes the track "default" (i.e. it is rendered when played). For * subtitles, an "enabled" subtitle is not rendered by default, but * if no subtitle is enabled, the subtitle menu in QuickTime will be * empty! */ static void enable_tracks(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; int enabled[AVMEDIA_TYPE_NB]; int first[AVMEDIA_TYPE_NB]; for (i = 0; i < AVMEDIA_TYPE_NB; i++) { enabled[i] = 0; first[i] = -1; } for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN || st->codecpar->codec_type >= AVMEDIA_TYPE_NB || is_cover_image(st)) continue; if (first[st->codecpar->codec_type] < 0) first[st->codecpar->codec_type] = i; if (st->disposition & AV_DISPOSITION_DEFAULT) { mov->tracks[i].flags |= MOV_TRACK_ENABLED; enabled[st->codecpar->codec_type]++; } } for (i = 0; i < AVMEDIA_TYPE_NB; i++) { switch (i) { case AVMEDIA_TYPE_VIDEO: case AVMEDIA_TYPE_AUDIO: case AVMEDIA_TYPE_SUBTITLE: if (enabled[i] > 1) mov->per_stream_grouping = 1; if (!enabled[i] && first[i] >= 0) mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED; break; } } } static void mov_free(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; if (mov->chapter_track) { if (mov->tracks[mov->chapter_track].par) av_freep(&mov->tracks[mov->chapter_track].par->extradata); av_freep(&mov->tracks[mov->chapter_track].par); } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) ff_mov_close_hinting(&mov->tracks[i]); else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd) av_freep(&mov->tracks[i].par); av_freep(&mov->tracks[i].cluster); av_freep(&mov->tracks[i].frag_info); av_packet_unref(&mov->tracks[i].cover_image); if (mov->tracks[i].vos_len) av_freep(&mov->tracks[i].vos_data); ff_mov_cenc_free(&mov->tracks[i].cenc); } av_freep(&mov->tracks); } static uint32_t rgb_to_yuv(uint32_t rgb) { uint8_t r, g, b; int y, cb, cr; r = (rgb >> 16) & 0xFF; g = (rgb >> 8) & 0xFF; b = (rgb ) & 0xFF; y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000); cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000); cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000); return (y << 16) | (cr << 8) | cb; } static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track, AVStream *st) { int i, width = 720, height = 480; int have_palette = 0, have_size = 0; uint32_t palette[16]; char *cur = st->codecpar->extradata; while (cur && *cur) { if (strncmp("palette:", cur, 8) == 0) { int i, count; count = sscanf(cur + 8, "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"", &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3], &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7], &palette[ 8], &palette[ 9], &palette[10], &palette[11], &palette[12], &palette[13], &palette[14], &palette[15]); for (i = 0; i < count; i++) { palette[i] = rgb_to_yuv(palette[i]); } have_palette = 1; } else if (!strncmp("size:", cur, 5)) { sscanf(cur + 5, "%dx%d", &width, &height); have_size = 1; } if (have_palette && have_size) break; cur += strcspn(cur, "\n\r"); cur += strspn(cur, "\n\r"); } if (have_palette) { track->vos_data = av_malloc(16*4); if (!track->vos_data) return AVERROR(ENOMEM); for (i = 0; i < 16; i++) { AV_WB32(track->vos_data + i * 4, palette[i]); } track->vos_len = 16 * 4; } st->codecpar->width = width; st->codecpar->height = track->height = height; return 0; } static int mov_init(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0); int i, ret; mov->fc = s; /* Default mode == MP4 */ mov->mode = MODE_MP4; if (s->oformat) { if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP; else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2; else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV; else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP; else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD; else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM; else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V; } if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) mov->flags |= FF_MOV_FLAG_EMPTY_MOOV; /* Set the FRAGMENT flag if any of the fragmentation methods are * enabled. */ if (mov->max_fragment_duration || mov->max_fragment_size || mov->flags & (FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_FRAG_KEYFRAME | FF_MOV_FLAG_FRAG_CUSTOM | FF_MOV_FLAG_FRAG_EVERY_FRAME)) mov->flags |= FF_MOV_FLAG_FRAGMENT; /* Set other implicit flags immediately */ if (mov->mode == MODE_ISM) mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF | FF_MOV_FLAG_FRAGMENT; if (mov->flags & FF_MOV_FLAG_DASH) mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_DEFAULT_BASE_MOOF; if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) { av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n"); s->flags &= ~AVFMT_FLAG_AUTO_BSF; } if (mov->flags & FF_MOV_FLAG_FASTSTART) { mov->reserved_moov_size = -1; } if (mov->use_editlist < 0) { mov->use_editlist = 1; if (mov->flags & FF_MOV_FLAG_FRAGMENT && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { // If we can avoid needing an edit list by shifting the // tracks, prefer that over (trying to) write edit lists // in fragmented output. if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) mov->use_editlist = 0; } } if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist) av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n"); if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO) s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO; /* Clear the omit_tfhd_offset flag if default_base_moof is set; * if the latter is set that's enough and omit_tfhd_offset doesn't * add anything extra on top of that. */ if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET; if (mov->frag_interleave && mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) { av_log(s, AV_LOG_ERROR, "Sample interleaving in fragments is mutually exclusive with " "omit_tfhd_offset and separate_moof\n"); return AVERROR(EINVAL); } /* Non-seekable output is ok if using fragmentation. If ism_lookahead * is enabled, we don't support non-seekable output at all. */ if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) { av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n"); return AVERROR(EINVAL); } mov->nb_streams = s->nb_streams; if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) mov->chapter_track = mov->nb_streams++; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { for (i = 0; i < s->nb_streams; i++) if (rtp_hinting_needed(s->streams[i])) mov->nb_streams++; } if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4) || mov->write_tmcd == 1) { /* +1 tmcd track for each video stream with a timecode */ for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; AVDictionaryEntry *t = global_tcr; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) { AVTimecode tc; ret = mov_check_timecode_track(s, &tc, i, t->value); if (ret >= 0) mov->nb_meta_tmcd++; } } /* check if there is already a tmcd track to remux */ if (mov->nb_meta_tmcd) { for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) { av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track " "so timecode metadata are now ignored\n"); mov->nb_meta_tmcd = 0; } } } mov->nb_streams += mov->nb_meta_tmcd; } // Reserve an extra stream for chapters for the case where chapters // are written in the trailer mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks)); if (!mov->tracks) return AVERROR(ENOMEM); if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) { if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) { mov->encryption_scheme = MOV_ENC_CENC_AES_CTR; if (mov->encryption_key_len != AES_CTR_KEY_SIZE) { av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n", mov->encryption_key_len, AES_CTR_KEY_SIZE); return AVERROR(EINVAL); } if (mov->encryption_kid_len != CENC_KID_SIZE) { av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n", mov->encryption_kid_len, CENC_KID_SIZE); return AVERROR(EINVAL); } } else { av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n", mov->encryption_scheme_str); return AVERROR(EINVAL); } } for (i = 0; i < s->nb_streams; i++) { AVStream *st= s->streams[i]; MOVTrack *track= &mov->tracks[i]; AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0); track->st = st; track->par = st->codecpar; track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV); if (track->language < 0) track->language = 0; track->mode = mov->mode; track->tag = mov_find_codec_tag(s, track); if (!track->tag) { av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, " "codec not currently supported in container\n", avcodec_get_name(st->codecpar->codec_id), i); return AVERROR(EINVAL); } /* If hinting of this track is enabled by a later hint track, * this is updated. */ track->hint_track = -1; track->start_dts = AV_NOPTS_VALUE; track->start_cts = AV_NOPTS_VALUE; track->end_pts = AV_NOPTS_VALUE; track->dts_shift = AV_NOPTS_VALUE; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') || track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') || track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) { if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) { av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n"); return AVERROR(EINVAL); } track->height = track->tag >> 24 == 'n' ? 486 : 576; } if (mov->video_track_timescale) { track->timescale = mov->video_track_timescale; } else { track->timescale = st->time_base.den; while(track->timescale < 10000) track->timescale *= 2; } if (st->codecpar->width > 65535 || st->codecpar->height > 65535) { av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height); return AVERROR(EINVAL); } if (track->mode == MODE_MOV && track->timescale > 100000) av_log(s, AV_LOG_WARNING, "WARNING codec timebase is very high. If duration is too long,\n" "file may not be playable by quicktime. Specify a shorter timebase\n" "or choose different container.\n"); if (track->mode == MODE_MOV && track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->tag == MKTAG('r','a','w',' ')) { enum AVPixelFormat pix_fmt = track->par->format; if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1) pix_fmt = AV_PIX_FMT_MONOWHITE; track->is_unaligned_qt_rgb = pix_fmt == AV_PIX_FMT_RGB24 || pix_fmt == AV_PIX_FMT_BGR24 || pix_fmt == AV_PIX_FMT_PAL8 || pix_fmt == AV_PIX_FMT_GRAY8 || pix_fmt == AV_PIX_FMT_MONOWHITE || pix_fmt == AV_PIX_FMT_MONOBLACK; } if (track->par->codec_id == AV_CODEC_ID_VP9) { if (track->mode != MODE_MP4) { av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n"); return AVERROR(EINVAL); } } else if (track->par->codec_id == AV_CODEC_ID_AV1) { /* spec is not finished, so forbid for now */ av_log(s, AV_LOG_ERROR, "AV1 muxing is currently not supported.\n"); return AVERROR_PATCHWELCOME; } else if (track->par->codec_id == AV_CODEC_ID_VP8) { /* altref frames handling is not defined in the spec as of version v1.0, * so just forbid muxing VP8 streams altogether until a new version does */ av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n"); return AVERROR_PATCHWELCOME; } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { track->timescale = st->codecpar->sample_rate; if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) { av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i); track->audio_vbr = 1; }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS || st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || st->codecpar->codec_id == AV_CODEC_ID_ILBC){ if (!st->codecpar->block_align) { av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i); return AVERROR(EINVAL); } track->sample_size = st->codecpar->block_align; }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */ track->audio_vbr = 1; }else{ track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels; } if (st->codecpar->codec_id == AV_CODEC_ID_ILBC || st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) { track->audio_vbr = 1; } if (track->mode != MODE_MOV && track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) { if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) { av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n", i, track->par->sample_rate); return AVERROR(EINVAL); } else { av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n", i, track->par->sample_rate); } } if (track->par->codec_id == AV_CODEC_ID_FLAC || track->par->codec_id == AV_CODEC_ID_OPUS) { if (track->mode != MODE_MP4) { av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id)); return AVERROR(EINVAL); } if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { av_log(s, AV_LOG_ERROR, "%s in MP4 support is experimental, add " "'-strict %d' if you want to use it.\n", avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL); return AVERROR_EXPERIMENTAL; } } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) { track->timescale = st->time_base.den; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) { track->timescale = st->time_base.den; } else { track->timescale = MOV_TIMESCALE; } if (!track->height) track->height = st->codecpar->height; /* The ism specific timescale isn't mandatory, but is assumed by * some tools, such as mp4split. */ if (mov->mode == MODE_ISM) track->timescale = 10000000; avpriv_set_pts_info(st, 64, 1, track->timescale); if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) { ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key, track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT); if (ret) return ret; } } enable_tracks(s); return 0; } static int mov_write_header(AVFormatContext *s) { AVIOContext *pb = s->pb; MOVMuxContext *mov = s->priv_data; AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0); int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams; if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) nb_tracks++; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { hint_track = nb_tracks; for (i = 0; i < s->nb_streams; i++) if (rtp_hinting_needed(s->streams[i])) nb_tracks++; } if (mov->mode == MODE_MOV || mov->mode == MODE_MP4) tmcd_track = nb_tracks; for (i = 0; i < s->nb_streams; i++) { int j; AVStream *st= s->streams[i]; MOVTrack *track= &mov->tracks[i]; /* copy extradata if it exists */ if (st->codecpar->extradata_size) { if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) mov_create_dvd_sub_decoder_specific_info(track, st); else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) { track->vos_len = st->codecpar->extradata_size; track->vos_data = av_malloc(track->vos_len); if (!track->vos_data) { return AVERROR(ENOMEM); } memcpy(track->vos_data, st->codecpar->extradata, track->vos_len); } } if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || track->par->channel_layout != AV_CH_LAYOUT_MONO) continue; for (j = 0; j < s->nb_streams; j++) { AVStream *stj= s->streams[j]; MOVTrack *trackj= &mov->tracks[j]; if (j == i) continue; if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || trackj->par->channel_layout != AV_CH_LAYOUT_MONO || trackj->language != track->language || trackj->tag != track->tag ) continue; track->multichannel_as_mono++; } } if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { if ((ret = mov_write_identification(pb, s)) < 0) return ret; } if (mov->reserved_moov_size){ mov->reserved_header_pos = avio_tell(pb); if (mov->reserved_moov_size > 0) avio_skip(pb, mov->reserved_moov_size); } if (mov->flags & FF_MOV_FLAG_FRAGMENT) { /* If no fragmentation options have been set, set a default. */ if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME | FF_MOV_FLAG_FRAG_CUSTOM | FF_MOV_FLAG_FRAG_EVERY_FRAME)) && !mov->max_fragment_duration && !mov->max_fragment_size) mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME; } else { if (mov->flags & FF_MOV_FLAG_FASTSTART) mov->reserved_header_pos = avio_tell(pb); mov_write_mdat_tag(pb, mov); } ff_parse_creation_time_metadata(s, &mov->time, 1); if (mov->time) mov->time += 0x7C25B080; // 1970 based -> 1904 based if (mov->chapter_track) if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0) return ret; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { for (i = 0; i < s->nb_streams; i++) { if (rtp_hinting_needed(s->streams[i])) { if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0) return ret; hint_track++; } } } if (mov->nb_meta_tmcd) { /* Initialize the tmcd tracks */ for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; t = global_tcr; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { AVTimecode tc; if (!t) t = av_dict_get(st->metadata, "timecode", NULL, 0); if (!t) continue; if (mov_check_timecode_track(s, &tc, i, t->value) < 0) continue; if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0) return ret; tmcd_track++; } } } avio_flush(pb); if (mov->flags & FF_MOV_FLAG_ISML) mov_write_isml_manifest(pb, mov, s); if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { if ((ret = mov_write_moov_tag(pb, mov, s)) < 0) return ret; avio_flush(pb); mov->moov_written = 1; if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(pb); } return 0; } static int get_moov_size(AVFormatContext *s) { int ret; AVIOContext *moov_buf; MOVMuxContext *mov = s->priv_data; if ((ret = ffio_open_null_buf(&moov_buf)) < 0) return ret; if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0) return ret; return ffio_close_null_buf(moov_buf); } static int get_sidx_size(AVFormatContext *s) { int ret; AVIOContext *buf; MOVMuxContext *mov = s->priv_data; if ((ret = ffio_open_null_buf(&buf)) < 0) return ret; mov_write_sidx_tags(buf, mov, -1, 0); return ffio_close_null_buf(buf); } /* * This function gets the moov size if moved to the top of the file: the chunk * offset table can switch between stco (32-bit entries) to co64 (64-bit * entries) when the moov is moved to the beginning, so the size of the moov * would change. It also updates the chunk offset tables. */ static int compute_moov_size(AVFormatContext *s) { int i, moov_size, moov_size2; MOVMuxContext *mov = s->priv_data; moov_size = get_moov_size(s); if (moov_size < 0) return moov_size; for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += moov_size; moov_size2 = get_moov_size(s); if (moov_size2 < 0) return moov_size2; /* if the size changed, we just switched from stco to co64 and need to * update the offsets */ if (moov_size2 != moov_size) for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += moov_size2 - moov_size; return moov_size2; } static int compute_sidx_size(AVFormatContext *s) { int i, sidx_size; MOVMuxContext *mov = s->priv_data; sidx_size = get_sidx_size(s); if (sidx_size < 0) return sidx_size; for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += sidx_size; return sidx_size; } static int shift_data(AVFormatContext *s) { int ret = 0, moov_size; MOVMuxContext *mov = s->priv_data; int64_t pos, pos_end = avio_tell(s->pb); uint8_t *buf, *read_buf[2]; int read_buf_id = 0; int read_size[2]; AVIOContext *read_pb; if (mov->flags & FF_MOV_FLAG_FRAGMENT) moov_size = compute_sidx_size(s); else moov_size = compute_moov_size(s); if (moov_size < 0) return moov_size; buf = av_malloc(moov_size * 2); if (!buf) return AVERROR(ENOMEM); read_buf[0] = buf; read_buf[1] = buf + moov_size; /* Shift the data: the AVIO context of the output can only be used for * writing, so we re-open the same output, but for reading. It also avoids * a read/seek/write/seek back and forth. */ avio_flush(s->pb); ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL); if (ret < 0) { av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for " "the second pass (faststart)\n", s->url); goto end; } /* mark the end of the shift to up to the last data we wrote, and get ready * for writing */ pos_end = avio_tell(s->pb); avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET); /* start reading at where the new moov will be placed */ avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET); pos = avio_tell(read_pb); #define READ_BLOCK do { \ read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \ read_buf_id ^= 1; \ } while (0) /* shift data by chunk of at most moov_size */ READ_BLOCK; do { int n; READ_BLOCK; n = read_size[read_buf_id]; if (n <= 0) break; avio_write(s->pb, read_buf[read_buf_id], n); pos += n; } while (pos < pos_end); ff_format_io_close(s, &read_pb); end: av_free(buf); return ret; } static int mov_write_trailer(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; AVIOContext *pb = s->pb; int res = 0; int i; int64_t moov_pos; if (mov->need_rewrite_extradata) { for (i = 0; i < s->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; AVCodecParameters *par = track->par; track->vos_len = par->extradata_size; track->vos_data = av_malloc(track->vos_len); if (!track->vos_data) return AVERROR(ENOMEM); memcpy(track->vos_data, par->extradata, track->vos_len); } mov->need_rewrite_extradata = 0; } /* * Before actually writing the trailer, make sure that there are no * dangling subtitles, that need a terminating sample. */ for (i = 0; i < mov->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT && !trk->last_sample_is_subtitle_end) { mov_write_subtitle_end_packet(s, i, trk->track_duration); trk->last_sample_is_subtitle_end = 1; } } // If there were no chapters when the header was written, but there // are chapters now, write them in the trailer. This only works // when we are not doing fragments. if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) { if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) { mov->chapter_track = mov->nb_streams++; if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0) return res; } } if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) { moov_pos = avio_tell(pb); /* Write size of mdat tag */ if (mov->mdat_size + 8 <= UINT32_MAX) { avio_seek(pb, mov->mdat_pos, SEEK_SET); avio_wb32(pb, mov->mdat_size + 8); } else { /* overwrite 'wide' placeholder atom */ avio_seek(pb, mov->mdat_pos - 8, SEEK_SET); /* special value: real atom size will be 64 bit value after * tag field */ avio_wb32(pb, 1); ffio_wfourcc(pb, "mdat"); avio_wb64(pb, mov->mdat_size + 16); } avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET); if (mov->flags & FF_MOV_FLAG_FASTSTART) { av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n"); res = shift_data(s); if (res < 0) return res; avio_seek(pb, mov->reserved_header_pos, SEEK_SET); if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; } else if (mov->reserved_moov_size > 0) { int64_t size; if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos); if (size < 8){ av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size); return AVERROR(EINVAL); } avio_wb32(pb, size); ffio_wfourcc(pb, "free"); ffio_fill(pb, 0, size - 8); avio_seek(pb, moov_pos, SEEK_SET); } else { if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; } res = 0; } else { mov_auto_flush_fragment(s, 1); for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset = 0; if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) { int64_t end; av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n"); res = shift_data(s); if (res < 0) return res; end = avio_tell(pb); avio_seek(pb, mov->reserved_header_pos, SEEK_SET); mov_write_sidx_tags(pb, mov, -1, 0); avio_seek(pb, end, SEEK_SET); avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER); mov_write_mfra_tag(pb, mov); } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) { avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER); mov_write_mfra_tag(pb, mov); } } return res; } static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt) { int ret = 1; AVStream *st = s->streams[pkt->stream_index]; if (st->codecpar->codec_id == AV_CODEC_ID_AAC) { if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL); } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) { ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL); } return ret; } static const AVCodecTag codec_3gp_tags[] = { { AV_CODEC_ID_H263, MKTAG('s','2','6','3') }, { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') }, { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') }, { AV_CODEC_ID_NONE, 0 }, }; const AVCodecTag codec_mp4_tags[] = { { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') }, { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') }, { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') }, { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') }, { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') }, { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') }, { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') }, { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') }, { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') }, { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') }, { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') }, { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') }, { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') }, { AV_CODEC_ID_NONE , 0 }, }; const AVCodecTag codec_ism_tags[] = { { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') }, { AV_CODEC_ID_NONE , 0 }, }; static const AVCodecTag codec_ipod_tags[] = { { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') }, { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') }, { AV_CODEC_ID_NONE, 0 }, }; static const AVCodecTag codec_f4v_tags[] = { { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') }, { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') }, { AV_CODEC_ID_NONE, 0 }, }; #if CONFIG_MOV_MUXER MOV_CLASS(mov) AVOutputFormat ff_mov_muxer = { .name = "mov", .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"), .extensions = "mov", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &mov_muxer_class, }; #endif #if CONFIG_TGP_MUXER MOV_CLASS(tgp) AVOutputFormat ff_tgp_muxer = { .name = "3gp", .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"), .extensions = "3gp", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AMR_NB, .video_codec = AV_CODEC_ID_H263, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &tgp_muxer_class, }; #endif #if CONFIG_MP4_MUXER MOV_CLASS(mp4) AVOutputFormat ff_mp4_muxer = { .name = "mp4", .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"), .mime_type = "video/mp4", .extensions = "mp4", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &mp4_muxer_class, }; #endif #if CONFIG_PSP_MUXER MOV_CLASS(psp) AVOutputFormat ff_psp_muxer = { .name = "psp", .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"), .extensions = "mp4,psp", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &psp_muxer_class, }; #endif #if CONFIG_TG2_MUXER MOV_CLASS(tg2) AVOutputFormat ff_tg2_muxer = { .name = "3g2", .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"), .extensions = "3g2", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AMR_NB, .video_codec = AV_CODEC_ID_H263, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &tg2_muxer_class, }; #endif #if CONFIG_IPOD_MUXER MOV_CLASS(ipod) AVOutputFormat ff_ipod_muxer = { .name = "ipod", .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"), .mime_type = "video/mp4", .extensions = "m4v,m4a,m4b", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &ipod_muxer_class, }; #endif #if CONFIG_ISMV_MUXER MOV_CLASS(ismv) AVOutputFormat ff_ismv_muxer = { .name = "ismv", .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"), .mime_type = "video/mp4", .extensions = "ismv,isma", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, codec_ism_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &ismv_muxer_class, }; #endif #if CONFIG_F4V_MUXER MOV_CLASS(f4v) AVOutputFormat ff_f4v_muxer = { .name = "f4v", .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"), .mime_type = "application/f4v", .extensions = "f4v", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH, .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &f4v_muxer_class, }; #endif
./CrossVul/dataset_final_sorted/CWE-129/c/good_217_0
crossvul-cpp_data_good_3336_0
/* * Server-side XDR for NFSv4 * * Copyright (c) 2002 The Regents of the University of Michigan. * All rights reserved. * * Kendrick Smith <kmsmith@umich.edu> * Andy Adamson <andros@umich.edu> * * 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 ``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 <linux/fs_struct.h> #include <linux/file.h> #include <linux/slab.h> #include <linux/namei.h> #include <linux/statfs.h> #include <linux/utsname.h> #include <linux/pagemap.h> #include <linux/sunrpc/svcauth_gss.h> #include "idmap.h" #include "acl.h" #include "xdr4.h" #include "vfs.h" #include "state.h" #include "cache.h" #include "netns.h" #include "pnfs.h" #ifdef CONFIG_NFSD_V4_SECURITY_LABEL #include <linux/security.h> #endif #define NFSDDBG_FACILITY NFSDDBG_XDR const u32 nfsd_suppattrs[3][3] = { {NFSD4_SUPPORTED_ATTRS_WORD0, NFSD4_SUPPORTED_ATTRS_WORD1, NFSD4_SUPPORTED_ATTRS_WORD2}, {NFSD4_1_SUPPORTED_ATTRS_WORD0, NFSD4_1_SUPPORTED_ATTRS_WORD1, NFSD4_1_SUPPORTED_ATTRS_WORD2}, {NFSD4_1_SUPPORTED_ATTRS_WORD0, NFSD4_1_SUPPORTED_ATTRS_WORD1, NFSD4_2_SUPPORTED_ATTRS_WORD2}, }; /* * As per referral draft, the fsid for a referral MUST be different from the fsid of the containing * directory in order to indicate to the client that a filesystem boundary is present * We use a fixed fsid for a referral */ #define NFS4_REFERRAL_FSID_MAJOR 0x8000000ULL #define NFS4_REFERRAL_FSID_MINOR 0x8000000ULL static __be32 check_filename(char *str, int len) { int i; if (len == 0) return nfserr_inval; if (isdotent(str, len)) return nfserr_badname; for (i = 0; i < len; i++) if (str[i] == '/') return nfserr_badname; return 0; } #define DECODE_HEAD \ __be32 *p; \ __be32 status #define DECODE_TAIL \ status = 0; \ out: \ return status; \ xdr_error: \ dprintk("NFSD: xdr error (%s:%d)\n", \ __FILE__, __LINE__); \ status = nfserr_bad_xdr; \ goto out #define READMEM(x,nbytes) do { \ x = (char *)p; \ p += XDR_QUADLEN(nbytes); \ } while (0) #define SAVEMEM(x,nbytes) do { \ if (!(x = (p==argp->tmp || p == argp->tmpp) ? \ savemem(argp, p, nbytes) : \ (char *)p)) { \ dprintk("NFSD: xdr error (%s:%d)\n", \ __FILE__, __LINE__); \ goto xdr_error; \ } \ p += XDR_QUADLEN(nbytes); \ } while (0) #define COPYMEM(x,nbytes) do { \ memcpy((x), p, nbytes); \ p += XDR_QUADLEN(nbytes); \ } while (0) /* READ_BUF, read_buf(): nbytes must be <= PAGE_SIZE */ #define READ_BUF(nbytes) do { \ if (nbytes <= (u32)((char *)argp->end - (char *)argp->p)) { \ p = argp->p; \ argp->p += XDR_QUADLEN(nbytes); \ } else if (!(p = read_buf(argp, nbytes))) { \ dprintk("NFSD: xdr error (%s:%d)\n", \ __FILE__, __LINE__); \ goto xdr_error; \ } \ } while (0) static void next_decode_page(struct nfsd4_compoundargs *argp) { argp->p = page_address(argp->pagelist[0]); argp->pagelist++; if (argp->pagelen < PAGE_SIZE) { argp->end = argp->p + (argp->pagelen>>2); argp->pagelen = 0; } else { argp->end = argp->p + (PAGE_SIZE>>2); argp->pagelen -= PAGE_SIZE; } } static __be32 *read_buf(struct nfsd4_compoundargs *argp, u32 nbytes) { /* We want more bytes than seem to be available. * Maybe we need a new page, maybe we have just run out */ unsigned int avail = (char *)argp->end - (char *)argp->p; __be32 *p; if (avail + argp->pagelen < nbytes) return NULL; if (avail + PAGE_SIZE < nbytes) /* need more than a page !! */ return NULL; /* ok, we can do it with the current plus the next page */ if (nbytes <= sizeof(argp->tmp)) p = argp->tmp; else { kfree(argp->tmpp); p = argp->tmpp = kmalloc(nbytes, GFP_KERNEL); if (!p) return NULL; } /* * The following memcpy is safe because read_buf is always * called with nbytes > avail, and the two cases above both * guarantee p points to at least nbytes bytes. */ memcpy(p, argp->p, avail); next_decode_page(argp); memcpy(((char*)p)+avail, argp->p, (nbytes - avail)); argp->p += XDR_QUADLEN(nbytes - avail); return p; } static int zero_clientid(clientid_t *clid) { return (clid->cl_boot == 0) && (clid->cl_id == 0); } /** * svcxdr_tmpalloc - allocate memory to be freed after compound processing * @argp: NFSv4 compound argument structure * @p: pointer to be freed (with kfree()) * * Marks @p to be freed when processing the compound operation * described in @argp finishes. */ static void * svcxdr_tmpalloc(struct nfsd4_compoundargs *argp, u32 len) { struct svcxdr_tmpbuf *tb; tb = kmalloc(sizeof(*tb) + len, GFP_KERNEL); if (!tb) return NULL; tb->next = argp->to_free; argp->to_free = tb; return tb->buf; } /* * For xdr strings that need to be passed to other kernel api's * as null-terminated strings. * * Note null-terminating in place usually isn't safe since the * buffer might end on a page boundary. */ static char * svcxdr_dupstr(struct nfsd4_compoundargs *argp, void *buf, u32 len) { char *p = svcxdr_tmpalloc(argp, len + 1); if (!p) return NULL; memcpy(p, buf, len); p[len] = '\0'; return p; } /** * savemem - duplicate a chunk of memory for later processing * @argp: NFSv4 compound argument structure to be freed with * @p: pointer to be duplicated * @nbytes: length to be duplicated * * Returns a pointer to a copy of @nbytes bytes of memory at @p * that are preserved until processing of the NFSv4 compound * operation described by @argp finishes. */ static char *savemem(struct nfsd4_compoundargs *argp, __be32 *p, int nbytes) { void *ret; ret = svcxdr_tmpalloc(argp, nbytes); if (!ret) return NULL; memcpy(ret, p, nbytes); return ret; } /* * We require the high 32 bits of 'seconds' to be 0, and * we ignore all 32 bits of 'nseconds'. */ static __be32 nfsd4_decode_time(struct nfsd4_compoundargs *argp, struct timespec *tv) { DECODE_HEAD; u64 sec; READ_BUF(12); p = xdr_decode_hyper(p, &sec); tv->tv_sec = sec; tv->tv_nsec = be32_to_cpup(p++); if (tv->tv_nsec >= (u32)1000000000) return nfserr_inval; DECODE_TAIL; } static __be32 nfsd4_decode_bitmap(struct nfsd4_compoundargs *argp, u32 *bmval) { u32 bmlen; DECODE_HEAD; bmval[0] = 0; bmval[1] = 0; bmval[2] = 0; READ_BUF(4); bmlen = be32_to_cpup(p++); if (bmlen > 1000) goto xdr_error; READ_BUF(bmlen << 2); if (bmlen > 0) bmval[0] = be32_to_cpup(p++); if (bmlen > 1) bmval[1] = be32_to_cpup(p++); if (bmlen > 2) bmval[2] = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_fattr(struct nfsd4_compoundargs *argp, u32 *bmval, struct iattr *iattr, struct nfs4_acl **acl, struct xdr_netobj *label, int *umask) { int expected_len, len = 0; u32 dummy32; char *buf; DECODE_HEAD; iattr->ia_valid = 0; if ((status = nfsd4_decode_bitmap(argp, bmval))) return status; if (bmval[0] & ~NFSD_WRITEABLE_ATTRS_WORD0 || bmval[1] & ~NFSD_WRITEABLE_ATTRS_WORD1 || bmval[2] & ~NFSD_WRITEABLE_ATTRS_WORD2) { if (nfsd_attrs_supported(argp->minorversion, bmval)) return nfserr_inval; return nfserr_attrnotsupp; } READ_BUF(4); expected_len = be32_to_cpup(p++); if (bmval[0] & FATTR4_WORD0_SIZE) { READ_BUF(8); len += 8; p = xdr_decode_hyper(p, &iattr->ia_size); iattr->ia_valid |= ATTR_SIZE; } if (bmval[0] & FATTR4_WORD0_ACL) { u32 nace; struct nfs4_ace *ace; READ_BUF(4); len += 4; nace = be32_to_cpup(p++); if (nace > NFS4_ACL_MAX) return nfserr_fbig; *acl = svcxdr_tmpalloc(argp, nfs4_acl_bytes(nace)); if (*acl == NULL) return nfserr_jukebox; (*acl)->naces = nace; for (ace = (*acl)->aces; ace < (*acl)->aces + nace; ace++) { READ_BUF(16); len += 16; ace->type = be32_to_cpup(p++); ace->flag = be32_to_cpup(p++); ace->access_mask = be32_to_cpup(p++); dummy32 = be32_to_cpup(p++); READ_BUF(dummy32); len += XDR_QUADLEN(dummy32) << 2; READMEM(buf, dummy32); ace->whotype = nfs4_acl_get_whotype(buf, dummy32); status = nfs_ok; if (ace->whotype != NFS4_ACL_WHO_NAMED) ; else if (ace->flag & NFS4_ACE_IDENTIFIER_GROUP) status = nfsd_map_name_to_gid(argp->rqstp, buf, dummy32, &ace->who_gid); else status = nfsd_map_name_to_uid(argp->rqstp, buf, dummy32, &ace->who_uid); if (status) return status; } } else *acl = NULL; if (bmval[1] & FATTR4_WORD1_MODE) { READ_BUF(4); len += 4; iattr->ia_mode = be32_to_cpup(p++); iattr->ia_mode &= (S_IFMT | S_IALLUGO); iattr->ia_valid |= ATTR_MODE; } if (bmval[1] & FATTR4_WORD1_OWNER) { READ_BUF(4); len += 4; dummy32 = be32_to_cpup(p++); READ_BUF(dummy32); len += (XDR_QUADLEN(dummy32) << 2); READMEM(buf, dummy32); if ((status = nfsd_map_name_to_uid(argp->rqstp, buf, dummy32, &iattr->ia_uid))) return status; iattr->ia_valid |= ATTR_UID; } if (bmval[1] & FATTR4_WORD1_OWNER_GROUP) { READ_BUF(4); len += 4; dummy32 = be32_to_cpup(p++); READ_BUF(dummy32); len += (XDR_QUADLEN(dummy32) << 2); READMEM(buf, dummy32); if ((status = nfsd_map_name_to_gid(argp->rqstp, buf, dummy32, &iattr->ia_gid))) return status; iattr->ia_valid |= ATTR_GID; } if (bmval[1] & FATTR4_WORD1_TIME_ACCESS_SET) { READ_BUF(4); len += 4; dummy32 = be32_to_cpup(p++); switch (dummy32) { case NFS4_SET_TO_CLIENT_TIME: len += 12; status = nfsd4_decode_time(argp, &iattr->ia_atime); if (status) return status; iattr->ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET); break; case NFS4_SET_TO_SERVER_TIME: iattr->ia_valid |= ATTR_ATIME; break; default: goto xdr_error; } } if (bmval[1] & FATTR4_WORD1_TIME_MODIFY_SET) { READ_BUF(4); len += 4; dummy32 = be32_to_cpup(p++); switch (dummy32) { case NFS4_SET_TO_CLIENT_TIME: len += 12; status = nfsd4_decode_time(argp, &iattr->ia_mtime); if (status) return status; iattr->ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET); break; case NFS4_SET_TO_SERVER_TIME: iattr->ia_valid |= ATTR_MTIME; break; default: goto xdr_error; } } label->len = 0; #ifdef CONFIG_NFSD_V4_SECURITY_LABEL if (bmval[2] & FATTR4_WORD2_SECURITY_LABEL) { READ_BUF(4); len += 4; dummy32 = be32_to_cpup(p++); /* lfs: we don't use it */ READ_BUF(4); len += 4; dummy32 = be32_to_cpup(p++); /* pi: we don't use it either */ READ_BUF(4); len += 4; dummy32 = be32_to_cpup(p++); READ_BUF(dummy32); if (dummy32 > NFS4_MAXLABELLEN) return nfserr_badlabel; len += (XDR_QUADLEN(dummy32) << 2); READMEM(buf, dummy32); label->len = dummy32; label->data = svcxdr_dupstr(argp, buf, dummy32); if (!label->data) return nfserr_jukebox; } #endif if (bmval[2] & FATTR4_WORD2_MODE_UMASK) { if (!umask) goto xdr_error; READ_BUF(8); len += 8; dummy32 = be32_to_cpup(p++); iattr->ia_mode = dummy32 & (S_IFMT | S_IALLUGO); dummy32 = be32_to_cpup(p++); *umask = dummy32 & S_IRWXUGO; iattr->ia_valid |= ATTR_MODE; } if (len != expected_len) goto xdr_error; DECODE_TAIL; } static __be32 nfsd4_decode_stateid(struct nfsd4_compoundargs *argp, stateid_t *sid) { DECODE_HEAD; READ_BUF(sizeof(stateid_t)); sid->si_generation = be32_to_cpup(p++); COPYMEM(&sid->si_opaque, sizeof(stateid_opaque_t)); DECODE_TAIL; } static __be32 nfsd4_decode_access(struct nfsd4_compoundargs *argp, struct nfsd4_access *access) { DECODE_HEAD; READ_BUF(4); access->ac_req_access = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_cb_sec(struct nfsd4_compoundargs *argp, struct nfsd4_cb_sec *cbs) { DECODE_HEAD; u32 dummy, uid, gid; char *machine_name; int i; int nr_secflavs; /* callback_sec_params4 */ READ_BUF(4); nr_secflavs = be32_to_cpup(p++); if (nr_secflavs) cbs->flavor = (u32)(-1); else /* Is this legal? Be generous, take it to mean AUTH_NONE: */ cbs->flavor = 0; for (i = 0; i < nr_secflavs; ++i) { READ_BUF(4); dummy = be32_to_cpup(p++); switch (dummy) { case RPC_AUTH_NULL: /* Nothing to read */ if (cbs->flavor == (u32)(-1)) cbs->flavor = RPC_AUTH_NULL; break; case RPC_AUTH_UNIX: READ_BUF(8); /* stamp */ dummy = be32_to_cpup(p++); /* machine name */ dummy = be32_to_cpup(p++); READ_BUF(dummy); SAVEMEM(machine_name, dummy); /* uid, gid */ READ_BUF(8); uid = be32_to_cpup(p++); gid = be32_to_cpup(p++); /* more gids */ READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy * 4); if (cbs->flavor == (u32)(-1)) { kuid_t kuid = make_kuid(&init_user_ns, uid); kgid_t kgid = make_kgid(&init_user_ns, gid); if (uid_valid(kuid) && gid_valid(kgid)) { cbs->uid = kuid; cbs->gid = kgid; cbs->flavor = RPC_AUTH_UNIX; } else { dprintk("RPC_AUTH_UNIX with invalid" "uid or gid ignoring!\n"); } } break; case RPC_AUTH_GSS: dprintk("RPC_AUTH_GSS callback secflavor " "not supported!\n"); READ_BUF(8); /* gcbp_service */ dummy = be32_to_cpup(p++); /* gcbp_handle_from_server */ dummy = be32_to_cpup(p++); READ_BUF(dummy); p += XDR_QUADLEN(dummy); /* gcbp_handle_from_client */ READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy); break; default: dprintk("Illegal callback secflavor\n"); return nfserr_inval; } } DECODE_TAIL; } static __be32 nfsd4_decode_backchannel_ctl(struct nfsd4_compoundargs *argp, struct nfsd4_backchannel_ctl *bc) { DECODE_HEAD; READ_BUF(4); bc->bc_cb_program = be32_to_cpup(p++); nfsd4_decode_cb_sec(argp, &bc->bc_cb_sec); DECODE_TAIL; } static __be32 nfsd4_decode_bind_conn_to_session(struct nfsd4_compoundargs *argp, struct nfsd4_bind_conn_to_session *bcts) { DECODE_HEAD; READ_BUF(NFS4_MAX_SESSIONID_LEN + 8); COPYMEM(bcts->sessionid.data, NFS4_MAX_SESSIONID_LEN); bcts->dir = be32_to_cpup(p++); /* XXX: skipping ctsa_use_conn_in_rdma_mode. Perhaps Tom Tucker * could help us figure out we should be using it. */ DECODE_TAIL; } static __be32 nfsd4_decode_close(struct nfsd4_compoundargs *argp, struct nfsd4_close *close) { DECODE_HEAD; READ_BUF(4); close->cl_seqid = be32_to_cpup(p++); return nfsd4_decode_stateid(argp, &close->cl_stateid); DECODE_TAIL; } static __be32 nfsd4_decode_commit(struct nfsd4_compoundargs *argp, struct nfsd4_commit *commit) { DECODE_HEAD; READ_BUF(12); p = xdr_decode_hyper(p, &commit->co_offset); commit->co_count = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_create(struct nfsd4_compoundargs *argp, struct nfsd4_create *create) { DECODE_HEAD; READ_BUF(4); create->cr_type = be32_to_cpup(p++); switch (create->cr_type) { case NF4LNK: READ_BUF(4); create->cr_datalen = be32_to_cpup(p++); READ_BUF(create->cr_datalen); create->cr_data = svcxdr_dupstr(argp, p, create->cr_datalen); if (!create->cr_data) return nfserr_jukebox; break; case NF4BLK: case NF4CHR: READ_BUF(8); create->cr_specdata1 = be32_to_cpup(p++); create->cr_specdata2 = be32_to_cpup(p++); break; case NF4SOCK: case NF4FIFO: case NF4DIR: default: break; } READ_BUF(4); create->cr_namelen = be32_to_cpup(p++); READ_BUF(create->cr_namelen); SAVEMEM(create->cr_name, create->cr_namelen); if ((status = check_filename(create->cr_name, create->cr_namelen))) return status; status = nfsd4_decode_fattr(argp, create->cr_bmval, &create->cr_iattr, &create->cr_acl, &create->cr_label, &current->fs->umask); if (status) goto out; DECODE_TAIL; } static inline __be32 nfsd4_decode_delegreturn(struct nfsd4_compoundargs *argp, struct nfsd4_delegreturn *dr) { return nfsd4_decode_stateid(argp, &dr->dr_stateid); } static inline __be32 nfsd4_decode_getattr(struct nfsd4_compoundargs *argp, struct nfsd4_getattr *getattr) { return nfsd4_decode_bitmap(argp, getattr->ga_bmval); } static __be32 nfsd4_decode_link(struct nfsd4_compoundargs *argp, struct nfsd4_link *link) { DECODE_HEAD; READ_BUF(4); link->li_namelen = be32_to_cpup(p++); READ_BUF(link->li_namelen); SAVEMEM(link->li_name, link->li_namelen); if ((status = check_filename(link->li_name, link->li_namelen))) return status; DECODE_TAIL; } static __be32 nfsd4_decode_lock(struct nfsd4_compoundargs *argp, struct nfsd4_lock *lock) { DECODE_HEAD; /* * type, reclaim(boolean), offset, length, new_lock_owner(boolean) */ READ_BUF(28); lock->lk_type = be32_to_cpup(p++); if ((lock->lk_type < NFS4_READ_LT) || (lock->lk_type > NFS4_WRITEW_LT)) goto xdr_error; lock->lk_reclaim = be32_to_cpup(p++); p = xdr_decode_hyper(p, &lock->lk_offset); p = xdr_decode_hyper(p, &lock->lk_length); lock->lk_is_new = be32_to_cpup(p++); if (lock->lk_is_new) { READ_BUF(4); lock->lk_new_open_seqid = be32_to_cpup(p++); status = nfsd4_decode_stateid(argp, &lock->lk_new_open_stateid); if (status) return status; READ_BUF(8 + sizeof(clientid_t)); lock->lk_new_lock_seqid = be32_to_cpup(p++); COPYMEM(&lock->lk_new_clientid, sizeof(clientid_t)); lock->lk_new_owner.len = be32_to_cpup(p++); READ_BUF(lock->lk_new_owner.len); READMEM(lock->lk_new_owner.data, lock->lk_new_owner.len); } else { status = nfsd4_decode_stateid(argp, &lock->lk_old_lock_stateid); if (status) return status; READ_BUF(4); lock->lk_old_lock_seqid = be32_to_cpup(p++); } DECODE_TAIL; } static __be32 nfsd4_decode_lockt(struct nfsd4_compoundargs *argp, struct nfsd4_lockt *lockt) { DECODE_HEAD; READ_BUF(32); lockt->lt_type = be32_to_cpup(p++); if((lockt->lt_type < NFS4_READ_LT) || (lockt->lt_type > NFS4_WRITEW_LT)) goto xdr_error; p = xdr_decode_hyper(p, &lockt->lt_offset); p = xdr_decode_hyper(p, &lockt->lt_length); COPYMEM(&lockt->lt_clientid, 8); lockt->lt_owner.len = be32_to_cpup(p++); READ_BUF(lockt->lt_owner.len); READMEM(lockt->lt_owner.data, lockt->lt_owner.len); DECODE_TAIL; } static __be32 nfsd4_decode_locku(struct nfsd4_compoundargs *argp, struct nfsd4_locku *locku) { DECODE_HEAD; READ_BUF(8); locku->lu_type = be32_to_cpup(p++); if ((locku->lu_type < NFS4_READ_LT) || (locku->lu_type > NFS4_WRITEW_LT)) goto xdr_error; locku->lu_seqid = be32_to_cpup(p++); status = nfsd4_decode_stateid(argp, &locku->lu_stateid); if (status) return status; READ_BUF(16); p = xdr_decode_hyper(p, &locku->lu_offset); p = xdr_decode_hyper(p, &locku->lu_length); DECODE_TAIL; } static __be32 nfsd4_decode_lookup(struct nfsd4_compoundargs *argp, struct nfsd4_lookup *lookup) { DECODE_HEAD; READ_BUF(4); lookup->lo_len = be32_to_cpup(p++); READ_BUF(lookup->lo_len); SAVEMEM(lookup->lo_name, lookup->lo_len); if ((status = check_filename(lookup->lo_name, lookup->lo_len))) return status; DECODE_TAIL; } static __be32 nfsd4_decode_share_access(struct nfsd4_compoundargs *argp, u32 *share_access, u32 *deleg_want, u32 *deleg_when) { __be32 *p; u32 w; READ_BUF(4); w = be32_to_cpup(p++); *share_access = w & NFS4_SHARE_ACCESS_MASK; *deleg_want = w & NFS4_SHARE_WANT_MASK; if (deleg_when) *deleg_when = w & NFS4_SHARE_WHEN_MASK; switch (w & NFS4_SHARE_ACCESS_MASK) { case NFS4_SHARE_ACCESS_READ: case NFS4_SHARE_ACCESS_WRITE: case NFS4_SHARE_ACCESS_BOTH: break; default: return nfserr_bad_xdr; } w &= ~NFS4_SHARE_ACCESS_MASK; if (!w) return nfs_ok; if (!argp->minorversion) return nfserr_bad_xdr; switch (w & NFS4_SHARE_WANT_MASK) { case NFS4_SHARE_WANT_NO_PREFERENCE: case NFS4_SHARE_WANT_READ_DELEG: case NFS4_SHARE_WANT_WRITE_DELEG: case NFS4_SHARE_WANT_ANY_DELEG: case NFS4_SHARE_WANT_NO_DELEG: case NFS4_SHARE_WANT_CANCEL: break; default: return nfserr_bad_xdr; } w &= ~NFS4_SHARE_WANT_MASK; if (!w) return nfs_ok; if (!deleg_when) /* open_downgrade */ return nfserr_inval; switch (w) { case NFS4_SHARE_SIGNAL_DELEG_WHEN_RESRC_AVAIL: case NFS4_SHARE_PUSH_DELEG_WHEN_UNCONTENDED: case (NFS4_SHARE_SIGNAL_DELEG_WHEN_RESRC_AVAIL | NFS4_SHARE_PUSH_DELEG_WHEN_UNCONTENDED): return nfs_ok; } xdr_error: return nfserr_bad_xdr; } static __be32 nfsd4_decode_share_deny(struct nfsd4_compoundargs *argp, u32 *x) { __be32 *p; READ_BUF(4); *x = be32_to_cpup(p++); /* Note: unlinke access bits, deny bits may be zero. */ if (*x & ~NFS4_SHARE_DENY_BOTH) return nfserr_bad_xdr; return nfs_ok; xdr_error: return nfserr_bad_xdr; } static __be32 nfsd4_decode_opaque(struct nfsd4_compoundargs *argp, struct xdr_netobj *o) { __be32 *p; READ_BUF(4); o->len = be32_to_cpup(p++); if (o->len == 0 || o->len > NFS4_OPAQUE_LIMIT) return nfserr_bad_xdr; READ_BUF(o->len); SAVEMEM(o->data, o->len); return nfs_ok; xdr_error: return nfserr_bad_xdr; } static __be32 nfsd4_decode_open(struct nfsd4_compoundargs *argp, struct nfsd4_open *open) { DECODE_HEAD; u32 dummy; memset(open->op_bmval, 0, sizeof(open->op_bmval)); open->op_iattr.ia_valid = 0; open->op_openowner = NULL; open->op_xdr_error = 0; /* seqid, share_access, share_deny, clientid, ownerlen */ READ_BUF(4); open->op_seqid = be32_to_cpup(p++); /* decode, yet ignore deleg_when until supported */ status = nfsd4_decode_share_access(argp, &open->op_share_access, &open->op_deleg_want, &dummy); if (status) goto xdr_error; status = nfsd4_decode_share_deny(argp, &open->op_share_deny); if (status) goto xdr_error; READ_BUF(sizeof(clientid_t)); COPYMEM(&open->op_clientid, sizeof(clientid_t)); status = nfsd4_decode_opaque(argp, &open->op_owner); if (status) goto xdr_error; READ_BUF(4); open->op_create = be32_to_cpup(p++); switch (open->op_create) { case NFS4_OPEN_NOCREATE: break; case NFS4_OPEN_CREATE: current->fs->umask = 0; READ_BUF(4); open->op_createmode = be32_to_cpup(p++); switch (open->op_createmode) { case NFS4_CREATE_UNCHECKED: case NFS4_CREATE_GUARDED: status = nfsd4_decode_fattr(argp, open->op_bmval, &open->op_iattr, &open->op_acl, &open->op_label, &current->fs->umask); if (status) goto out; break; case NFS4_CREATE_EXCLUSIVE: READ_BUF(NFS4_VERIFIER_SIZE); COPYMEM(open->op_verf.data, NFS4_VERIFIER_SIZE); break; case NFS4_CREATE_EXCLUSIVE4_1: if (argp->minorversion < 1) goto xdr_error; READ_BUF(NFS4_VERIFIER_SIZE); COPYMEM(open->op_verf.data, NFS4_VERIFIER_SIZE); status = nfsd4_decode_fattr(argp, open->op_bmval, &open->op_iattr, &open->op_acl, &open->op_label, &current->fs->umask); if (status) goto out; break; default: goto xdr_error; } break; default: goto xdr_error; } /* open_claim */ READ_BUF(4); open->op_claim_type = be32_to_cpup(p++); switch (open->op_claim_type) { case NFS4_OPEN_CLAIM_NULL: case NFS4_OPEN_CLAIM_DELEGATE_PREV: READ_BUF(4); open->op_fname.len = be32_to_cpup(p++); READ_BUF(open->op_fname.len); SAVEMEM(open->op_fname.data, open->op_fname.len); if ((status = check_filename(open->op_fname.data, open->op_fname.len))) return status; break; case NFS4_OPEN_CLAIM_PREVIOUS: READ_BUF(4); open->op_delegate_type = be32_to_cpup(p++); break; case NFS4_OPEN_CLAIM_DELEGATE_CUR: status = nfsd4_decode_stateid(argp, &open->op_delegate_stateid); if (status) return status; READ_BUF(4); open->op_fname.len = be32_to_cpup(p++); READ_BUF(open->op_fname.len); SAVEMEM(open->op_fname.data, open->op_fname.len); if ((status = check_filename(open->op_fname.data, open->op_fname.len))) return status; break; case NFS4_OPEN_CLAIM_FH: case NFS4_OPEN_CLAIM_DELEG_PREV_FH: if (argp->minorversion < 1) goto xdr_error; /* void */ break; case NFS4_OPEN_CLAIM_DELEG_CUR_FH: if (argp->minorversion < 1) goto xdr_error; status = nfsd4_decode_stateid(argp, &open->op_delegate_stateid); if (status) return status; break; default: goto xdr_error; } DECODE_TAIL; } static __be32 nfsd4_decode_open_confirm(struct nfsd4_compoundargs *argp, struct nfsd4_open_confirm *open_conf) { DECODE_HEAD; if (argp->minorversion >= 1) return nfserr_notsupp; status = nfsd4_decode_stateid(argp, &open_conf->oc_req_stateid); if (status) return status; READ_BUF(4); open_conf->oc_seqid = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_open_downgrade(struct nfsd4_compoundargs *argp, struct nfsd4_open_downgrade *open_down) { DECODE_HEAD; status = nfsd4_decode_stateid(argp, &open_down->od_stateid); if (status) return status; READ_BUF(4); open_down->od_seqid = be32_to_cpup(p++); status = nfsd4_decode_share_access(argp, &open_down->od_share_access, &open_down->od_deleg_want, NULL); if (status) return status; status = nfsd4_decode_share_deny(argp, &open_down->od_share_deny); if (status) return status; DECODE_TAIL; } static __be32 nfsd4_decode_putfh(struct nfsd4_compoundargs *argp, struct nfsd4_putfh *putfh) { DECODE_HEAD; READ_BUF(4); putfh->pf_fhlen = be32_to_cpup(p++); if (putfh->pf_fhlen > NFS4_FHSIZE) goto xdr_error; READ_BUF(putfh->pf_fhlen); SAVEMEM(putfh->pf_fhval, putfh->pf_fhlen); DECODE_TAIL; } static __be32 nfsd4_decode_putpubfh(struct nfsd4_compoundargs *argp, void *p) { if (argp->minorversion == 0) return nfs_ok; return nfserr_notsupp; } static __be32 nfsd4_decode_read(struct nfsd4_compoundargs *argp, struct nfsd4_read *read) { DECODE_HEAD; status = nfsd4_decode_stateid(argp, &read->rd_stateid); if (status) return status; READ_BUF(12); p = xdr_decode_hyper(p, &read->rd_offset); read->rd_length = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_readdir(struct nfsd4_compoundargs *argp, struct nfsd4_readdir *readdir) { DECODE_HEAD; READ_BUF(24); p = xdr_decode_hyper(p, &readdir->rd_cookie); COPYMEM(readdir->rd_verf.data, sizeof(readdir->rd_verf.data)); readdir->rd_dircount = be32_to_cpup(p++); readdir->rd_maxcount = be32_to_cpup(p++); if ((status = nfsd4_decode_bitmap(argp, readdir->rd_bmval))) goto out; DECODE_TAIL; } static __be32 nfsd4_decode_remove(struct nfsd4_compoundargs *argp, struct nfsd4_remove *remove) { DECODE_HEAD; READ_BUF(4); remove->rm_namelen = be32_to_cpup(p++); READ_BUF(remove->rm_namelen); SAVEMEM(remove->rm_name, remove->rm_namelen); if ((status = check_filename(remove->rm_name, remove->rm_namelen))) return status; DECODE_TAIL; } static __be32 nfsd4_decode_rename(struct nfsd4_compoundargs *argp, struct nfsd4_rename *rename) { DECODE_HEAD; READ_BUF(4); rename->rn_snamelen = be32_to_cpup(p++); READ_BUF(rename->rn_snamelen); SAVEMEM(rename->rn_sname, rename->rn_snamelen); READ_BUF(4); rename->rn_tnamelen = be32_to_cpup(p++); READ_BUF(rename->rn_tnamelen); SAVEMEM(rename->rn_tname, rename->rn_tnamelen); if ((status = check_filename(rename->rn_sname, rename->rn_snamelen))) return status; if ((status = check_filename(rename->rn_tname, rename->rn_tnamelen))) return status; DECODE_TAIL; } static __be32 nfsd4_decode_renew(struct nfsd4_compoundargs *argp, clientid_t *clientid) { DECODE_HEAD; if (argp->minorversion >= 1) return nfserr_notsupp; READ_BUF(sizeof(clientid_t)); COPYMEM(clientid, sizeof(clientid_t)); DECODE_TAIL; } static __be32 nfsd4_decode_secinfo(struct nfsd4_compoundargs *argp, struct nfsd4_secinfo *secinfo) { DECODE_HEAD; READ_BUF(4); secinfo->si_namelen = be32_to_cpup(p++); READ_BUF(secinfo->si_namelen); SAVEMEM(secinfo->si_name, secinfo->si_namelen); status = check_filename(secinfo->si_name, secinfo->si_namelen); if (status) return status; DECODE_TAIL; } static __be32 nfsd4_decode_secinfo_no_name(struct nfsd4_compoundargs *argp, struct nfsd4_secinfo_no_name *sin) { DECODE_HEAD; READ_BUF(4); sin->sin_style = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_setattr(struct nfsd4_compoundargs *argp, struct nfsd4_setattr *setattr) { __be32 status; status = nfsd4_decode_stateid(argp, &setattr->sa_stateid); if (status) return status; return nfsd4_decode_fattr(argp, setattr->sa_bmval, &setattr->sa_iattr, &setattr->sa_acl, &setattr->sa_label, NULL); } static __be32 nfsd4_decode_setclientid(struct nfsd4_compoundargs *argp, struct nfsd4_setclientid *setclientid) { DECODE_HEAD; if (argp->minorversion >= 1) return nfserr_notsupp; READ_BUF(NFS4_VERIFIER_SIZE); COPYMEM(setclientid->se_verf.data, NFS4_VERIFIER_SIZE); status = nfsd4_decode_opaque(argp, &setclientid->se_name); if (status) return nfserr_bad_xdr; READ_BUF(8); setclientid->se_callback_prog = be32_to_cpup(p++); setclientid->se_callback_netid_len = be32_to_cpup(p++); READ_BUF(setclientid->se_callback_netid_len); SAVEMEM(setclientid->se_callback_netid_val, setclientid->se_callback_netid_len); READ_BUF(4); setclientid->se_callback_addr_len = be32_to_cpup(p++); READ_BUF(setclientid->se_callback_addr_len); SAVEMEM(setclientid->se_callback_addr_val, setclientid->se_callback_addr_len); READ_BUF(4); setclientid->se_callback_ident = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_setclientid_confirm(struct nfsd4_compoundargs *argp, struct nfsd4_setclientid_confirm *scd_c) { DECODE_HEAD; if (argp->minorversion >= 1) return nfserr_notsupp; READ_BUF(8 + NFS4_VERIFIER_SIZE); COPYMEM(&scd_c->sc_clientid, 8); COPYMEM(&scd_c->sc_confirm, NFS4_VERIFIER_SIZE); DECODE_TAIL; } /* Also used for NVERIFY */ static __be32 nfsd4_decode_verify(struct nfsd4_compoundargs *argp, struct nfsd4_verify *verify) { DECODE_HEAD; if ((status = nfsd4_decode_bitmap(argp, verify->ve_bmval))) goto out; /* For convenience's sake, we compare raw xdr'd attributes in * nfsd4_proc_verify */ READ_BUF(4); verify->ve_attrlen = be32_to_cpup(p++); READ_BUF(verify->ve_attrlen); SAVEMEM(verify->ve_attrval, verify->ve_attrlen); DECODE_TAIL; } static __be32 nfsd4_decode_write(struct nfsd4_compoundargs *argp, struct nfsd4_write *write) { int avail; int len; DECODE_HEAD; status = nfsd4_decode_stateid(argp, &write->wr_stateid); if (status) return status; READ_BUF(16); p = xdr_decode_hyper(p, &write->wr_offset); write->wr_stable_how = be32_to_cpup(p++); if (write->wr_stable_how > NFS_FILE_SYNC) goto xdr_error; write->wr_buflen = be32_to_cpup(p++); /* Sorry .. no magic macros for this.. * * READ_BUF(write->wr_buflen); * SAVEMEM(write->wr_buf, write->wr_buflen); */ avail = (char*)argp->end - (char*)argp->p; if (avail + argp->pagelen < write->wr_buflen) { dprintk("NFSD: xdr error (%s:%d)\n", __FILE__, __LINE__); goto xdr_error; } write->wr_head.iov_base = p; write->wr_head.iov_len = avail; write->wr_pagelist = argp->pagelist; len = XDR_QUADLEN(write->wr_buflen) << 2; if (len >= avail) { int pages; len -= avail; pages = len >> PAGE_SHIFT; argp->pagelist += pages; argp->pagelen -= pages * PAGE_SIZE; len -= pages * PAGE_SIZE; argp->p = (__be32 *)page_address(argp->pagelist[0]); argp->pagelist++; argp->end = argp->p + XDR_QUADLEN(PAGE_SIZE); } argp->p += XDR_QUADLEN(len); DECODE_TAIL; } static __be32 nfsd4_decode_release_lockowner(struct nfsd4_compoundargs *argp, struct nfsd4_release_lockowner *rlockowner) { DECODE_HEAD; if (argp->minorversion >= 1) return nfserr_notsupp; READ_BUF(12); COPYMEM(&rlockowner->rl_clientid, sizeof(clientid_t)); rlockowner->rl_owner.len = be32_to_cpup(p++); READ_BUF(rlockowner->rl_owner.len); READMEM(rlockowner->rl_owner.data, rlockowner->rl_owner.len); if (argp->minorversion && !zero_clientid(&rlockowner->rl_clientid)) return nfserr_inval; DECODE_TAIL; } static __be32 nfsd4_decode_exchange_id(struct nfsd4_compoundargs *argp, struct nfsd4_exchange_id *exid) { int dummy, tmp; DECODE_HEAD; READ_BUF(NFS4_VERIFIER_SIZE); COPYMEM(exid->verifier.data, NFS4_VERIFIER_SIZE); status = nfsd4_decode_opaque(argp, &exid->clname); if (status) return nfserr_bad_xdr; READ_BUF(4); exid->flags = be32_to_cpup(p++); /* Ignore state_protect4_a */ READ_BUF(4); exid->spa_how = be32_to_cpup(p++); switch (exid->spa_how) { case SP4_NONE: break; case SP4_MACH_CRED: /* spo_must_enforce */ status = nfsd4_decode_bitmap(argp, exid->spo_must_enforce); if (status) goto out; /* spo_must_allow */ status = nfsd4_decode_bitmap(argp, exid->spo_must_allow); if (status) goto out; break; case SP4_SSV: /* ssp_ops */ READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy * 4); p += dummy; READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy * 4); p += dummy; /* ssp_hash_algs<> */ READ_BUF(4); tmp = be32_to_cpup(p++); while (tmp--) { READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy); p += XDR_QUADLEN(dummy); } /* ssp_encr_algs<> */ READ_BUF(4); tmp = be32_to_cpup(p++); while (tmp--) { READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy); p += XDR_QUADLEN(dummy); } /* ssp_window and ssp_num_gss_handles */ READ_BUF(8); dummy = be32_to_cpup(p++); dummy = be32_to_cpup(p++); break; default: goto xdr_error; } /* Ignore Implementation ID */ READ_BUF(4); /* nfs_impl_id4 array length */ dummy = be32_to_cpup(p++); if (dummy > 1) goto xdr_error; if (dummy == 1) { /* nii_domain */ READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy); p += XDR_QUADLEN(dummy); /* nii_name */ READ_BUF(4); dummy = be32_to_cpup(p++); READ_BUF(dummy); p += XDR_QUADLEN(dummy); /* nii_date */ READ_BUF(12); p += 3; } DECODE_TAIL; } static __be32 nfsd4_decode_create_session(struct nfsd4_compoundargs *argp, struct nfsd4_create_session *sess) { DECODE_HEAD; u32 dummy; READ_BUF(16); COPYMEM(&sess->clientid, 8); sess->seqid = be32_to_cpup(p++); sess->flags = be32_to_cpup(p++); /* Fore channel attrs */ READ_BUF(28); dummy = be32_to_cpup(p++); /* headerpadsz is always 0 */ sess->fore_channel.maxreq_sz = be32_to_cpup(p++); sess->fore_channel.maxresp_sz = be32_to_cpup(p++); sess->fore_channel.maxresp_cached = be32_to_cpup(p++); sess->fore_channel.maxops = be32_to_cpup(p++); sess->fore_channel.maxreqs = be32_to_cpup(p++); sess->fore_channel.nr_rdma_attrs = be32_to_cpup(p++); if (sess->fore_channel.nr_rdma_attrs == 1) { READ_BUF(4); sess->fore_channel.rdma_attrs = be32_to_cpup(p++); } else if (sess->fore_channel.nr_rdma_attrs > 1) { dprintk("Too many fore channel attr bitmaps!\n"); goto xdr_error; } /* Back channel attrs */ READ_BUF(28); dummy = be32_to_cpup(p++); /* headerpadsz is always 0 */ sess->back_channel.maxreq_sz = be32_to_cpup(p++); sess->back_channel.maxresp_sz = be32_to_cpup(p++); sess->back_channel.maxresp_cached = be32_to_cpup(p++); sess->back_channel.maxops = be32_to_cpup(p++); sess->back_channel.maxreqs = be32_to_cpup(p++); sess->back_channel.nr_rdma_attrs = be32_to_cpup(p++); if (sess->back_channel.nr_rdma_attrs == 1) { READ_BUF(4); sess->back_channel.rdma_attrs = be32_to_cpup(p++); } else if (sess->back_channel.nr_rdma_attrs > 1) { dprintk("Too many back channel attr bitmaps!\n"); goto xdr_error; } READ_BUF(4); sess->callback_prog = be32_to_cpup(p++); nfsd4_decode_cb_sec(argp, &sess->cb_sec); DECODE_TAIL; } static __be32 nfsd4_decode_destroy_session(struct nfsd4_compoundargs *argp, struct nfsd4_destroy_session *destroy_session) { DECODE_HEAD; READ_BUF(NFS4_MAX_SESSIONID_LEN); COPYMEM(destroy_session->sessionid.data, NFS4_MAX_SESSIONID_LEN); DECODE_TAIL; } static __be32 nfsd4_decode_free_stateid(struct nfsd4_compoundargs *argp, struct nfsd4_free_stateid *free_stateid) { DECODE_HEAD; READ_BUF(sizeof(stateid_t)); free_stateid->fr_stateid.si_generation = be32_to_cpup(p++); COPYMEM(&free_stateid->fr_stateid.si_opaque, sizeof(stateid_opaque_t)); DECODE_TAIL; } static __be32 nfsd4_decode_sequence(struct nfsd4_compoundargs *argp, struct nfsd4_sequence *seq) { DECODE_HEAD; READ_BUF(NFS4_MAX_SESSIONID_LEN + 16); COPYMEM(seq->sessionid.data, NFS4_MAX_SESSIONID_LEN); seq->seqid = be32_to_cpup(p++); seq->slotid = be32_to_cpup(p++); seq->maxslots = be32_to_cpup(p++); seq->cachethis = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_test_stateid(struct nfsd4_compoundargs *argp, struct nfsd4_test_stateid *test_stateid) { int i; __be32 *p, status; struct nfsd4_test_stateid_id *stateid; READ_BUF(4); test_stateid->ts_num_ids = ntohl(*p++); INIT_LIST_HEAD(&test_stateid->ts_stateid_list); for (i = 0; i < test_stateid->ts_num_ids; i++) { stateid = svcxdr_tmpalloc(argp, sizeof(*stateid)); if (!stateid) { status = nfserrno(-ENOMEM); goto out; } INIT_LIST_HEAD(&stateid->ts_id_list); list_add_tail(&stateid->ts_id_list, &test_stateid->ts_stateid_list); status = nfsd4_decode_stateid(argp, &stateid->ts_id_stateid); if (status) goto out; } status = 0; out: return status; xdr_error: dprintk("NFSD: xdr error (%s:%d)\n", __FILE__, __LINE__); status = nfserr_bad_xdr; goto out; } static __be32 nfsd4_decode_destroy_clientid(struct nfsd4_compoundargs *argp, struct nfsd4_destroy_clientid *dc) { DECODE_HEAD; READ_BUF(8); COPYMEM(&dc->clientid, 8); DECODE_TAIL; } static __be32 nfsd4_decode_reclaim_complete(struct nfsd4_compoundargs *argp, struct nfsd4_reclaim_complete *rc) { DECODE_HEAD; READ_BUF(4); rc->rca_one_fs = be32_to_cpup(p++); DECODE_TAIL; } #ifdef CONFIG_NFSD_PNFS static __be32 nfsd4_decode_getdeviceinfo(struct nfsd4_compoundargs *argp, struct nfsd4_getdeviceinfo *gdev) { DECODE_HEAD; u32 num, i; READ_BUF(sizeof(struct nfsd4_deviceid) + 3 * 4); COPYMEM(&gdev->gd_devid, sizeof(struct nfsd4_deviceid)); gdev->gd_layout_type = be32_to_cpup(p++); gdev->gd_maxcount = be32_to_cpup(p++); num = be32_to_cpup(p++); if (num) { READ_BUF(4 * num); gdev->gd_notify_types = be32_to_cpup(p++); for (i = 1; i < num; i++) { if (be32_to_cpup(p++)) { status = nfserr_inval; goto out; } } } DECODE_TAIL; } static __be32 nfsd4_decode_layoutget(struct nfsd4_compoundargs *argp, struct nfsd4_layoutget *lgp) { DECODE_HEAD; READ_BUF(36); lgp->lg_signal = be32_to_cpup(p++); lgp->lg_layout_type = be32_to_cpup(p++); lgp->lg_seg.iomode = be32_to_cpup(p++); p = xdr_decode_hyper(p, &lgp->lg_seg.offset); p = xdr_decode_hyper(p, &lgp->lg_seg.length); p = xdr_decode_hyper(p, &lgp->lg_minlength); status = nfsd4_decode_stateid(argp, &lgp->lg_sid); if (status) return status; READ_BUF(4); lgp->lg_maxcount = be32_to_cpup(p++); DECODE_TAIL; } static __be32 nfsd4_decode_layoutcommit(struct nfsd4_compoundargs *argp, struct nfsd4_layoutcommit *lcp) { DECODE_HEAD; u32 timechange; READ_BUF(20); p = xdr_decode_hyper(p, &lcp->lc_seg.offset); p = xdr_decode_hyper(p, &lcp->lc_seg.length); lcp->lc_reclaim = be32_to_cpup(p++); status = nfsd4_decode_stateid(argp, &lcp->lc_sid); if (status) return status; READ_BUF(4); lcp->lc_newoffset = be32_to_cpup(p++); if (lcp->lc_newoffset) { READ_BUF(8); p = xdr_decode_hyper(p, &lcp->lc_last_wr); } else lcp->lc_last_wr = 0; READ_BUF(4); timechange = be32_to_cpup(p++); if (timechange) { status = nfsd4_decode_time(argp, &lcp->lc_mtime); if (status) return status; } else { lcp->lc_mtime.tv_nsec = UTIME_NOW; } READ_BUF(8); lcp->lc_layout_type = be32_to_cpup(p++); /* * Save the layout update in XDR format and let the layout driver deal * with it later. */ lcp->lc_up_len = be32_to_cpup(p++); if (lcp->lc_up_len > 0) { READ_BUF(lcp->lc_up_len); READMEM(lcp->lc_up_layout, lcp->lc_up_len); } DECODE_TAIL; } static __be32 nfsd4_decode_layoutreturn(struct nfsd4_compoundargs *argp, struct nfsd4_layoutreturn *lrp) { DECODE_HEAD; READ_BUF(16); lrp->lr_reclaim = be32_to_cpup(p++); lrp->lr_layout_type = be32_to_cpup(p++); lrp->lr_seg.iomode = be32_to_cpup(p++); lrp->lr_return_type = be32_to_cpup(p++); if (lrp->lr_return_type == RETURN_FILE) { READ_BUF(16); p = xdr_decode_hyper(p, &lrp->lr_seg.offset); p = xdr_decode_hyper(p, &lrp->lr_seg.length); status = nfsd4_decode_stateid(argp, &lrp->lr_sid); if (status) return status; READ_BUF(4); lrp->lrf_body_len = be32_to_cpup(p++); if (lrp->lrf_body_len > 0) { READ_BUF(lrp->lrf_body_len); READMEM(lrp->lrf_body, lrp->lrf_body_len); } } else { lrp->lr_seg.offset = 0; lrp->lr_seg.length = NFS4_MAX_UINT64; } DECODE_TAIL; } #endif /* CONFIG_NFSD_PNFS */ static __be32 nfsd4_decode_fallocate(struct nfsd4_compoundargs *argp, struct nfsd4_fallocate *fallocate) { DECODE_HEAD; status = nfsd4_decode_stateid(argp, &fallocate->falloc_stateid); if (status) return status; READ_BUF(16); p = xdr_decode_hyper(p, &fallocate->falloc_offset); xdr_decode_hyper(p, &fallocate->falloc_length); DECODE_TAIL; } static __be32 nfsd4_decode_clone(struct nfsd4_compoundargs *argp, struct nfsd4_clone *clone) { DECODE_HEAD; status = nfsd4_decode_stateid(argp, &clone->cl_src_stateid); if (status) return status; status = nfsd4_decode_stateid(argp, &clone->cl_dst_stateid); if (status) return status; READ_BUF(8 + 8 + 8); p = xdr_decode_hyper(p, &clone->cl_src_pos); p = xdr_decode_hyper(p, &clone->cl_dst_pos); p = xdr_decode_hyper(p, &clone->cl_count); DECODE_TAIL; } static __be32 nfsd4_decode_copy(struct nfsd4_compoundargs *argp, struct nfsd4_copy *copy) { DECODE_HEAD; unsigned int tmp; status = nfsd4_decode_stateid(argp, &copy->cp_src_stateid); if (status) return status; status = nfsd4_decode_stateid(argp, &copy->cp_dst_stateid); if (status) return status; READ_BUF(8 + 8 + 8 + 4 + 4 + 4); p = xdr_decode_hyper(p, &copy->cp_src_pos); p = xdr_decode_hyper(p, &copy->cp_dst_pos); p = xdr_decode_hyper(p, &copy->cp_count); copy->cp_consecutive = be32_to_cpup(p++); copy->cp_synchronous = be32_to_cpup(p++); tmp = be32_to_cpup(p); /* Source server list not supported */ DECODE_TAIL; } static __be32 nfsd4_decode_seek(struct nfsd4_compoundargs *argp, struct nfsd4_seek *seek) { DECODE_HEAD; status = nfsd4_decode_stateid(argp, &seek->seek_stateid); if (status) return status; READ_BUF(8 + 4); p = xdr_decode_hyper(p, &seek->seek_offset); seek->seek_whence = be32_to_cpup(p); DECODE_TAIL; } static __be32 nfsd4_decode_noop(struct nfsd4_compoundargs *argp, void *p) { return nfs_ok; } static __be32 nfsd4_decode_notsupp(struct nfsd4_compoundargs *argp, void *p) { return nfserr_notsupp; } typedef __be32(*nfsd4_dec)(struct nfsd4_compoundargs *argp, void *); static nfsd4_dec nfsd4_dec_ops[] = { [OP_ACCESS] = (nfsd4_dec)nfsd4_decode_access, [OP_CLOSE] = (nfsd4_dec)nfsd4_decode_close, [OP_COMMIT] = (nfsd4_dec)nfsd4_decode_commit, [OP_CREATE] = (nfsd4_dec)nfsd4_decode_create, [OP_DELEGPURGE] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_DELEGRETURN] = (nfsd4_dec)nfsd4_decode_delegreturn, [OP_GETATTR] = (nfsd4_dec)nfsd4_decode_getattr, [OP_GETFH] = (nfsd4_dec)nfsd4_decode_noop, [OP_LINK] = (nfsd4_dec)nfsd4_decode_link, [OP_LOCK] = (nfsd4_dec)nfsd4_decode_lock, [OP_LOCKT] = (nfsd4_dec)nfsd4_decode_lockt, [OP_LOCKU] = (nfsd4_dec)nfsd4_decode_locku, [OP_LOOKUP] = (nfsd4_dec)nfsd4_decode_lookup, [OP_LOOKUPP] = (nfsd4_dec)nfsd4_decode_noop, [OP_NVERIFY] = (nfsd4_dec)nfsd4_decode_verify, [OP_OPEN] = (nfsd4_dec)nfsd4_decode_open, [OP_OPENATTR] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_OPEN_CONFIRM] = (nfsd4_dec)nfsd4_decode_open_confirm, [OP_OPEN_DOWNGRADE] = (nfsd4_dec)nfsd4_decode_open_downgrade, [OP_PUTFH] = (nfsd4_dec)nfsd4_decode_putfh, [OP_PUTPUBFH] = (nfsd4_dec)nfsd4_decode_putpubfh, [OP_PUTROOTFH] = (nfsd4_dec)nfsd4_decode_noop, [OP_READ] = (nfsd4_dec)nfsd4_decode_read, [OP_READDIR] = (nfsd4_dec)nfsd4_decode_readdir, [OP_READLINK] = (nfsd4_dec)nfsd4_decode_noop, [OP_REMOVE] = (nfsd4_dec)nfsd4_decode_remove, [OP_RENAME] = (nfsd4_dec)nfsd4_decode_rename, [OP_RENEW] = (nfsd4_dec)nfsd4_decode_renew, [OP_RESTOREFH] = (nfsd4_dec)nfsd4_decode_noop, [OP_SAVEFH] = (nfsd4_dec)nfsd4_decode_noop, [OP_SECINFO] = (nfsd4_dec)nfsd4_decode_secinfo, [OP_SETATTR] = (nfsd4_dec)nfsd4_decode_setattr, [OP_SETCLIENTID] = (nfsd4_dec)nfsd4_decode_setclientid, [OP_SETCLIENTID_CONFIRM] = (nfsd4_dec)nfsd4_decode_setclientid_confirm, [OP_VERIFY] = (nfsd4_dec)nfsd4_decode_verify, [OP_WRITE] = (nfsd4_dec)nfsd4_decode_write, [OP_RELEASE_LOCKOWNER] = (nfsd4_dec)nfsd4_decode_release_lockowner, /* new operations for NFSv4.1 */ [OP_BACKCHANNEL_CTL] = (nfsd4_dec)nfsd4_decode_backchannel_ctl, [OP_BIND_CONN_TO_SESSION]= (nfsd4_dec)nfsd4_decode_bind_conn_to_session, [OP_EXCHANGE_ID] = (nfsd4_dec)nfsd4_decode_exchange_id, [OP_CREATE_SESSION] = (nfsd4_dec)nfsd4_decode_create_session, [OP_DESTROY_SESSION] = (nfsd4_dec)nfsd4_decode_destroy_session, [OP_FREE_STATEID] = (nfsd4_dec)nfsd4_decode_free_stateid, [OP_GET_DIR_DELEGATION] = (nfsd4_dec)nfsd4_decode_notsupp, #ifdef CONFIG_NFSD_PNFS [OP_GETDEVICEINFO] = (nfsd4_dec)nfsd4_decode_getdeviceinfo, [OP_GETDEVICELIST] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_LAYOUTCOMMIT] = (nfsd4_dec)nfsd4_decode_layoutcommit, [OP_LAYOUTGET] = (nfsd4_dec)nfsd4_decode_layoutget, [OP_LAYOUTRETURN] = (nfsd4_dec)nfsd4_decode_layoutreturn, #else [OP_GETDEVICEINFO] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_GETDEVICELIST] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_LAYOUTCOMMIT] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_LAYOUTGET] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_LAYOUTRETURN] = (nfsd4_dec)nfsd4_decode_notsupp, #endif [OP_SECINFO_NO_NAME] = (nfsd4_dec)nfsd4_decode_secinfo_no_name, [OP_SEQUENCE] = (nfsd4_dec)nfsd4_decode_sequence, [OP_SET_SSV] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_TEST_STATEID] = (nfsd4_dec)nfsd4_decode_test_stateid, [OP_WANT_DELEGATION] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_DESTROY_CLIENTID] = (nfsd4_dec)nfsd4_decode_destroy_clientid, [OP_RECLAIM_COMPLETE] = (nfsd4_dec)nfsd4_decode_reclaim_complete, /* new operations for NFSv4.2 */ [OP_ALLOCATE] = (nfsd4_dec)nfsd4_decode_fallocate, [OP_COPY] = (nfsd4_dec)nfsd4_decode_copy, [OP_COPY_NOTIFY] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_DEALLOCATE] = (nfsd4_dec)nfsd4_decode_fallocate, [OP_IO_ADVISE] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_LAYOUTERROR] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_LAYOUTSTATS] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_OFFLOAD_CANCEL] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_OFFLOAD_STATUS] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_READ_PLUS] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_SEEK] = (nfsd4_dec)nfsd4_decode_seek, [OP_WRITE_SAME] = (nfsd4_dec)nfsd4_decode_notsupp, [OP_CLONE] = (nfsd4_dec)nfsd4_decode_clone, }; static inline bool nfsd4_opnum_in_range(struct nfsd4_compoundargs *argp, struct nfsd4_op *op) { if (op->opnum < FIRST_NFS4_OP) return false; else if (argp->minorversion == 0 && op->opnum > LAST_NFS40_OP) return false; else if (argp->minorversion == 1 && op->opnum > LAST_NFS41_OP) return false; else if (argp->minorversion == 2 && op->opnum > LAST_NFS42_OP) return false; return true; } static __be32 nfsd4_decode_compound(struct nfsd4_compoundargs *argp) { DECODE_HEAD; struct nfsd4_op *op; bool cachethis = false; int auth_slack= argp->rqstp->rq_auth_slack; int max_reply = auth_slack + 8; /* opcnt, status */ int readcount = 0; int readbytes = 0; int i; READ_BUF(4); argp->taglen = be32_to_cpup(p++); READ_BUF(argp->taglen); SAVEMEM(argp->tag, argp->taglen); READ_BUF(8); argp->minorversion = be32_to_cpup(p++); argp->opcnt = be32_to_cpup(p++); max_reply += 4 + (XDR_QUADLEN(argp->taglen) << 2); if (argp->taglen > NFSD4_MAX_TAGLEN) goto xdr_error; if (argp->opcnt > 100) goto xdr_error; if (argp->opcnt > ARRAY_SIZE(argp->iops)) { argp->ops = kzalloc(argp->opcnt * sizeof(*argp->ops), GFP_KERNEL); if (!argp->ops) { argp->ops = argp->iops; dprintk("nfsd: couldn't allocate room for COMPOUND\n"); goto xdr_error; } } if (argp->minorversion > NFSD_SUPPORTED_MINOR_VERSION) argp->opcnt = 0; for (i = 0; i < argp->opcnt; i++) { op = &argp->ops[i]; op->replay = NULL; READ_BUF(4); op->opnum = be32_to_cpup(p++); if (nfsd4_opnum_in_range(argp, op)) op->status = nfsd4_dec_ops[op->opnum](argp, &op->u); else { op->opnum = OP_ILLEGAL; op->status = nfserr_op_illegal; } /* * We'll try to cache the result in the DRC if any one * op in the compound wants to be cached: */ cachethis |= nfsd4_cache_this_op(op); if (op->opnum == OP_READ) { readcount++; readbytes += nfsd4_max_reply(argp->rqstp, op); } else max_reply += nfsd4_max_reply(argp->rqstp, op); /* * OP_LOCK and OP_LOCKT may return a conflicting lock. * (Special case because it will just skip encoding this * if it runs out of xdr buffer space, and it is the only * operation that behaves this way.) */ if (op->opnum == OP_LOCK || op->opnum == OP_LOCKT) max_reply += NFS4_OPAQUE_LIMIT; if (op->status) { argp->opcnt = i+1; break; } } /* Sessions make the DRC unnecessary: */ if (argp->minorversion) cachethis = false; svc_reserve(argp->rqstp, max_reply + readbytes); argp->rqstp->rq_cachetype = cachethis ? RC_REPLBUFF : RC_NOCACHE; if (readcount > 1 || max_reply > PAGE_SIZE - auth_slack) clear_bit(RQ_SPLICE_OK, &argp->rqstp->rq_flags); DECODE_TAIL; } static __be32 *encode_change(__be32 *p, struct kstat *stat, struct inode *inode, struct svc_export *exp) { if (exp->ex_flags & NFSEXP_V4ROOT) { *p++ = cpu_to_be32(convert_to_wallclock(exp->cd->flush_time)); *p++ = 0; } else if (IS_I_VERSION(inode)) { p = xdr_encode_hyper(p, inode->i_version); } else { *p++ = cpu_to_be32(stat->ctime.tv_sec); *p++ = cpu_to_be32(stat->ctime.tv_nsec); } return p; } static __be32 *encode_cinfo(__be32 *p, struct nfsd4_change_info *c) { *p++ = cpu_to_be32(c->atomic); if (c->change_supported) { p = xdr_encode_hyper(p, c->before_change); p = xdr_encode_hyper(p, c->after_change); } else { *p++ = cpu_to_be32(c->before_ctime_sec); *p++ = cpu_to_be32(c->before_ctime_nsec); *p++ = cpu_to_be32(c->after_ctime_sec); *p++ = cpu_to_be32(c->after_ctime_nsec); } return p; } /* Encode as an array of strings the string given with components * separated @sep, escaped with esc_enter and esc_exit. */ static __be32 nfsd4_encode_components_esc(struct xdr_stream *xdr, char sep, char *components, char esc_enter, char esc_exit) { __be32 *p; __be32 pathlen; int pathlen_offset; int strlen, count=0; char *str, *end, *next; dprintk("nfsd4_encode_components(%s)\n", components); pathlen_offset = xdr->buf->len; p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; p++; /* We will fill this in with @count later */ end = str = components; while (*end) { bool found_esc = false; /* try to parse as esc_start, ..., esc_end, sep */ if (*str == esc_enter) { for (; *end && (*end != esc_exit); end++) /* find esc_exit or end of string */; next = end + 1; if (*end && (!*next || *next == sep)) { str++; found_esc = true; } } if (!found_esc) for (; *end && (*end != sep); end++) /* find sep or end of string */; strlen = end - str; if (strlen) { p = xdr_reserve_space(xdr, strlen + 4); if (!p) return nfserr_resource; p = xdr_encode_opaque(p, str, strlen); count++; } else end++; if (found_esc) end = next; str = end; } pathlen = htonl(count); write_bytes_to_xdr_buf(xdr->buf, pathlen_offset, &pathlen, 4); return 0; } /* Encode as an array of strings the string given with components * separated @sep. */ static __be32 nfsd4_encode_components(struct xdr_stream *xdr, char sep, char *components) { return nfsd4_encode_components_esc(xdr, sep, components, 0, 0); } /* * encode a location element of a fs_locations structure */ static __be32 nfsd4_encode_fs_location4(struct xdr_stream *xdr, struct nfsd4_fs_location *location) { __be32 status; status = nfsd4_encode_components_esc(xdr, ':', location->hosts, '[', ']'); if (status) return status; status = nfsd4_encode_components(xdr, '/', location->path); if (status) return status; return 0; } /* * Encode a path in RFC3530 'pathname4' format */ static __be32 nfsd4_encode_path(struct xdr_stream *xdr, const struct path *root, const struct path *path) { struct path cur = *path; __be32 *p; struct dentry **components = NULL; unsigned int ncomponents = 0; __be32 err = nfserr_jukebox; dprintk("nfsd4_encode_components("); path_get(&cur); /* First walk the path up to the nfsd root, and store the * dentries/path components in an array. */ for (;;) { if (path_equal(&cur, root)) break; if (cur.dentry == cur.mnt->mnt_root) { if (follow_up(&cur)) continue; goto out_free; } if ((ncomponents & 15) == 0) { struct dentry **new; new = krealloc(components, sizeof(*new) * (ncomponents + 16), GFP_KERNEL); if (!new) goto out_free; components = new; } components[ncomponents++] = cur.dentry; cur.dentry = dget_parent(cur.dentry); } err = nfserr_resource; p = xdr_reserve_space(xdr, 4); if (!p) goto out_free; *p++ = cpu_to_be32(ncomponents); while (ncomponents) { struct dentry *dentry = components[ncomponents - 1]; unsigned int len; spin_lock(&dentry->d_lock); len = dentry->d_name.len; p = xdr_reserve_space(xdr, len + 4); if (!p) { spin_unlock(&dentry->d_lock); goto out_free; } p = xdr_encode_opaque(p, dentry->d_name.name, len); dprintk("/%pd", dentry); spin_unlock(&dentry->d_lock); dput(dentry); ncomponents--; } err = 0; out_free: dprintk(")\n"); while (ncomponents) dput(components[--ncomponents]); kfree(components); path_put(&cur); return err; } static __be32 nfsd4_encode_fsloc_fsroot(struct xdr_stream *xdr, struct svc_rqst *rqstp, const struct path *path) { struct svc_export *exp_ps; __be32 res; exp_ps = rqst_find_fsidzero_export(rqstp); if (IS_ERR(exp_ps)) return nfserrno(PTR_ERR(exp_ps)); res = nfsd4_encode_path(xdr, &exp_ps->ex_path, path); exp_put(exp_ps); return res; } /* * encode a fs_locations structure */ static __be32 nfsd4_encode_fs_locations(struct xdr_stream *xdr, struct svc_rqst *rqstp, struct svc_export *exp) { __be32 status; int i; __be32 *p; struct nfsd4_fs_locations *fslocs = &exp->ex_fslocs; status = nfsd4_encode_fsloc_fsroot(xdr, rqstp, &exp->ex_path); if (status) return status; p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; *p++ = cpu_to_be32(fslocs->locations_count); for (i=0; i<fslocs->locations_count; i++) { status = nfsd4_encode_fs_location4(xdr, &fslocs->locations[i]); if (status) return status; } return 0; } static u32 nfs4_file_type(umode_t mode) { switch (mode & S_IFMT) { case S_IFIFO: return NF4FIFO; case S_IFCHR: return NF4CHR; case S_IFDIR: return NF4DIR; case S_IFBLK: return NF4BLK; case S_IFLNK: return NF4LNK; case S_IFREG: return NF4REG; case S_IFSOCK: return NF4SOCK; default: return NF4BAD; }; } static inline __be32 nfsd4_encode_aclname(struct xdr_stream *xdr, struct svc_rqst *rqstp, struct nfs4_ace *ace) { if (ace->whotype != NFS4_ACL_WHO_NAMED) return nfs4_acl_write_who(xdr, ace->whotype); else if (ace->flag & NFS4_ACE_IDENTIFIER_GROUP) return nfsd4_encode_group(xdr, rqstp, ace->who_gid); else return nfsd4_encode_user(xdr, rqstp, ace->who_uid); } static inline __be32 nfsd4_encode_layout_types(struct xdr_stream *xdr, u32 layout_types) { __be32 *p; unsigned long i = hweight_long(layout_types); p = xdr_reserve_space(xdr, 4 + 4 * i); if (!p) return nfserr_resource; *p++ = cpu_to_be32(i); for (i = LAYOUT_NFSV4_1_FILES; i < LAYOUT_TYPE_MAX; ++i) if (layout_types & (1 << i)) *p++ = cpu_to_be32(i); return 0; } #define WORD0_ABSENT_FS_ATTRS (FATTR4_WORD0_FS_LOCATIONS | FATTR4_WORD0_FSID | \ FATTR4_WORD0_RDATTR_ERROR) #define WORD1_ABSENT_FS_ATTRS FATTR4_WORD1_MOUNTED_ON_FILEID #define WORD2_ABSENT_FS_ATTRS 0 #ifdef CONFIG_NFSD_V4_SECURITY_LABEL static inline __be32 nfsd4_encode_security_label(struct xdr_stream *xdr, struct svc_rqst *rqstp, void *context, int len) { __be32 *p; p = xdr_reserve_space(xdr, len + 4 + 4 + 4); if (!p) return nfserr_resource; /* * For now we use a 0 here to indicate the null translation; in * the future we may place a call to translation code here. */ *p++ = cpu_to_be32(0); /* lfs */ *p++ = cpu_to_be32(0); /* pi */ p = xdr_encode_opaque(p, context, len); return 0; } #else static inline __be32 nfsd4_encode_security_label(struct xdr_stream *xdr, struct svc_rqst *rqstp, void *context, int len) { return 0; } #endif static __be32 fattr_handle_absent_fs(u32 *bmval0, u32 *bmval1, u32 *bmval2, u32 *rdattr_err) { /* As per referral draft: */ if (*bmval0 & ~WORD0_ABSENT_FS_ATTRS || *bmval1 & ~WORD1_ABSENT_FS_ATTRS) { if (*bmval0 & FATTR4_WORD0_RDATTR_ERROR || *bmval0 & FATTR4_WORD0_FS_LOCATIONS) *rdattr_err = NFSERR_MOVED; else return nfserr_moved; } *bmval0 &= WORD0_ABSENT_FS_ATTRS; *bmval1 &= WORD1_ABSENT_FS_ATTRS; *bmval2 &= WORD2_ABSENT_FS_ATTRS; return 0; } static int get_parent_attributes(struct svc_export *exp, struct kstat *stat) { struct path path = exp->ex_path; int err; path_get(&path); while (follow_up(&path)) { if (path.dentry != path.mnt->mnt_root) break; } err = vfs_getattr(&path, stat, STATX_BASIC_STATS, AT_STATX_SYNC_AS_STAT); path_put(&path); return err; } static __be32 nfsd4_encode_bitmap(struct xdr_stream *xdr, u32 bmval0, u32 bmval1, u32 bmval2) { __be32 *p; if (bmval2) { p = xdr_reserve_space(xdr, 16); if (!p) goto out_resource; *p++ = cpu_to_be32(3); *p++ = cpu_to_be32(bmval0); *p++ = cpu_to_be32(bmval1); *p++ = cpu_to_be32(bmval2); } else if (bmval1) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; *p++ = cpu_to_be32(2); *p++ = cpu_to_be32(bmval0); *p++ = cpu_to_be32(bmval1); } else { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; *p++ = cpu_to_be32(1); *p++ = cpu_to_be32(bmval0); } return 0; out_resource: return nfserr_resource; } /* * Note: @fhp can be NULL; in this case, we might have to compose the filehandle * ourselves. */ static __be32 nfsd4_encode_fattr(struct xdr_stream *xdr, struct svc_fh *fhp, struct svc_export *exp, struct dentry *dentry, u32 *bmval, struct svc_rqst *rqstp, int ignore_crossmnt) { u32 bmval0 = bmval[0]; u32 bmval1 = bmval[1]; u32 bmval2 = bmval[2]; struct kstat stat; struct svc_fh *tempfh = NULL; struct kstatfs statfs; __be32 *p; int starting_len = xdr->buf->len; int attrlen_offset; __be32 attrlen; u32 dummy; u64 dummy64; u32 rdattr_err = 0; __be32 status; int err; struct nfs4_acl *acl = NULL; void *context = NULL; int contextlen; bool contextsupport = false; struct nfsd4_compoundres *resp = rqstp->rq_resp; u32 minorversion = resp->cstate.minorversion; struct path path = { .mnt = exp->ex_path.mnt, .dentry = dentry, }; struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id); BUG_ON(bmval1 & NFSD_WRITEONLY_ATTRS_WORD1); BUG_ON(!nfsd_attrs_supported(minorversion, bmval)); if (exp->ex_fslocs.migrated) { status = fattr_handle_absent_fs(&bmval0, &bmval1, &bmval2, &rdattr_err); if (status) goto out; } err = vfs_getattr(&path, &stat, STATX_BASIC_STATS, AT_STATX_SYNC_AS_STAT); if (err) goto out_nfserr; if ((bmval0 & (FATTR4_WORD0_FILES_AVAIL | FATTR4_WORD0_FILES_FREE | FATTR4_WORD0_FILES_TOTAL | FATTR4_WORD0_MAXNAME)) || (bmval1 & (FATTR4_WORD1_SPACE_AVAIL | FATTR4_WORD1_SPACE_FREE | FATTR4_WORD1_SPACE_TOTAL))) { err = vfs_statfs(&path, &statfs); if (err) goto out_nfserr; } if ((bmval0 & (FATTR4_WORD0_FILEHANDLE | FATTR4_WORD0_FSID)) && !fhp) { tempfh = kmalloc(sizeof(struct svc_fh), GFP_KERNEL); status = nfserr_jukebox; if (!tempfh) goto out; fh_init(tempfh, NFS4_FHSIZE); status = fh_compose(tempfh, exp, dentry, NULL); if (status) goto out; fhp = tempfh; } if (bmval0 & FATTR4_WORD0_ACL) { err = nfsd4_get_nfs4_acl(rqstp, dentry, &acl); if (err == -EOPNOTSUPP) bmval0 &= ~FATTR4_WORD0_ACL; else if (err == -EINVAL) { status = nfserr_attrnotsupp; goto out; } else if (err != 0) goto out_nfserr; } #ifdef CONFIG_NFSD_V4_SECURITY_LABEL if ((bmval2 & FATTR4_WORD2_SECURITY_LABEL) || bmval0 & FATTR4_WORD0_SUPPORTED_ATTRS) { if (exp->ex_flags & NFSEXP_SECURITY_LABEL) err = security_inode_getsecctx(d_inode(dentry), &context, &contextlen); else err = -EOPNOTSUPP; contextsupport = (err == 0); if (bmval2 & FATTR4_WORD2_SECURITY_LABEL) { if (err == -EOPNOTSUPP) bmval2 &= ~FATTR4_WORD2_SECURITY_LABEL; else if (err) goto out_nfserr; } } #endif /* CONFIG_NFSD_V4_SECURITY_LABEL */ status = nfsd4_encode_bitmap(xdr, bmval0, bmval1, bmval2); if (status) goto out; attrlen_offset = xdr->buf->len; p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; p++; /* to be backfilled later */ if (bmval0 & FATTR4_WORD0_SUPPORTED_ATTRS) { u32 supp[3]; memcpy(supp, nfsd_suppattrs[minorversion], sizeof(supp)); if (!IS_POSIXACL(dentry->d_inode)) supp[0] &= ~FATTR4_WORD0_ACL; if (!contextsupport) supp[2] &= ~FATTR4_WORD2_SECURITY_LABEL; if (!supp[2]) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; *p++ = cpu_to_be32(2); *p++ = cpu_to_be32(supp[0]); *p++ = cpu_to_be32(supp[1]); } else { p = xdr_reserve_space(xdr, 16); if (!p) goto out_resource; *p++ = cpu_to_be32(3); *p++ = cpu_to_be32(supp[0]); *p++ = cpu_to_be32(supp[1]); *p++ = cpu_to_be32(supp[2]); } } if (bmval0 & FATTR4_WORD0_TYPE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; dummy = nfs4_file_type(stat.mode); if (dummy == NF4BAD) { status = nfserr_serverfault; goto out; } *p++ = cpu_to_be32(dummy); } if (bmval0 & FATTR4_WORD0_FH_EXPIRE_TYPE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; if (exp->ex_flags & NFSEXP_NOSUBTREECHECK) *p++ = cpu_to_be32(NFS4_FH_PERSISTENT); else *p++ = cpu_to_be32(NFS4_FH_PERSISTENT| NFS4_FH_VOL_RENAME); } if (bmval0 & FATTR4_WORD0_CHANGE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = encode_change(p, &stat, d_inode(dentry), exp); } if (bmval0 & FATTR4_WORD0_SIZE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, stat.size); } if (bmval0 & FATTR4_WORD0_LINK_SUPPORT) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_SYMLINK_SUPPORT) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_NAMED_ATTR) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); } if (bmval0 & FATTR4_WORD0_FSID) { p = xdr_reserve_space(xdr, 16); if (!p) goto out_resource; if (exp->ex_fslocs.migrated) { p = xdr_encode_hyper(p, NFS4_REFERRAL_FSID_MAJOR); p = xdr_encode_hyper(p, NFS4_REFERRAL_FSID_MINOR); } else switch(fsid_source(fhp)) { case FSIDSOURCE_FSID: p = xdr_encode_hyper(p, (u64)exp->ex_fsid); p = xdr_encode_hyper(p, (u64)0); break; case FSIDSOURCE_DEV: *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(MAJOR(stat.dev)); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(MINOR(stat.dev)); break; case FSIDSOURCE_UUID: p = xdr_encode_opaque_fixed(p, exp->ex_uuid, EX_UUID_LEN); break; } } if (bmval0 & FATTR4_WORD0_UNIQUE_HANDLES) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); } if (bmval0 & FATTR4_WORD0_LEASE_TIME) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(nn->nfsd4_lease); } if (bmval0 & FATTR4_WORD0_RDATTR_ERROR) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(rdattr_err); } if (bmval0 & FATTR4_WORD0_ACL) { struct nfs4_ace *ace; if (acl == NULL) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); goto out_acl; } p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(acl->naces); for (ace = acl->aces; ace < acl->aces + acl->naces; ace++) { p = xdr_reserve_space(xdr, 4*3); if (!p) goto out_resource; *p++ = cpu_to_be32(ace->type); *p++ = cpu_to_be32(ace->flag); *p++ = cpu_to_be32(ace->access_mask & NFS4_ACE_MASK_ALL); status = nfsd4_encode_aclname(xdr, rqstp, ace); if (status) goto out; } } out_acl: if (bmval0 & FATTR4_WORD0_ACLSUPPORT) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(IS_POSIXACL(dentry->d_inode) ? ACL4_SUPPORT_ALLOW_ACL|ACL4_SUPPORT_DENY_ACL : 0); } if (bmval0 & FATTR4_WORD0_CANSETTIME) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_CASE_INSENSITIVE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); } if (bmval0 & FATTR4_WORD0_CASE_PRESERVING) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_CHOWN_RESTRICTED) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_FILEHANDLE) { p = xdr_reserve_space(xdr, fhp->fh_handle.fh_size + 4); if (!p) goto out_resource; p = xdr_encode_opaque(p, &fhp->fh_handle.fh_base, fhp->fh_handle.fh_size); } if (bmval0 & FATTR4_WORD0_FILEID) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, stat.ino); } if (bmval0 & FATTR4_WORD0_FILES_AVAIL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) statfs.f_ffree); } if (bmval0 & FATTR4_WORD0_FILES_FREE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) statfs.f_ffree); } if (bmval0 & FATTR4_WORD0_FILES_TOTAL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) statfs.f_files); } if (bmval0 & FATTR4_WORD0_FS_LOCATIONS) { status = nfsd4_encode_fs_locations(xdr, rqstp, exp); if (status) goto out; } if (bmval0 & FATTR4_WORD0_HOMOGENEOUS) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_MAXFILESIZE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, exp->ex_path.mnt->mnt_sb->s_maxbytes); } if (bmval0 & FATTR4_WORD0_MAXLINK) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(255); } if (bmval0 & FATTR4_WORD0_MAXNAME) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(statfs.f_namelen); } if (bmval0 & FATTR4_WORD0_MAXREAD) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) svc_max_payload(rqstp)); } if (bmval0 & FATTR4_WORD0_MAXWRITE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) svc_max_payload(rqstp)); } if (bmval1 & FATTR4_WORD1_MODE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(stat.mode & S_IALLUGO); } if (bmval1 & FATTR4_WORD1_NO_TRUNC) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval1 & FATTR4_WORD1_NUMLINKS) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(stat.nlink); } if (bmval1 & FATTR4_WORD1_OWNER) { status = nfsd4_encode_user(xdr, rqstp, stat.uid); if (status) goto out; } if (bmval1 & FATTR4_WORD1_OWNER_GROUP) { status = nfsd4_encode_group(xdr, rqstp, stat.gid); if (status) goto out; } if (bmval1 & FATTR4_WORD1_RAWDEV) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; *p++ = cpu_to_be32((u32) MAJOR(stat.rdev)); *p++ = cpu_to_be32((u32) MINOR(stat.rdev)); } if (bmval1 & FATTR4_WORD1_SPACE_AVAIL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)statfs.f_bavail * (u64)statfs.f_bsize; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_SPACE_FREE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)statfs.f_bfree * (u64)statfs.f_bsize; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_SPACE_TOTAL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)statfs.f_blocks * (u64)statfs.f_bsize; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_SPACE_USED) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)stat.blocks << 9; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_TIME_ACCESS) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; p = xdr_encode_hyper(p, (s64)stat.atime.tv_sec); *p++ = cpu_to_be32(stat.atime.tv_nsec); } if (bmval1 & FATTR4_WORD1_TIME_DELTA) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(1); *p++ = cpu_to_be32(0); } if (bmval1 & FATTR4_WORD1_TIME_METADATA) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; p = xdr_encode_hyper(p, (s64)stat.ctime.tv_sec); *p++ = cpu_to_be32(stat.ctime.tv_nsec); } if (bmval1 & FATTR4_WORD1_TIME_MODIFY) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; p = xdr_encode_hyper(p, (s64)stat.mtime.tv_sec); *p++ = cpu_to_be32(stat.mtime.tv_nsec); } if (bmval1 & FATTR4_WORD1_MOUNTED_ON_FILEID) { struct kstat parent_stat; u64 ino = stat.ino; p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; /* * Get parent's attributes if not ignoring crossmount * and this is the root of a cross-mounted filesystem. */ if (ignore_crossmnt == 0 && dentry == exp->ex_path.mnt->mnt_root) { err = get_parent_attributes(exp, &parent_stat); if (err) goto out_nfserr; ino = parent_stat.ino; } p = xdr_encode_hyper(p, ino); } #ifdef CONFIG_NFSD_PNFS if (bmval1 & FATTR4_WORD1_FS_LAYOUT_TYPES) { status = nfsd4_encode_layout_types(xdr, exp->ex_layout_types); if (status) goto out; } if (bmval2 & FATTR4_WORD2_LAYOUT_TYPES) { status = nfsd4_encode_layout_types(xdr, exp->ex_layout_types); if (status) goto out; } if (bmval2 & FATTR4_WORD2_LAYOUT_BLKSIZE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(stat.blksize); } #endif /* CONFIG_NFSD_PNFS */ if (bmval2 & FATTR4_WORD2_SUPPATTR_EXCLCREAT) { status = nfsd4_encode_bitmap(xdr, NFSD_SUPPATTR_EXCLCREAT_WORD0, NFSD_SUPPATTR_EXCLCREAT_WORD1, NFSD_SUPPATTR_EXCLCREAT_WORD2); if (status) goto out; } if (bmval2 & FATTR4_WORD2_SECURITY_LABEL) { status = nfsd4_encode_security_label(xdr, rqstp, context, contextlen); if (status) goto out; } attrlen = htonl(xdr->buf->len - attrlen_offset - 4); write_bytes_to_xdr_buf(xdr->buf, attrlen_offset, &attrlen, 4); status = nfs_ok; out: #ifdef CONFIG_NFSD_V4_SECURITY_LABEL if (context) security_release_secctx(context, contextlen); #endif /* CONFIG_NFSD_V4_SECURITY_LABEL */ kfree(acl); if (tempfh) { fh_put(tempfh); kfree(tempfh); } if (status) xdr_truncate_encode(xdr, starting_len); return status; out_nfserr: status = nfserrno(err); goto out; out_resource: status = nfserr_resource; goto out; } static void svcxdr_init_encode_from_buffer(struct xdr_stream *xdr, struct xdr_buf *buf, __be32 *p, int bytes) { xdr->scratch.iov_len = 0; memset(buf, 0, sizeof(struct xdr_buf)); buf->head[0].iov_base = p; buf->head[0].iov_len = 0; buf->len = 0; xdr->buf = buf; xdr->iov = buf->head; xdr->p = p; xdr->end = (void *)p + bytes; buf->buflen = bytes; } __be32 nfsd4_encode_fattr_to_buf(__be32 **p, int words, struct svc_fh *fhp, struct svc_export *exp, struct dentry *dentry, u32 *bmval, struct svc_rqst *rqstp, int ignore_crossmnt) { struct xdr_buf dummy; struct xdr_stream xdr; __be32 ret; svcxdr_init_encode_from_buffer(&xdr, &dummy, *p, words << 2); ret = nfsd4_encode_fattr(&xdr, fhp, exp, dentry, bmval, rqstp, ignore_crossmnt); *p = xdr.p; return ret; } static inline int attributes_need_mount(u32 *bmval) { if (bmval[0] & ~(FATTR4_WORD0_RDATTR_ERROR | FATTR4_WORD0_LEASE_TIME)) return 1; if (bmval[1] & ~FATTR4_WORD1_MOUNTED_ON_FILEID) return 1; return 0; } static __be32 nfsd4_encode_dirent_fattr(struct xdr_stream *xdr, struct nfsd4_readdir *cd, const char *name, int namlen) { struct svc_export *exp = cd->rd_fhp->fh_export; struct dentry *dentry; __be32 nfserr; int ignore_crossmnt = 0; dentry = lookup_one_len_unlocked(name, cd->rd_fhp->fh_dentry, namlen); if (IS_ERR(dentry)) return nfserrno(PTR_ERR(dentry)); if (d_really_is_negative(dentry)) { /* * we're not holding the i_mutex here, so there's * a window where this directory entry could have gone * away. */ dput(dentry); return nfserr_noent; } exp_get(exp); /* * In the case of a mountpoint, the client may be asking for * attributes that are only properties of the underlying filesystem * as opposed to the cross-mounted file system. In such a case, * we will not follow the cross mount and will fill the attribtutes * directly from the mountpoint dentry. */ if (nfsd_mountpoint(dentry, exp)) { int err; if (!(exp->ex_flags & NFSEXP_V4ROOT) && !attributes_need_mount(cd->rd_bmval)) { ignore_crossmnt = 1; goto out_encode; } /* * Why the heck aren't we just using nfsd_lookup?? * Different "."/".." handling? Something else? * At least, add a comment here to explain.... */ err = nfsd_cross_mnt(cd->rd_rqstp, &dentry, &exp); if (err) { nfserr = nfserrno(err); goto out_put; } nfserr = check_nfsd_access(exp, cd->rd_rqstp); if (nfserr) goto out_put; } out_encode: nfserr = nfsd4_encode_fattr(xdr, NULL, exp, dentry, cd->rd_bmval, cd->rd_rqstp, ignore_crossmnt); out_put: dput(dentry); exp_put(exp); return nfserr; } static __be32 * nfsd4_encode_rdattr_error(struct xdr_stream *xdr, __be32 nfserr) { __be32 *p; p = xdr_reserve_space(xdr, 20); if (!p) return NULL; *p++ = htonl(2); *p++ = htonl(FATTR4_WORD0_RDATTR_ERROR); /* bmval0 */ *p++ = htonl(0); /* bmval1 */ *p++ = htonl(4); /* attribute length */ *p++ = nfserr; /* no htonl */ return p; } static int nfsd4_encode_dirent(void *ccdv, const char *name, int namlen, loff_t offset, u64 ino, unsigned int d_type) { struct readdir_cd *ccd = ccdv; struct nfsd4_readdir *cd = container_of(ccd, struct nfsd4_readdir, common); struct xdr_stream *xdr = cd->xdr; int start_offset = xdr->buf->len; int cookie_offset; u32 name_and_cookie; int entry_bytes; __be32 nfserr = nfserr_toosmall; __be64 wire_offset; __be32 *p; /* In nfsv4, "." and ".." never make it onto the wire.. */ if (name && isdotent(name, namlen)) { cd->common.err = nfs_ok; return 0; } if (cd->cookie_offset) { wire_offset = cpu_to_be64(offset); write_bytes_to_xdr_buf(xdr->buf, cd->cookie_offset, &wire_offset, 8); } p = xdr_reserve_space(xdr, 4); if (!p) goto fail; *p++ = xdr_one; /* mark entry present */ cookie_offset = xdr->buf->len; p = xdr_reserve_space(xdr, 3*4 + namlen); if (!p) goto fail; p = xdr_encode_hyper(p, NFS_OFFSET_MAX); /* offset of next entry */ p = xdr_encode_array(p, name, namlen); /* name length & name */ nfserr = nfsd4_encode_dirent_fattr(xdr, cd, name, namlen); switch (nfserr) { case nfs_ok: break; case nfserr_resource: nfserr = nfserr_toosmall; goto fail; case nfserr_noent: xdr_truncate_encode(xdr, start_offset); goto skip_entry; default: /* * If the client requested the RDATTR_ERROR attribute, * we stuff the error code into this attribute * and continue. If this attribute was not requested, * then in accordance with the spec, we fail the * entire READDIR operation(!) */ if (!(cd->rd_bmval[0] & FATTR4_WORD0_RDATTR_ERROR)) goto fail; p = nfsd4_encode_rdattr_error(xdr, nfserr); if (p == NULL) { nfserr = nfserr_toosmall; goto fail; } } nfserr = nfserr_toosmall; entry_bytes = xdr->buf->len - start_offset; if (entry_bytes > cd->rd_maxcount) goto fail; cd->rd_maxcount -= entry_bytes; /* * RFC 3530 14.2.24 describes rd_dircount as only a "hint", so * let's always let through the first entry, at least: */ if (!cd->rd_dircount) goto fail; name_and_cookie = 4 + 4 * XDR_QUADLEN(namlen) + 8; if (name_and_cookie > cd->rd_dircount && cd->cookie_offset) goto fail; cd->rd_dircount -= min(cd->rd_dircount, name_and_cookie); cd->cookie_offset = cookie_offset; skip_entry: cd->common.err = nfs_ok; return 0; fail: xdr_truncate_encode(xdr, start_offset); cd->common.err = nfserr; return -EINVAL; } static __be32 nfsd4_encode_stateid(struct xdr_stream *xdr, stateid_t *sid) { __be32 *p; p = xdr_reserve_space(xdr, sizeof(stateid_t)); if (!p) return nfserr_resource; *p++ = cpu_to_be32(sid->si_generation); p = xdr_encode_opaque_fixed(p, &sid->si_opaque, sizeof(stateid_opaque_t)); return 0; } static __be32 nfsd4_encode_access(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_access *access) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, 8); if (!p) return nfserr_resource; *p++ = cpu_to_be32(access->ac_supported); *p++ = cpu_to_be32(access->ac_resp_access); } return nfserr; } static __be32 nfsd4_encode_bind_conn_to_session(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_bind_conn_to_session *bcts) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, NFS4_MAX_SESSIONID_LEN + 8); if (!p) return nfserr_resource; p = xdr_encode_opaque_fixed(p, bcts->sessionid.data, NFS4_MAX_SESSIONID_LEN); *p++ = cpu_to_be32(bcts->dir); /* Upshifting from TCP to RDMA is not supported */ *p++ = cpu_to_be32(0); } return nfserr; } static __be32 nfsd4_encode_close(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_close *close) { struct xdr_stream *xdr = &resp->xdr; if (!nfserr) nfserr = nfsd4_encode_stateid(xdr, &close->cl_stateid); return nfserr; } static __be32 nfsd4_encode_commit(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_commit *commit) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, NFS4_VERIFIER_SIZE); if (!p) return nfserr_resource; p = xdr_encode_opaque_fixed(p, commit->co_verf.data, NFS4_VERIFIER_SIZE); } return nfserr; } static __be32 nfsd4_encode_create(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_create *create) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, 20); if (!p) return nfserr_resource; encode_cinfo(p, &create->cr_cinfo); nfserr = nfsd4_encode_bitmap(xdr, create->cr_bmval[0], create->cr_bmval[1], create->cr_bmval[2]); } return nfserr; } static __be32 nfsd4_encode_getattr(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_getattr *getattr) { struct svc_fh *fhp = getattr->ga_fhp; struct xdr_stream *xdr = &resp->xdr; if (nfserr) return nfserr; nfserr = nfsd4_encode_fattr(xdr, fhp, fhp->fh_export, fhp->fh_dentry, getattr->ga_bmval, resp->rqstp, 0); return nfserr; } static __be32 nfsd4_encode_getfh(struct nfsd4_compoundres *resp, __be32 nfserr, struct svc_fh **fhpp) { struct xdr_stream *xdr = &resp->xdr; struct svc_fh *fhp = *fhpp; unsigned int len; __be32 *p; if (!nfserr) { len = fhp->fh_handle.fh_size; p = xdr_reserve_space(xdr, len + 4); if (!p) return nfserr_resource; p = xdr_encode_opaque(p, &fhp->fh_handle.fh_base, len); } return nfserr; } /* * Including all fields other than the name, a LOCK4denied structure requires * 8(clientid) + 4(namelen) + 8(offset) + 8(length) + 4(type) = 32 bytes. */ static __be32 nfsd4_encode_lock_denied(struct xdr_stream *xdr, struct nfsd4_lock_denied *ld) { struct xdr_netobj *conf = &ld->ld_owner; __be32 *p; again: p = xdr_reserve_space(xdr, 32 + XDR_LEN(conf->len)); if (!p) { /* * Don't fail to return the result just because we can't * return the conflicting open: */ if (conf->len) { kfree(conf->data); conf->len = 0; conf->data = NULL; goto again; } return nfserr_resource; } p = xdr_encode_hyper(p, ld->ld_start); p = xdr_encode_hyper(p, ld->ld_length); *p++ = cpu_to_be32(ld->ld_type); if (conf->len) { p = xdr_encode_opaque_fixed(p, &ld->ld_clientid, 8); p = xdr_encode_opaque(p, conf->data, conf->len); kfree(conf->data); } else { /* non - nfsv4 lock in conflict, no clientid nor owner */ p = xdr_encode_hyper(p, (u64)0); /* clientid */ *p++ = cpu_to_be32(0); /* length of owner name */ } return nfserr_denied; } static __be32 nfsd4_encode_lock(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_lock *lock) { struct xdr_stream *xdr = &resp->xdr; if (!nfserr) nfserr = nfsd4_encode_stateid(xdr, &lock->lk_resp_stateid); else if (nfserr == nfserr_denied) nfserr = nfsd4_encode_lock_denied(xdr, &lock->lk_denied); return nfserr; } static __be32 nfsd4_encode_lockt(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_lockt *lockt) { struct xdr_stream *xdr = &resp->xdr; if (nfserr == nfserr_denied) nfsd4_encode_lock_denied(xdr, &lockt->lt_denied); return nfserr; } static __be32 nfsd4_encode_locku(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_locku *locku) { struct xdr_stream *xdr = &resp->xdr; if (!nfserr) nfserr = nfsd4_encode_stateid(xdr, &locku->lu_stateid); return nfserr; } static __be32 nfsd4_encode_link(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_link *link) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, 20); if (!p) return nfserr_resource; p = encode_cinfo(p, &link->li_cinfo); } return nfserr; } static __be32 nfsd4_encode_open(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_open *open) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (nfserr) goto out; nfserr = nfsd4_encode_stateid(xdr, &open->op_stateid); if (nfserr) goto out; p = xdr_reserve_space(xdr, 24); if (!p) return nfserr_resource; p = encode_cinfo(p, &open->op_cinfo); *p++ = cpu_to_be32(open->op_rflags); nfserr = nfsd4_encode_bitmap(xdr, open->op_bmval[0], open->op_bmval[1], open->op_bmval[2]); if (nfserr) goto out; p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; *p++ = cpu_to_be32(open->op_delegate_type); switch (open->op_delegate_type) { case NFS4_OPEN_DELEGATE_NONE: break; case NFS4_OPEN_DELEGATE_READ: nfserr = nfsd4_encode_stateid(xdr, &open->op_delegate_stateid); if (nfserr) return nfserr; p = xdr_reserve_space(xdr, 20); if (!p) return nfserr_resource; *p++ = cpu_to_be32(open->op_recall); /* * TODO: ACE's in delegations */ *p++ = cpu_to_be32(NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); /* XXX: is NULL principal ok? */ break; case NFS4_OPEN_DELEGATE_WRITE: nfserr = nfsd4_encode_stateid(xdr, &open->op_delegate_stateid); if (nfserr) return nfserr; p = xdr_reserve_space(xdr, 32); if (!p) return nfserr_resource; *p++ = cpu_to_be32(0); /* * TODO: space_limit's in delegations */ *p++ = cpu_to_be32(NFS4_LIMIT_SIZE); *p++ = cpu_to_be32(~(u32)0); *p++ = cpu_to_be32(~(u32)0); /* * TODO: ACE's in delegations */ *p++ = cpu_to_be32(NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); /* XXX: is NULL principal ok? */ break; case NFS4_OPEN_DELEGATE_NONE_EXT: /* 4.1 */ switch (open->op_why_no_deleg) { case WND4_CONTENTION: case WND4_RESOURCE: p = xdr_reserve_space(xdr, 8); if (!p) return nfserr_resource; *p++ = cpu_to_be32(open->op_why_no_deleg); /* deleg signaling not supported yet: */ *p++ = cpu_to_be32(0); break; default: p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; *p++ = cpu_to_be32(open->op_why_no_deleg); } break; default: BUG(); } /* XXX save filehandle here */ out: return nfserr; } static __be32 nfsd4_encode_open_confirm(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_open_confirm *oc) { struct xdr_stream *xdr = &resp->xdr; if (!nfserr) nfserr = nfsd4_encode_stateid(xdr, &oc->oc_resp_stateid); return nfserr; } static __be32 nfsd4_encode_open_downgrade(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_open_downgrade *od) { struct xdr_stream *xdr = &resp->xdr; if (!nfserr) nfserr = nfsd4_encode_stateid(xdr, &od->od_stateid); return nfserr; } static __be32 nfsd4_encode_splice_read( struct nfsd4_compoundres *resp, struct nfsd4_read *read, struct file *file, unsigned long maxcount) { struct xdr_stream *xdr = &resp->xdr; struct xdr_buf *buf = xdr->buf; u32 eof; long len; int space_left; __be32 nfserr; __be32 *p = xdr->p - 2; /* Make sure there will be room for padding if needed */ if (xdr->end - xdr->p < 1) return nfserr_resource; len = maxcount; nfserr = nfsd_splice_read(read->rd_rqstp, file, read->rd_offset, &maxcount); if (nfserr) { /* * nfsd_splice_actor may have already messed with the * page length; reset it so as not to confuse * xdr_truncate_encode: */ buf->page_len = 0; return nfserr; } eof = nfsd_eof_on_read(len, maxcount, read->rd_offset, d_inode(read->rd_fhp->fh_dentry)->i_size); *(p++) = htonl(eof); *(p++) = htonl(maxcount); buf->page_len = maxcount; buf->len += maxcount; xdr->page_ptr += (buf->page_base + maxcount + PAGE_SIZE - 1) / PAGE_SIZE; /* Use rest of head for padding and remaining ops: */ buf->tail[0].iov_base = xdr->p; buf->tail[0].iov_len = 0; xdr->iov = buf->tail; if (maxcount&3) { int pad = 4 - (maxcount&3); *(xdr->p++) = 0; buf->tail[0].iov_base += maxcount&3; buf->tail[0].iov_len = pad; buf->len += pad; } space_left = min_t(int, (void *)xdr->end - (void *)xdr->p, buf->buflen - buf->len); buf->buflen = buf->len + space_left; xdr->end = (__be32 *)((void *)xdr->end + space_left); return 0; } static __be32 nfsd4_encode_readv(struct nfsd4_compoundres *resp, struct nfsd4_read *read, struct file *file, unsigned long maxcount) { struct xdr_stream *xdr = &resp->xdr; u32 eof; int v; int starting_len = xdr->buf->len - 8; long len; int thislen; __be32 nfserr; __be32 tmp; __be32 *p; u32 zzz = 0; int pad; len = maxcount; v = 0; thislen = min_t(long, len, ((void *)xdr->end - (void *)xdr->p)); p = xdr_reserve_space(xdr, (thislen+3)&~3); WARN_ON_ONCE(!p); resp->rqstp->rq_vec[v].iov_base = p; resp->rqstp->rq_vec[v].iov_len = thislen; v++; len -= thislen; while (len) { thislen = min_t(long, len, PAGE_SIZE); p = xdr_reserve_space(xdr, (thislen+3)&~3); WARN_ON_ONCE(!p); resp->rqstp->rq_vec[v].iov_base = p; resp->rqstp->rq_vec[v].iov_len = thislen; v++; len -= thislen; } read->rd_vlen = v; len = maxcount; nfserr = nfsd_readv(file, read->rd_offset, resp->rqstp->rq_vec, read->rd_vlen, &maxcount); if (nfserr) return nfserr; xdr_truncate_encode(xdr, starting_len + 8 + ((maxcount+3)&~3)); eof = nfsd_eof_on_read(len, maxcount, read->rd_offset, d_inode(read->rd_fhp->fh_dentry)->i_size); tmp = htonl(eof); write_bytes_to_xdr_buf(xdr->buf, starting_len , &tmp, 4); tmp = htonl(maxcount); write_bytes_to_xdr_buf(xdr->buf, starting_len + 4, &tmp, 4); pad = (maxcount&3) ? 4 - (maxcount&3) : 0; write_bytes_to_xdr_buf(xdr->buf, starting_len + 8 + maxcount, &zzz, pad); return 0; } static __be32 nfsd4_encode_read(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_read *read) { unsigned long maxcount; struct xdr_stream *xdr = &resp->xdr; struct file *file = read->rd_filp; int starting_len = xdr->buf->len; struct raparms *ra = NULL; __be32 *p; if (nfserr) goto out; p = xdr_reserve_space(xdr, 8); /* eof flag and byte count */ if (!p) { WARN_ON_ONCE(test_bit(RQ_SPLICE_OK, &resp->rqstp->rq_flags)); nfserr = nfserr_resource; goto out; } if (resp->xdr.buf->page_len && test_bit(RQ_SPLICE_OK, &resp->rqstp->rq_flags)) { WARN_ON_ONCE(1); nfserr = nfserr_resource; goto out; } xdr_commit_encode(xdr); maxcount = svc_max_payload(resp->rqstp); maxcount = min_t(unsigned long, maxcount, (xdr->buf->buflen - xdr->buf->len)); maxcount = min_t(unsigned long, maxcount, read->rd_length); if (read->rd_tmp_file) ra = nfsd_init_raparms(file); if (file->f_op->splice_read && test_bit(RQ_SPLICE_OK, &resp->rqstp->rq_flags)) nfserr = nfsd4_encode_splice_read(resp, read, file, maxcount); else nfserr = nfsd4_encode_readv(resp, read, file, maxcount); if (ra) nfsd_put_raparams(file, ra); if (nfserr) xdr_truncate_encode(xdr, starting_len); out: if (file) fput(file); return nfserr; } static __be32 nfsd4_encode_readlink(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_readlink *readlink) { int maxcount; __be32 wire_count; int zero = 0; struct xdr_stream *xdr = &resp->xdr; int length_offset = xdr->buf->len; __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; maxcount = PAGE_SIZE; p = xdr_reserve_space(xdr, maxcount); if (!p) return nfserr_resource; /* * XXX: By default, vfs_readlink() will truncate symlinks if they * would overflow the buffer. Is this kosher in NFSv4? If not, one * easy fix is: if vfs_readlink() precisely fills the buffer, assume * that truncation occurred, and return NFS4ERR_RESOURCE. */ nfserr = nfsd_readlink(readlink->rl_rqstp, readlink->rl_fhp, (char *)p, &maxcount); if (nfserr == nfserr_isdir) nfserr = nfserr_inval; if (nfserr) { xdr_truncate_encode(xdr, length_offset); return nfserr; } wire_count = htonl(maxcount); write_bytes_to_xdr_buf(xdr->buf, length_offset, &wire_count, 4); xdr_truncate_encode(xdr, length_offset + 4 + ALIGN(maxcount, 4)); if (maxcount & 3) write_bytes_to_xdr_buf(xdr->buf, length_offset + 4 + maxcount, &zero, 4 - (maxcount&3)); return 0; } static __be32 nfsd4_encode_readdir(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_readdir *readdir) { int maxcount; int bytes_left; loff_t offset; __be64 wire_offset; struct xdr_stream *xdr = &resp->xdr; int starting_len = xdr->buf->len; __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(xdr, NFS4_VERIFIER_SIZE); if (!p) return nfserr_resource; /* XXX: Following NFSv3, we ignore the READDIR verifier for now. */ *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); resp->xdr.buf->head[0].iov_len = ((char *)resp->xdr.p) - (char *)resp->xdr.buf->head[0].iov_base; /* * Number of bytes left for directory entries allowing for the * final 8 bytes of the readdir and a following failed op: */ bytes_left = xdr->buf->buflen - xdr->buf->len - COMPOUND_ERR_SLACK_SPACE - 8; if (bytes_left < 0) { nfserr = nfserr_resource; goto err_no_verf; } maxcount = min_t(u32, readdir->rd_maxcount, INT_MAX); /* * Note the rfc defines rd_maxcount as the size of the * READDIR4resok structure, which includes the verifier above * and the 8 bytes encoded at the end of this function: */ if (maxcount < 16) { nfserr = nfserr_toosmall; goto err_no_verf; } maxcount = min_t(int, maxcount-16, bytes_left); /* RFC 3530 14.2.24 allows us to ignore dircount when it's 0: */ if (!readdir->rd_dircount) readdir->rd_dircount = INT_MAX; readdir->xdr = xdr; readdir->rd_maxcount = maxcount; readdir->common.err = 0; readdir->cookie_offset = 0; offset = readdir->rd_cookie; nfserr = nfsd_readdir(readdir->rd_rqstp, readdir->rd_fhp, &offset, &readdir->common, nfsd4_encode_dirent); if (nfserr == nfs_ok && readdir->common.err == nfserr_toosmall && xdr->buf->len == starting_len + 8) { /* nothing encoded; which limit did we hit?: */ if (maxcount - 16 < bytes_left) /* It was the fault of rd_maxcount: */ nfserr = nfserr_toosmall; else /* We ran out of buffer space: */ nfserr = nfserr_resource; } if (nfserr) goto err_no_verf; if (readdir->cookie_offset) { wire_offset = cpu_to_be64(offset); write_bytes_to_xdr_buf(xdr->buf, readdir->cookie_offset, &wire_offset, 8); } p = xdr_reserve_space(xdr, 8); if (!p) { WARN_ON_ONCE(1); goto err_no_verf; } *p++ = 0; /* no more entries */ *p++ = htonl(readdir->common.err == nfserr_eof); return 0; err_no_verf: xdr_truncate_encode(xdr, starting_len); return nfserr; } static __be32 nfsd4_encode_remove(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_remove *remove) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, 20); if (!p) return nfserr_resource; p = encode_cinfo(p, &remove->rm_cinfo); } return nfserr; } static __be32 nfsd4_encode_rename(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_rename *rename) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, 40); if (!p) return nfserr_resource; p = encode_cinfo(p, &rename->rn_sinfo); p = encode_cinfo(p, &rename->rn_tinfo); } return nfserr; } static __be32 nfsd4_do_encode_secinfo(struct xdr_stream *xdr, __be32 nfserr, struct svc_export *exp) { u32 i, nflavs, supported; struct exp_flavor_info *flavs; struct exp_flavor_info def_flavs[2]; __be32 *p, *flavorsp; static bool report = true; if (nfserr) goto out; nfserr = nfserr_resource; if (exp->ex_nflavors) { flavs = exp->ex_flavors; nflavs = exp->ex_nflavors; } else { /* Handling of some defaults in absence of real secinfo: */ flavs = def_flavs; if (exp->ex_client->flavour->flavour == RPC_AUTH_UNIX) { nflavs = 2; flavs[0].pseudoflavor = RPC_AUTH_UNIX; flavs[1].pseudoflavor = RPC_AUTH_NULL; } else if (exp->ex_client->flavour->flavour == RPC_AUTH_GSS) { nflavs = 1; flavs[0].pseudoflavor = svcauth_gss_flavor(exp->ex_client); } else { nflavs = 1; flavs[0].pseudoflavor = exp->ex_client->flavour->flavour; } } supported = 0; p = xdr_reserve_space(xdr, 4); if (!p) goto out; flavorsp = p++; /* to be backfilled later */ for (i = 0; i < nflavs; i++) { rpc_authflavor_t pf = flavs[i].pseudoflavor; struct rpcsec_gss_info info; if (rpcauth_get_gssinfo(pf, &info) == 0) { supported++; p = xdr_reserve_space(xdr, 4 + 4 + XDR_LEN(info.oid.len) + 4 + 4); if (!p) goto out; *p++ = cpu_to_be32(RPC_AUTH_GSS); p = xdr_encode_opaque(p, info.oid.data, info.oid.len); *p++ = cpu_to_be32(info.qop); *p++ = cpu_to_be32(info.service); } else if (pf < RPC_AUTH_MAXFLAVOR) { supported++; p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = cpu_to_be32(pf); } else { if (report) pr_warn("NFS: SECINFO: security flavor %u " "is not supported\n", pf); } } if (nflavs != supported) report = false; *flavorsp = htonl(supported); nfserr = 0; out: if (exp) exp_put(exp); return nfserr; } static __be32 nfsd4_encode_secinfo(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_secinfo *secinfo) { struct xdr_stream *xdr = &resp->xdr; return nfsd4_do_encode_secinfo(xdr, nfserr, secinfo->si_exp); } static __be32 nfsd4_encode_secinfo_no_name(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_secinfo_no_name *secinfo) { struct xdr_stream *xdr = &resp->xdr; return nfsd4_do_encode_secinfo(xdr, nfserr, secinfo->sin_exp); } /* * The SETATTR encode routine is special -- it always encodes a bitmap, * regardless of the error status. */ static __be32 nfsd4_encode_setattr(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_setattr *setattr) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; p = xdr_reserve_space(xdr, 16); if (!p) return nfserr_resource; if (nfserr) { *p++ = cpu_to_be32(3); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); } else { *p++ = cpu_to_be32(3); *p++ = cpu_to_be32(setattr->sa_bmval[0]); *p++ = cpu_to_be32(setattr->sa_bmval[1]); *p++ = cpu_to_be32(setattr->sa_bmval[2]); } return nfserr; } static __be32 nfsd4_encode_setclientid(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_setclientid *scd) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, 8 + NFS4_VERIFIER_SIZE); if (!p) return nfserr_resource; p = xdr_encode_opaque_fixed(p, &scd->se_clientid, 8); p = xdr_encode_opaque_fixed(p, &scd->se_confirm, NFS4_VERIFIER_SIZE); } else if (nfserr == nfserr_clid_inuse) { p = xdr_reserve_space(xdr, 8); if (!p) return nfserr_resource; *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(0); } return nfserr; } static __be32 nfsd4_encode_write(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_write *write) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, 16); if (!p) return nfserr_resource; *p++ = cpu_to_be32(write->wr_bytes_written); *p++ = cpu_to_be32(write->wr_how_written); p = xdr_encode_opaque_fixed(p, write->wr_verifier.data, NFS4_VERIFIER_SIZE); } return nfserr; } static __be32 nfsd4_encode_exchange_id(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_exchange_id *exid) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; char *major_id; char *server_scope; int major_id_sz; int server_scope_sz; int status = 0; uint64_t minor_id = 0; if (nfserr) return nfserr; major_id = utsname()->nodename; major_id_sz = strlen(major_id); server_scope = utsname()->nodename; server_scope_sz = strlen(server_scope); p = xdr_reserve_space(xdr, 8 /* eir_clientid */ + 4 /* eir_sequenceid */ + 4 /* eir_flags */ + 4 /* spr_how */); if (!p) return nfserr_resource; p = xdr_encode_opaque_fixed(p, &exid->clientid, 8); *p++ = cpu_to_be32(exid->seqid); *p++ = cpu_to_be32(exid->flags); *p++ = cpu_to_be32(exid->spa_how); switch (exid->spa_how) { case SP4_NONE: break; case SP4_MACH_CRED: /* spo_must_enforce bitmap: */ status = nfsd4_encode_bitmap(xdr, exid->spo_must_enforce[0], exid->spo_must_enforce[1], exid->spo_must_enforce[2]); if (status) goto out; /* spo_must_allow bitmap: */ status = nfsd4_encode_bitmap(xdr, exid->spo_must_allow[0], exid->spo_must_allow[1], exid->spo_must_allow[2]); if (status) goto out; break; default: WARN_ON_ONCE(1); } p = xdr_reserve_space(xdr, 8 /* so_minor_id */ + 4 /* so_major_id.len */ + (XDR_QUADLEN(major_id_sz) * 4) + 4 /* eir_server_scope.len */ + (XDR_QUADLEN(server_scope_sz) * 4) + 4 /* eir_server_impl_id.count (0) */); if (!p) return nfserr_resource; /* The server_owner struct */ p = xdr_encode_hyper(p, minor_id); /* Minor id */ /* major id */ p = xdr_encode_opaque(p, major_id, major_id_sz); /* Server scope */ p = xdr_encode_opaque(p, server_scope, server_scope_sz); /* Implementation id */ *p++ = cpu_to_be32(0); /* zero length nfs_impl_id4 array */ return 0; out: return status; } static __be32 nfsd4_encode_create_session(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_create_session *sess) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(xdr, 24); if (!p) return nfserr_resource; p = xdr_encode_opaque_fixed(p, sess->sessionid.data, NFS4_MAX_SESSIONID_LEN); *p++ = cpu_to_be32(sess->seqid); *p++ = cpu_to_be32(sess->flags); p = xdr_reserve_space(xdr, 28); if (!p) return nfserr_resource; *p++ = cpu_to_be32(0); /* headerpadsz */ *p++ = cpu_to_be32(sess->fore_channel.maxreq_sz); *p++ = cpu_to_be32(sess->fore_channel.maxresp_sz); *p++ = cpu_to_be32(sess->fore_channel.maxresp_cached); *p++ = cpu_to_be32(sess->fore_channel.maxops); *p++ = cpu_to_be32(sess->fore_channel.maxreqs); *p++ = cpu_to_be32(sess->fore_channel.nr_rdma_attrs); if (sess->fore_channel.nr_rdma_attrs) { p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; *p++ = cpu_to_be32(sess->fore_channel.rdma_attrs); } p = xdr_reserve_space(xdr, 28); if (!p) return nfserr_resource; *p++ = cpu_to_be32(0); /* headerpadsz */ *p++ = cpu_to_be32(sess->back_channel.maxreq_sz); *p++ = cpu_to_be32(sess->back_channel.maxresp_sz); *p++ = cpu_to_be32(sess->back_channel.maxresp_cached); *p++ = cpu_to_be32(sess->back_channel.maxops); *p++ = cpu_to_be32(sess->back_channel.maxreqs); *p++ = cpu_to_be32(sess->back_channel.nr_rdma_attrs); if (sess->back_channel.nr_rdma_attrs) { p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; *p++ = cpu_to_be32(sess->back_channel.rdma_attrs); } return 0; } static __be32 nfsd4_encode_sequence(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_sequence *seq) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(xdr, NFS4_MAX_SESSIONID_LEN + 20); if (!p) return nfserr_resource; p = xdr_encode_opaque_fixed(p, seq->sessionid.data, NFS4_MAX_SESSIONID_LEN); *p++ = cpu_to_be32(seq->seqid); *p++ = cpu_to_be32(seq->slotid); /* Note slotid's are numbered from zero: */ *p++ = cpu_to_be32(seq->maxslots - 1); /* sr_highest_slotid */ *p++ = cpu_to_be32(seq->maxslots - 1); /* sr_target_highest_slotid */ *p++ = cpu_to_be32(seq->status_flags); resp->cstate.data_offset = xdr->buf->len; /* DRC cache data pointer */ return 0; } static __be32 nfsd4_encode_test_stateid(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_test_stateid *test_stateid) { struct xdr_stream *xdr = &resp->xdr; struct nfsd4_test_stateid_id *stateid, *next; __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(xdr, 4 + (4 * test_stateid->ts_num_ids)); if (!p) return nfserr_resource; *p++ = htonl(test_stateid->ts_num_ids); list_for_each_entry_safe(stateid, next, &test_stateid->ts_stateid_list, ts_id_list) { *p++ = stateid->ts_id_status; } return nfserr; } #ifdef CONFIG_NFSD_PNFS static __be32 nfsd4_encode_getdeviceinfo(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_getdeviceinfo *gdev) { struct xdr_stream *xdr = &resp->xdr; const struct nfsd4_layout_ops *ops; u32 starting_len = xdr->buf->len, needed_len; __be32 *p; dprintk("%s: err %d\n", __func__, be32_to_cpu(nfserr)); if (nfserr) goto out; nfserr = nfserr_resource; p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = cpu_to_be32(gdev->gd_layout_type); /* If maxcount is 0 then just update notifications */ if (gdev->gd_maxcount != 0) { ops = nfsd4_layout_ops[gdev->gd_layout_type]; nfserr = ops->encode_getdeviceinfo(xdr, gdev); if (nfserr) { /* * We don't bother to burden the layout drivers with * enforcing gd_maxcount, just tell the client to * come back with a bigger buffer if it's not enough. */ if (xdr->buf->len + 4 > gdev->gd_maxcount) goto toosmall; goto out; } } nfserr = nfserr_resource; if (gdev->gd_notify_types) { p = xdr_reserve_space(xdr, 4 + 4); if (!p) goto out; *p++ = cpu_to_be32(1); /* bitmap length */ *p++ = cpu_to_be32(gdev->gd_notify_types); } else { p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = 0; } nfserr = 0; out: kfree(gdev->gd_device); dprintk("%s: done: %d\n", __func__, be32_to_cpu(nfserr)); return nfserr; toosmall: dprintk("%s: maxcount too small\n", __func__); needed_len = xdr->buf->len + 4 /* notifications */; xdr_truncate_encode(xdr, starting_len); p = xdr_reserve_space(xdr, 4); if (!p) { nfserr = nfserr_resource; } else { *p++ = cpu_to_be32(needed_len); nfserr = nfserr_toosmall; } goto out; } static __be32 nfsd4_encode_layoutget(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_layoutget *lgp) { struct xdr_stream *xdr = &resp->xdr; const struct nfsd4_layout_ops *ops; __be32 *p; dprintk("%s: err %d\n", __func__, nfserr); if (nfserr) goto out; nfserr = nfserr_resource; p = xdr_reserve_space(xdr, 36 + sizeof(stateid_opaque_t)); if (!p) goto out; *p++ = cpu_to_be32(1); /* we always set return-on-close */ *p++ = cpu_to_be32(lgp->lg_sid.si_generation); p = xdr_encode_opaque_fixed(p, &lgp->lg_sid.si_opaque, sizeof(stateid_opaque_t)); *p++ = cpu_to_be32(1); /* we always return a single layout */ p = xdr_encode_hyper(p, lgp->lg_seg.offset); p = xdr_encode_hyper(p, lgp->lg_seg.length); *p++ = cpu_to_be32(lgp->lg_seg.iomode); *p++ = cpu_to_be32(lgp->lg_layout_type); ops = nfsd4_layout_ops[lgp->lg_layout_type]; nfserr = ops->encode_layoutget(xdr, lgp); out: kfree(lgp->lg_content); return nfserr; } static __be32 nfsd4_encode_layoutcommit(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_layoutcommit *lcp) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; *p++ = cpu_to_be32(lcp->lc_size_chg); if (lcp->lc_size_chg) { p = xdr_reserve_space(xdr, 8); if (!p) return nfserr_resource; p = xdr_encode_hyper(p, lcp->lc_newsize); } return nfs_ok; } static __be32 nfsd4_encode_layoutreturn(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_layoutreturn *lrp) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(xdr, 4); if (!p) return nfserr_resource; *p++ = cpu_to_be32(lrp->lrs_present); if (lrp->lrs_present) return nfsd4_encode_stateid(xdr, &lrp->lr_sid); return nfs_ok; } #endif /* CONFIG_NFSD_PNFS */ static __be32 nfsd42_encode_write_res(struct nfsd4_compoundres *resp, struct nfsd42_write_res *write) { __be32 *p; p = xdr_reserve_space(&resp->xdr, 4 + 8 + 4 + NFS4_VERIFIER_SIZE); if (!p) return nfserr_resource; *p++ = cpu_to_be32(0); p = xdr_encode_hyper(p, write->wr_bytes_written); *p++ = cpu_to_be32(write->wr_stable_how); p = xdr_encode_opaque_fixed(p, write->wr_verifier.data, NFS4_VERIFIER_SIZE); return nfs_ok; } static __be32 nfsd4_encode_copy(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_copy *copy) { __be32 *p; if (!nfserr) { nfserr = nfsd42_encode_write_res(resp, &copy->cp_res); if (nfserr) return nfserr; p = xdr_reserve_space(&resp->xdr, 4 + 4); *p++ = cpu_to_be32(copy->cp_consecutive); *p++ = cpu_to_be32(copy->cp_synchronous); } return nfserr; } static __be32 nfsd4_encode_seek(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_seek *seek) { __be32 *p; if (nfserr) return nfserr; p = xdr_reserve_space(&resp->xdr, 4 + 8); *p++ = cpu_to_be32(seek->seek_eof); p = xdr_encode_hyper(p, seek->seek_pos); return nfserr; } static __be32 nfsd4_encode_noop(struct nfsd4_compoundres *resp, __be32 nfserr, void *p) { return nfserr; } typedef __be32(* nfsd4_enc)(struct nfsd4_compoundres *, __be32, void *); /* * Note: nfsd4_enc_ops vector is shared for v4.0 and v4.1 * since we don't need to filter out obsolete ops as this is * done in the decoding phase. */ static nfsd4_enc nfsd4_enc_ops[] = { [OP_ACCESS] = (nfsd4_enc)nfsd4_encode_access, [OP_CLOSE] = (nfsd4_enc)nfsd4_encode_close, [OP_COMMIT] = (nfsd4_enc)nfsd4_encode_commit, [OP_CREATE] = (nfsd4_enc)nfsd4_encode_create, [OP_DELEGPURGE] = (nfsd4_enc)nfsd4_encode_noop, [OP_DELEGRETURN] = (nfsd4_enc)nfsd4_encode_noop, [OP_GETATTR] = (nfsd4_enc)nfsd4_encode_getattr, [OP_GETFH] = (nfsd4_enc)nfsd4_encode_getfh, [OP_LINK] = (nfsd4_enc)nfsd4_encode_link, [OP_LOCK] = (nfsd4_enc)nfsd4_encode_lock, [OP_LOCKT] = (nfsd4_enc)nfsd4_encode_lockt, [OP_LOCKU] = (nfsd4_enc)nfsd4_encode_locku, [OP_LOOKUP] = (nfsd4_enc)nfsd4_encode_noop, [OP_LOOKUPP] = (nfsd4_enc)nfsd4_encode_noop, [OP_NVERIFY] = (nfsd4_enc)nfsd4_encode_noop, [OP_OPEN] = (nfsd4_enc)nfsd4_encode_open, [OP_OPENATTR] = (nfsd4_enc)nfsd4_encode_noop, [OP_OPEN_CONFIRM] = (nfsd4_enc)nfsd4_encode_open_confirm, [OP_OPEN_DOWNGRADE] = (nfsd4_enc)nfsd4_encode_open_downgrade, [OP_PUTFH] = (nfsd4_enc)nfsd4_encode_noop, [OP_PUTPUBFH] = (nfsd4_enc)nfsd4_encode_noop, [OP_PUTROOTFH] = (nfsd4_enc)nfsd4_encode_noop, [OP_READ] = (nfsd4_enc)nfsd4_encode_read, [OP_READDIR] = (nfsd4_enc)nfsd4_encode_readdir, [OP_READLINK] = (nfsd4_enc)nfsd4_encode_readlink, [OP_REMOVE] = (nfsd4_enc)nfsd4_encode_remove, [OP_RENAME] = (nfsd4_enc)nfsd4_encode_rename, [OP_RENEW] = (nfsd4_enc)nfsd4_encode_noop, [OP_RESTOREFH] = (nfsd4_enc)nfsd4_encode_noop, [OP_SAVEFH] = (nfsd4_enc)nfsd4_encode_noop, [OP_SECINFO] = (nfsd4_enc)nfsd4_encode_secinfo, [OP_SETATTR] = (nfsd4_enc)nfsd4_encode_setattr, [OP_SETCLIENTID] = (nfsd4_enc)nfsd4_encode_setclientid, [OP_SETCLIENTID_CONFIRM] = (nfsd4_enc)nfsd4_encode_noop, [OP_VERIFY] = (nfsd4_enc)nfsd4_encode_noop, [OP_WRITE] = (nfsd4_enc)nfsd4_encode_write, [OP_RELEASE_LOCKOWNER] = (nfsd4_enc)nfsd4_encode_noop, /* NFSv4.1 operations */ [OP_BACKCHANNEL_CTL] = (nfsd4_enc)nfsd4_encode_noop, [OP_BIND_CONN_TO_SESSION] = (nfsd4_enc)nfsd4_encode_bind_conn_to_session, [OP_EXCHANGE_ID] = (nfsd4_enc)nfsd4_encode_exchange_id, [OP_CREATE_SESSION] = (nfsd4_enc)nfsd4_encode_create_session, [OP_DESTROY_SESSION] = (nfsd4_enc)nfsd4_encode_noop, [OP_FREE_STATEID] = (nfsd4_enc)nfsd4_encode_noop, [OP_GET_DIR_DELEGATION] = (nfsd4_enc)nfsd4_encode_noop, #ifdef CONFIG_NFSD_PNFS [OP_GETDEVICEINFO] = (nfsd4_enc)nfsd4_encode_getdeviceinfo, [OP_GETDEVICELIST] = (nfsd4_enc)nfsd4_encode_noop, [OP_LAYOUTCOMMIT] = (nfsd4_enc)nfsd4_encode_layoutcommit, [OP_LAYOUTGET] = (nfsd4_enc)nfsd4_encode_layoutget, [OP_LAYOUTRETURN] = (nfsd4_enc)nfsd4_encode_layoutreturn, #else [OP_GETDEVICEINFO] = (nfsd4_enc)nfsd4_encode_noop, [OP_GETDEVICELIST] = (nfsd4_enc)nfsd4_encode_noop, [OP_LAYOUTCOMMIT] = (nfsd4_enc)nfsd4_encode_noop, [OP_LAYOUTGET] = (nfsd4_enc)nfsd4_encode_noop, [OP_LAYOUTRETURN] = (nfsd4_enc)nfsd4_encode_noop, #endif [OP_SECINFO_NO_NAME] = (nfsd4_enc)nfsd4_encode_secinfo_no_name, [OP_SEQUENCE] = (nfsd4_enc)nfsd4_encode_sequence, [OP_SET_SSV] = (nfsd4_enc)nfsd4_encode_noop, [OP_TEST_STATEID] = (nfsd4_enc)nfsd4_encode_test_stateid, [OP_WANT_DELEGATION] = (nfsd4_enc)nfsd4_encode_noop, [OP_DESTROY_CLIENTID] = (nfsd4_enc)nfsd4_encode_noop, [OP_RECLAIM_COMPLETE] = (nfsd4_enc)nfsd4_encode_noop, /* NFSv4.2 operations */ [OP_ALLOCATE] = (nfsd4_enc)nfsd4_encode_noop, [OP_COPY] = (nfsd4_enc)nfsd4_encode_copy, [OP_COPY_NOTIFY] = (nfsd4_enc)nfsd4_encode_noop, [OP_DEALLOCATE] = (nfsd4_enc)nfsd4_encode_noop, [OP_IO_ADVISE] = (nfsd4_enc)nfsd4_encode_noop, [OP_LAYOUTERROR] = (nfsd4_enc)nfsd4_encode_noop, [OP_LAYOUTSTATS] = (nfsd4_enc)nfsd4_encode_noop, [OP_OFFLOAD_CANCEL] = (nfsd4_enc)nfsd4_encode_noop, [OP_OFFLOAD_STATUS] = (nfsd4_enc)nfsd4_encode_noop, [OP_READ_PLUS] = (nfsd4_enc)nfsd4_encode_noop, [OP_SEEK] = (nfsd4_enc)nfsd4_encode_seek, [OP_WRITE_SAME] = (nfsd4_enc)nfsd4_encode_noop, [OP_CLONE] = (nfsd4_enc)nfsd4_encode_noop, }; /* * Calculate whether we still have space to encode repsize bytes. * There are two considerations: * - For NFS versions >=4.1, the size of the reply must stay within * session limits * - For all NFS versions, we must stay within limited preallocated * buffer space. * * This is called before the operation is processed, so can only provide * an upper estimate. For some nonidempotent operations (such as * getattr), it's not necessarily a problem if that estimate is wrong, * as we can fail it after processing without significant side effects. */ __be32 nfsd4_check_resp_size(struct nfsd4_compoundres *resp, u32 respsize) { struct xdr_buf *buf = &resp->rqstp->rq_res; struct nfsd4_slot *slot = resp->cstate.slot; if (buf->len + respsize <= buf->buflen) return nfs_ok; if (!nfsd4_has_session(&resp->cstate)) return nfserr_resource; if (slot->sl_flags & NFSD4_SLOT_CACHETHIS) { WARN_ON_ONCE(1); return nfserr_rep_too_big_to_cache; } return nfserr_rep_too_big; } void nfsd4_encode_operation(struct nfsd4_compoundres *resp, struct nfsd4_op *op) { struct xdr_stream *xdr = &resp->xdr; struct nfs4_stateowner *so = resp->cstate.replay_owner; struct svc_rqst *rqstp = resp->rqstp; int post_err_offset; nfsd4_enc encoder; __be32 *p; p = xdr_reserve_space(xdr, 8); if (!p) { WARN_ON_ONCE(1); return; } *p++ = cpu_to_be32(op->opnum); post_err_offset = xdr->buf->len; if (op->opnum == OP_ILLEGAL) goto status; BUG_ON(op->opnum < 0 || op->opnum >= ARRAY_SIZE(nfsd4_enc_ops) || !nfsd4_enc_ops[op->opnum]); encoder = nfsd4_enc_ops[op->opnum]; op->status = encoder(resp, op->status, &op->u); xdr_commit_encode(xdr); /* nfsd4_check_resp_size guarantees enough room for error status */ if (!op->status) { int space_needed = 0; if (!nfsd4_last_compound_op(rqstp)) space_needed = COMPOUND_ERR_SLACK_SPACE; op->status = nfsd4_check_resp_size(resp, space_needed); } if (op->status == nfserr_resource && nfsd4_has_session(&resp->cstate)) { struct nfsd4_slot *slot = resp->cstate.slot; if (slot->sl_flags & NFSD4_SLOT_CACHETHIS) op->status = nfserr_rep_too_big_to_cache; else op->status = nfserr_rep_too_big; } if (op->status == nfserr_resource || op->status == nfserr_rep_too_big || op->status == nfserr_rep_too_big_to_cache) { /* * The operation may have already been encoded or * partially encoded. No op returns anything additional * in the case of one of these three errors, so we can * just truncate back to after the status. But it's a * bug if we had to do this on a non-idempotent op: */ warn_on_nonidempotent_op(op); xdr_truncate_encode(xdr, post_err_offset); } if (so) { int len = xdr->buf->len - post_err_offset; so->so_replay.rp_status = op->status; so->so_replay.rp_buflen = len; read_bytes_from_xdr_buf(xdr->buf, post_err_offset, so->so_replay.rp_buf, len); } status: /* Note that op->status is already in network byte order: */ write_bytes_to_xdr_buf(xdr->buf, post_err_offset - 4, &op->status, 4); } /* * Encode the reply stored in the stateowner reply cache * * XDR note: do not encode rp->rp_buflen: the buffer contains the * previously sent already encoded operation. */ void nfsd4_encode_replay(struct xdr_stream *xdr, struct nfsd4_op *op) { __be32 *p; struct nfs4_replay *rp = op->replay; BUG_ON(!rp); p = xdr_reserve_space(xdr, 8 + rp->rp_buflen); if (!p) { WARN_ON_ONCE(1); return; } *p++ = cpu_to_be32(op->opnum); *p++ = rp->rp_status; /* already xdr'ed */ p = xdr_encode_opaque_fixed(p, rp->rp_buf, rp->rp_buflen); } int nfs4svc_encode_voidres(struct svc_rqst *rqstp, __be32 *p, void *dummy) { return xdr_ressize_check(rqstp, p); } int nfsd4_release_compoundargs(void *rq, __be32 *p, void *resp) { struct svc_rqst *rqstp = rq; struct nfsd4_compoundargs *args = rqstp->rq_argp; if (args->ops != args->iops) { kfree(args->ops); args->ops = args->iops; } kfree(args->tmpp); args->tmpp = NULL; while (args->to_free) { struct svcxdr_tmpbuf *tb = args->to_free; args->to_free = tb->next; kfree(tb); } return 1; } int nfs4svc_decode_compoundargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd4_compoundargs *args) { if (rqstp->rq_arg.head[0].iov_len % 4) { /* client is nuts */ dprintk("%s: compound not properly padded! (peeraddr=%pISc xid=0x%x)", __func__, svc_addr(rqstp), be32_to_cpu(rqstp->rq_xid)); return 0; } args->p = p; args->end = rqstp->rq_arg.head[0].iov_base + rqstp->rq_arg.head[0].iov_len; args->pagelist = rqstp->rq_arg.pages; args->pagelen = rqstp->rq_arg.page_len; args->tmpp = NULL; args->to_free = NULL; args->ops = args->iops; args->rqstp = rqstp; return !nfsd4_decode_compound(args); } int nfs4svc_encode_compoundres(struct svc_rqst *rqstp, __be32 *p, struct nfsd4_compoundres *resp) { /* * All that remains is to write the tag and operation count... */ struct xdr_buf *buf = resp->xdr.buf; WARN_ON_ONCE(buf->len != buf->head[0].iov_len + buf->page_len + buf->tail[0].iov_len); rqstp->rq_next_page = resp->xdr.page_ptr + 1; p = resp->tagp; *p++ = htonl(resp->taglen); memcpy(p, resp->tag, resp->taglen); p += XDR_QUADLEN(resp->taglen); *p++ = htonl(resp->opcnt); nfsd4_sequence_done(resp); return 1; } /* * Local variables: * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-129/c/good_3336_0
crossvul-cpp_data_good_1182_0
/* * Westwood Studios VQA Video Decoder * Copyright (C) 2003 The FFmpeg project * * 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 */ /** * @file * VQA Video Decoder * @author Mike Melanson (melanson@pcisys.net) * @see http://wiki.multimedia.cx/index.php?title=VQA * * The VQA video decoder outputs PAL8 or RGB555 colorspace data, depending * on the type of data in the file. * * This decoder needs the 42-byte VQHD header from the beginning * of the VQA file passed through the extradata field. The VQHD header * is laid out as: * * bytes 0-3 chunk fourcc: 'VQHD' * bytes 4-7 chunk size in big-endian format, should be 0x0000002A * bytes 8-49 VQHD chunk data * * Bytes 8-49 are what this decoder expects to see. * * Briefly, VQA is a vector quantized animation format that operates in a * VGA palettized colorspace. It operates on pixel vectors (blocks) * of either 4x2 or 4x4 in size. Compressed VQA chunks can contain vector * codebooks, palette information, and code maps for rendering vectors onto * frames. Any of these components can also be compressed with a run-length * encoding (RLE) algorithm commonly referred to as "format80". * * VQA takes a novel approach to rate control. Each group of n frames * (usually, n = 8) relies on a different vector codebook. Rather than * transporting an entire codebook every 8th frame, the new codebook is * broken up into 8 pieces and sent along with the compressed video chunks * for each of the 8 frames preceding the 8 frames which require the * codebook. A full codebook is also sent on the very first frame of a * file. This is an interesting technique, although it makes random file * seeking difficult despite the fact that the frames are all intracoded. * * V1,2 VQA uses 12-bit codebook indexes. If the 12-bit indexes were * packed into bytes and then RLE compressed, bytewise, the results would * be poor. That is why the coding method divides each index into 2 parts, * the top 4 bits and the bottom 8 bits, then RL encodes the 4-bit pieces * together and the 8-bit pieces together. If most of the vectors are * clustered into one group of 256 vectors, most of the 4-bit index pieces * should be the same. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "libavutil/intreadwrite.h" #include "libavutil/imgutils.h" #include "avcodec.h" #include "bytestream.h" #include "internal.h" #define PALETTE_COUNT 256 #define VQA_HEADER_SIZE 0x2A /* allocate the maximum vector space, regardless of the file version: * (0xFF00 codebook vectors + 0x100 solid pixel vectors) * (4x4 pixels/block) */ #define MAX_CODEBOOK_VECTORS 0xFF00 #define SOLID_PIXEL_VECTORS 0x100 #define MAX_VECTORS (MAX_CODEBOOK_VECTORS + SOLID_PIXEL_VECTORS) #define MAX_CODEBOOK_SIZE (MAX_VECTORS * 4 * 4) #define CBF0_TAG MKBETAG('C', 'B', 'F', '0') #define CBFZ_TAG MKBETAG('C', 'B', 'F', 'Z') #define CBP0_TAG MKBETAG('C', 'B', 'P', '0') #define CBPZ_TAG MKBETAG('C', 'B', 'P', 'Z') #define CPL0_TAG MKBETAG('C', 'P', 'L', '0') #define CPLZ_TAG MKBETAG('C', 'P', 'L', 'Z') #define VPTZ_TAG MKBETAG('V', 'P', 'T', 'Z') typedef struct VqaContext { AVCodecContext *avctx; GetByteContext gb; uint32_t palette[PALETTE_COUNT]; int width; /* width of a frame */ int height; /* height of a frame */ int vector_width; /* width of individual vector */ int vector_height; /* height of individual vector */ int vqa_version; /* this should be either 1, 2 or 3 */ unsigned char *codebook; /* the current codebook */ int codebook_size; unsigned char *next_codebook_buffer; /* accumulator for next codebook */ int next_codebook_buffer_index; unsigned char *decode_buffer; int decode_buffer_size; /* number of frames to go before replacing codebook */ int partial_countdown; int partial_count; } VqaContext; static av_cold int vqa_decode_init(AVCodecContext *avctx) { VqaContext *s = avctx->priv_data; int i, j, codebook_index, ret; s->avctx = avctx; avctx->pix_fmt = AV_PIX_FMT_PAL8; /* make sure the extradata made it */ if (s->avctx->extradata_size != VQA_HEADER_SIZE) { av_log(s->avctx, AV_LOG_ERROR, "expected extradata size of %d\n", VQA_HEADER_SIZE); return AVERROR(EINVAL); } /* load up the VQA parameters from the header */ s->vqa_version = s->avctx->extradata[0]; switch (s->vqa_version) { case 1: case 2: break; case 3: avpriv_report_missing_feature(avctx, "VQA Version %d", s->vqa_version); return AVERROR_PATCHWELCOME; default: avpriv_request_sample(avctx, "VQA Version %i", s->vqa_version); return AVERROR_PATCHWELCOME; } s->width = AV_RL16(&s->avctx->extradata[6]); s->height = AV_RL16(&s->avctx->extradata[8]); if ((ret = ff_set_dimensions(avctx, s->width, s->height)) < 0) { s->width= s->height= 0; return ret; } s->vector_width = s->avctx->extradata[10]; s->vector_height = s->avctx->extradata[11]; s->partial_count = s->partial_countdown = s->avctx->extradata[13]; /* the vector dimensions have to meet very stringent requirements */ if ((s->vector_width != 4) || ((s->vector_height != 2) && (s->vector_height != 4))) { /* return without further initialization */ return AVERROR_INVALIDDATA; } if (s->width % s->vector_width || s->height % s->vector_height) { av_log(avctx, AV_LOG_ERROR, "Image size not multiple of block size\n"); return AVERROR_INVALIDDATA; } /* allocate codebooks */ s->codebook_size = MAX_CODEBOOK_SIZE; s->codebook = av_malloc(s->codebook_size); if (!s->codebook) goto fail; s->next_codebook_buffer = av_malloc(s->codebook_size); if (!s->next_codebook_buffer) goto fail; /* allocate decode buffer */ s->decode_buffer_size = (s->width / s->vector_width) * (s->height / s->vector_height) * 2; s->decode_buffer = av_mallocz(s->decode_buffer_size); if (!s->decode_buffer) goto fail; /* initialize the solid-color vectors */ if (s->vector_height == 4) { codebook_index = 0xFF00 * 16; for (i = 0; i < 256; i++) for (j = 0; j < 16; j++) s->codebook[codebook_index++] = i; } else { codebook_index = 0xF00 * 8; for (i = 0; i < 256; i++) for (j = 0; j < 8; j++) s->codebook[codebook_index++] = i; } s->next_codebook_buffer_index = 0; return 0; fail: av_freep(&s->codebook); av_freep(&s->next_codebook_buffer); av_freep(&s->decode_buffer); return AVERROR(ENOMEM); } #define CHECK_COUNT() \ if (dest_index + count > dest_size) { \ av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: next op would overflow dest_index\n"); \ av_log(s->avctx, AV_LOG_ERROR, "current dest_index = %d, count = %d, dest_size = %d\n", \ dest_index, count, dest_size); \ return AVERROR_INVALIDDATA; \ } #define CHECK_COPY(idx) \ if (idx < 0 || idx + count > dest_size) { \ av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: next op would overflow dest_index\n"); \ av_log(s->avctx, AV_LOG_ERROR, "current src_pos = %d, count = %d, dest_size = %d\n", \ src_pos, count, dest_size); \ return AVERROR_INVALIDDATA; \ } static int decode_format80(VqaContext *s, int src_size, unsigned char *dest, int dest_size, int check_size) { int dest_index = 0; int count, opcode, start; int src_pos; unsigned char color; int i; if (src_size < 0 || src_size > bytestream2_get_bytes_left(&s->gb)) { av_log(s->avctx, AV_LOG_ERROR, "Chunk size %d is out of range\n", src_size); return AVERROR_INVALIDDATA; } start = bytestream2_tell(&s->gb); while (bytestream2_tell(&s->gb) - start < src_size) { opcode = bytestream2_get_byte(&s->gb); ff_tlog(s->avctx, "opcode %02X: ", opcode); /* 0x80 means that frame is finished */ if (opcode == 0x80) break; if (dest_index >= dest_size) { av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: dest_index (%d) exceeded dest_size (%d)\n", dest_index, dest_size); return AVERROR_INVALIDDATA; } if (opcode == 0xFF) { count = bytestream2_get_le16(&s->gb); src_pos = bytestream2_get_le16(&s->gb); ff_tlog(s->avctx, "(1) copy %X bytes from absolute pos %X\n", count, src_pos); CHECK_COUNT(); CHECK_COPY(src_pos); for (i = 0; i < count; i++) dest[dest_index + i] = dest[src_pos + i]; dest_index += count; } else if (opcode == 0xFE) { count = bytestream2_get_le16(&s->gb); color = bytestream2_get_byte(&s->gb); ff_tlog(s->avctx, "(2) set %X bytes to %02X\n", count, color); CHECK_COUNT(); memset(&dest[dest_index], color, count); dest_index += count; } else if ((opcode & 0xC0) == 0xC0) { count = (opcode & 0x3F) + 3; src_pos = bytestream2_get_le16(&s->gb); ff_tlog(s->avctx, "(3) copy %X bytes from absolute pos %X\n", count, src_pos); CHECK_COUNT(); CHECK_COPY(src_pos); for (i = 0; i < count; i++) dest[dest_index + i] = dest[src_pos + i]; dest_index += count; } else if (opcode > 0x80) { count = opcode & 0x3F; ff_tlog(s->avctx, "(4) copy %X bytes from source to dest\n", count); CHECK_COUNT(); bytestream2_get_buffer(&s->gb, &dest[dest_index], count); dest_index += count; } else { count = ((opcode & 0x70) >> 4) + 3; src_pos = bytestream2_get_byte(&s->gb) | ((opcode & 0x0F) << 8); ff_tlog(s->avctx, "(5) copy %X bytes from relpos %X\n", count, src_pos); CHECK_COUNT(); CHECK_COPY(dest_index - src_pos); for (i = 0; i < count; i++) dest[dest_index + i] = dest[dest_index - src_pos + i]; dest_index += count; } } /* validate that the entire destination buffer was filled; this is * important for decoding frame maps since each vector needs to have a * codebook entry; it is not important for compressed codebooks because * not every entry needs to be filled */ if (check_size) if (dest_index < dest_size) { av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: decode finished with dest_index (%d) < dest_size (%d)\n", dest_index, dest_size); memset(dest + dest_index, 0, dest_size - dest_index); } return 0; // let's display what we decoded anyway } static int vqa_decode_chunk(VqaContext *s, AVFrame *frame) { unsigned int chunk_type; unsigned int chunk_size; int byte_skip; unsigned int index = 0; int i; unsigned char r, g, b; int index_shift; int res; int cbf0_chunk = -1; int cbfz_chunk = -1; int cbp0_chunk = -1; int cbpz_chunk = -1; int cpl0_chunk = -1; int cplz_chunk = -1; int vptz_chunk = -1; int x, y; int lines = 0; int pixel_ptr; int vector_index = 0; int lobyte = 0; int hibyte = 0; int lobytes = 0; int hibytes = s->decode_buffer_size / 2; /* first, traverse through the frame and find the subchunks */ while (bytestream2_get_bytes_left(&s->gb) >= 8) { chunk_type = bytestream2_get_be32u(&s->gb); index = bytestream2_tell(&s->gb); chunk_size = bytestream2_get_be32u(&s->gb); switch (chunk_type) { case CBF0_TAG: cbf0_chunk = index; break; case CBFZ_TAG: cbfz_chunk = index; break; case CBP0_TAG: cbp0_chunk = index; break; case CBPZ_TAG: cbpz_chunk = index; break; case CPL0_TAG: cpl0_chunk = index; break; case CPLZ_TAG: cplz_chunk = index; break; case VPTZ_TAG: vptz_chunk = index; break; default: av_log(s->avctx, AV_LOG_ERROR, "Found unknown chunk type: %s (%08X)\n", av_fourcc2str(av_bswap32(chunk_type)), chunk_type); break; } byte_skip = chunk_size & 0x01; bytestream2_skip(&s->gb, chunk_size + byte_skip); } /* next, deal with the palette */ if ((cpl0_chunk != -1) && (cplz_chunk != -1)) { /* a chunk should not have both chunk types */ av_log(s->avctx, AV_LOG_ERROR, "problem: found both CPL0 and CPLZ chunks\n"); return AVERROR_INVALIDDATA; } /* decompress the palette chunk */ if (cplz_chunk != -1) { /* yet to be handled */ } /* convert the RGB palette into the machine's endian format */ if (cpl0_chunk != -1) { bytestream2_seek(&s->gb, cpl0_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); /* sanity check the palette size */ if (chunk_size / 3 > 256 || chunk_size > bytestream2_get_bytes_left(&s->gb)) { av_log(s->avctx, AV_LOG_ERROR, "problem: found a palette chunk with %d colors\n", chunk_size / 3); return AVERROR_INVALIDDATA; } for (i = 0; i < chunk_size / 3; i++) { /* scale by 4 to transform 6-bit palette -> 8-bit */ r = bytestream2_get_byteu(&s->gb) * 4; g = bytestream2_get_byteu(&s->gb) * 4; b = bytestream2_get_byteu(&s->gb) * 4; s->palette[i] = 0xFFU << 24 | r << 16 | g << 8 | b; s->palette[i] |= s->palette[i] >> 6 & 0x30303; } } /* next, look for a full codebook */ if ((cbf0_chunk != -1) && (cbfz_chunk != -1)) { /* a chunk should not have both chunk types */ av_log(s->avctx, AV_LOG_ERROR, "problem: found both CBF0 and CBFZ chunks\n"); return AVERROR_INVALIDDATA; } /* decompress the full codebook chunk */ if (cbfz_chunk != -1) { bytestream2_seek(&s->gb, cbfz_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if ((res = decode_format80(s, chunk_size, s->codebook, s->codebook_size, 0)) < 0) return res; } /* copy a full codebook */ if (cbf0_chunk != -1) { bytestream2_seek(&s->gb, cbf0_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); /* sanity check the full codebook size */ if (chunk_size > MAX_CODEBOOK_SIZE) { av_log(s->avctx, AV_LOG_ERROR, "problem: CBF0 chunk too large (0x%X bytes)\n", chunk_size); return AVERROR_INVALIDDATA; } bytestream2_get_buffer(&s->gb, s->codebook, chunk_size); } /* decode the frame */ if (vptz_chunk == -1) { /* something is wrong if there is no VPTZ chunk */ av_log(s->avctx, AV_LOG_ERROR, "problem: no VPTZ chunk found\n"); return AVERROR_INVALIDDATA; } bytestream2_seek(&s->gb, vptz_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if ((res = decode_format80(s, chunk_size, s->decode_buffer, s->decode_buffer_size, 1)) < 0) return res; /* render the final PAL8 frame */ if (s->vector_height == 4) index_shift = 4; else index_shift = 3; for (y = 0; y < s->height; y += s->vector_height) { for (x = 0; x < s->width; x += 4, lobytes++, hibytes++) { pixel_ptr = y * frame->linesize[0] + x; /* get the vector index, the method for which varies according to * VQA file version */ switch (s->vqa_version) { case 1: lobyte = s->decode_buffer[lobytes * 2]; hibyte = s->decode_buffer[(lobytes * 2) + 1]; vector_index = ((hibyte << 8) | lobyte) >> 3; vector_index <<= index_shift; lines = s->vector_height; /* uniform color fill - a quick hack */ if (hibyte == 0xFF) { while (lines--) { frame->data[0][pixel_ptr + 0] = 255 - lobyte; frame->data[0][pixel_ptr + 1] = 255 - lobyte; frame->data[0][pixel_ptr + 2] = 255 - lobyte; frame->data[0][pixel_ptr + 3] = 255 - lobyte; pixel_ptr += frame->linesize[0]; } lines=0; } break; case 2: lobyte = s->decode_buffer[lobytes]; hibyte = s->decode_buffer[hibytes]; vector_index = (hibyte << 8) | lobyte; vector_index <<= index_shift; lines = s->vector_height; break; case 3: /* not implemented yet */ lines = 0; break; } while (lines--) { frame->data[0][pixel_ptr + 0] = s->codebook[vector_index++]; frame->data[0][pixel_ptr + 1] = s->codebook[vector_index++]; frame->data[0][pixel_ptr + 2] = s->codebook[vector_index++]; frame->data[0][pixel_ptr + 3] = s->codebook[vector_index++]; pixel_ptr += frame->linesize[0]; } } } /* handle partial codebook */ if ((cbp0_chunk != -1) && (cbpz_chunk != -1)) { /* a chunk should not have both chunk types */ av_log(s->avctx, AV_LOG_ERROR, "problem: found both CBP0 and CBPZ chunks\n"); return AVERROR_INVALIDDATA; } if (cbp0_chunk != -1) { bytestream2_seek(&s->gb, cbp0_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if (chunk_size > MAX_CODEBOOK_SIZE - s->next_codebook_buffer_index) { av_log(s->avctx, AV_LOG_ERROR, "cbp0 chunk too large (%u bytes)\n", chunk_size); return AVERROR_INVALIDDATA; } /* accumulate partial codebook */ bytestream2_get_buffer(&s->gb, &s->next_codebook_buffer[s->next_codebook_buffer_index], chunk_size); s->next_codebook_buffer_index += chunk_size; s->partial_countdown--; if (s->partial_countdown <= 0) { /* time to replace codebook */ memcpy(s->codebook, s->next_codebook_buffer, s->next_codebook_buffer_index); /* reset accounting */ s->next_codebook_buffer_index = 0; s->partial_countdown = s->partial_count; } } if (cbpz_chunk != -1) { bytestream2_seek(&s->gb, cbpz_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if (chunk_size > MAX_CODEBOOK_SIZE - s->next_codebook_buffer_index) { av_log(s->avctx, AV_LOG_ERROR, "cbpz chunk too large (%u bytes)\n", chunk_size); return AVERROR_INVALIDDATA; } /* accumulate partial codebook */ bytestream2_get_buffer(&s->gb, &s->next_codebook_buffer[s->next_codebook_buffer_index], chunk_size); s->next_codebook_buffer_index += chunk_size; s->partial_countdown--; if (s->partial_countdown <= 0) { bytestream2_init(&s->gb, s->next_codebook_buffer, s->next_codebook_buffer_index); /* decompress codebook */ if ((res = decode_format80(s, s->next_codebook_buffer_index, s->codebook, s->codebook_size, 0)) < 0) return res; /* reset accounting */ s->next_codebook_buffer_index = 0; s->partial_countdown = s->partial_count; } } return 0; } static int vqa_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { VqaContext *s = avctx->priv_data; AVFrame *frame = data; int res; if ((res = ff_get_buffer(avctx, frame, 0)) < 0) return res; bytestream2_init(&s->gb, avpkt->data, avpkt->size); if ((res = vqa_decode_chunk(s, frame)) < 0) return res; /* make the palette available on the way out */ memcpy(frame->data[1], s->palette, PALETTE_COUNT * 4); frame->palette_has_changed = 1; *got_frame = 1; /* report that the buffer was completely consumed */ return avpkt->size; } static av_cold int vqa_decode_end(AVCodecContext *avctx) { VqaContext *s = avctx->priv_data; av_freep(&s->codebook); av_freep(&s->next_codebook_buffer); av_freep(&s->decode_buffer); return 0; } AVCodec ff_vqa_decoder = { .name = "vqavideo", .long_name = NULL_IF_CONFIG_SMALL("Westwood Studios VQA (Vector Quantized Animation) video"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_WS_VQA, .priv_data_size = sizeof(VqaContext), .init = vqa_decode_init, .close = vqa_decode_end, .decode = vqa_decode_frame, .capabilities = AV_CODEC_CAP_DR1, };
./CrossVul/dataset_final_sorted/CWE-129/c/good_1182_0
crossvul-cpp_data_bad_705_0
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/avassert.h" #include "libavutil/pixfmt.h" #include "cbs.h" #include "cbs_internal.h" #include "cbs_av1.h" #include "internal.h" static int cbs_av1_read_uvlc(CodedBitstreamContext *ctx, GetBitContext *gbc, const char *name, uint32_t *write_to, uint32_t range_min, uint32_t range_max) { uint32_t value; int position, zeroes, i, j; char bits[65]; if (ctx->trace_enable) position = get_bits_count(gbc); zeroes = i = 0; while (1) { if (get_bits_left(gbc) < zeroes + 1) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid uvlc code at " "%s: bitstream ended.\n", name); return AVERROR_INVALIDDATA; } if (get_bits1(gbc)) { bits[i++] = '1'; break; } else { bits[i++] = '0'; ++zeroes; } } if (zeroes >= 32) { value = MAX_UINT_BITS(32); } else { value = get_bits_long(gbc, zeroes); for (j = 0; j < zeroes; j++) bits[i++] = (value >> (zeroes - j - 1) & 1) ? '1' : '0'; value += (1 << zeroes) - 1; } if (ctx->trace_enable) { bits[i] = 0; ff_cbs_trace_syntax_element(ctx, position, name, NULL, bits, value); } if (value < range_min || value > range_max) { av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: " "%"PRIu32", but must be in [%"PRIu32",%"PRIu32"].\n", name, value, range_min, range_max); return AVERROR_INVALIDDATA; } *write_to = value; return 0; } static int cbs_av1_write_uvlc(CodedBitstreamContext *ctx, PutBitContext *pbc, const char *name, uint32_t value, uint32_t range_min, uint32_t range_max) { uint32_t v; int position, zeroes; if (value < range_min || value > range_max) { av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: " "%"PRIu32", but must be in [%"PRIu32",%"PRIu32"].\n", name, value, range_min, range_max); return AVERROR_INVALIDDATA; } if (ctx->trace_enable) position = put_bits_count(pbc); if (value == 0) { zeroes = 0; put_bits(pbc, 1, 1); } else { zeroes = av_log2(value + 1); v = value - (1 << zeroes) + 1; put_bits(pbc, zeroes + 1, 1); put_bits(pbc, zeroes, v); } if (ctx->trace_enable) { char bits[65]; int i, j; i = 0; for (j = 0; j < zeroes; j++) bits[i++] = '0'; bits[i++] = '1'; for (j = 0; j < zeroes; j++) bits[i++] = (v >> (zeroes - j - 1) & 1) ? '1' : '0'; bits[i++] = 0; ff_cbs_trace_syntax_element(ctx, position, name, NULL, bits, value); } return 0; } static int cbs_av1_read_leb128(CodedBitstreamContext *ctx, GetBitContext *gbc, const char *name, uint64_t *write_to) { uint64_t value; int position, err, i; if (ctx->trace_enable) position = get_bits_count(gbc); value = 0; for (i = 0; i < 8; i++) { int subscript[2] = { 1, i }; uint32_t byte; err = ff_cbs_read_unsigned(ctx, gbc, 8, "leb128_byte[i]", subscript, &byte, 0x00, 0xff); if (err < 0) return err; value |= (uint64_t)(byte & 0x7f) << (i * 7); if (!(byte & 0x80)) break; } if (ctx->trace_enable) ff_cbs_trace_syntax_element(ctx, position, name, NULL, "", value); *write_to = value; return 0; } static int cbs_av1_write_leb128(CodedBitstreamContext *ctx, PutBitContext *pbc, const char *name, uint64_t value) { int position, err, len, i; uint8_t byte; len = (av_log2(value) + 7) / 7; if (ctx->trace_enable) position = put_bits_count(pbc); for (i = 0; i < len; i++) { int subscript[2] = { 1, i }; byte = value >> (7 * i) & 0x7f; if (i < len - 1) byte |= 0x80; err = ff_cbs_write_unsigned(ctx, pbc, 8, "leb128_byte[i]", subscript, byte, 0x00, 0xff); if (err < 0) return err; } if (ctx->trace_enable) ff_cbs_trace_syntax_element(ctx, position, name, NULL, "", value); return 0; } static int cbs_av1_read_su(CodedBitstreamContext *ctx, GetBitContext *gbc, int width, const char *name, const int *subscripts, int32_t *write_to) { int position; int32_t value; if (ctx->trace_enable) position = get_bits_count(gbc); if (get_bits_left(gbc) < width) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid signed value at " "%s: bitstream ended.\n", name); return AVERROR_INVALIDDATA; } value = get_sbits(gbc, width); if (ctx->trace_enable) { char bits[33]; int i; for (i = 0; i < width; i++) bits[i] = value & (1 << (width - i - 1)) ? '1' : '0'; bits[i] = 0; ff_cbs_trace_syntax_element(ctx, position, name, subscripts, bits, value); } *write_to = value; return 0; } static int cbs_av1_write_su(CodedBitstreamContext *ctx, PutBitContext *pbc, int width, const char *name, const int *subscripts, int32_t value) { if (put_bits_left(pbc) < width) return AVERROR(ENOSPC); if (ctx->trace_enable) { char bits[33]; int i; for (i = 0; i < width; i++) bits[i] = value & (1 << (width - i - 1)) ? '1' : '0'; bits[i] = 0; ff_cbs_trace_syntax_element(ctx, put_bits_count(pbc), name, subscripts, bits, value); } put_sbits(pbc, width, value); return 0; } static int cbs_av1_read_ns(CodedBitstreamContext *ctx, GetBitContext *gbc, uint32_t n, const char *name, const int *subscripts, uint32_t *write_to) { uint32_t w, m, v, extra_bit, value; int position; av_assert0(n > 0); if (ctx->trace_enable) position = get_bits_count(gbc); w = av_log2(n) + 1; m = (1 << w) - n; if (get_bits_left(gbc) < w) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid non-symmetric value at " "%s: bitstream ended.\n", name); return AVERROR_INVALIDDATA; } if (w - 1 > 0) v = get_bits(gbc, w - 1); else v = 0; if (v < m) { value = v; } else { extra_bit = get_bits1(gbc); value = (v << 1) - m + extra_bit; } if (ctx->trace_enable) { char bits[33]; int i; for (i = 0; i < w - 1; i++) bits[i] = (v >> i & 1) ? '1' : '0'; if (v >= m) bits[i++] = extra_bit ? '1' : '0'; bits[i] = 0; ff_cbs_trace_syntax_element(ctx, position, name, subscripts, bits, value); } *write_to = value; return 0; } static int cbs_av1_write_ns(CodedBitstreamContext *ctx, PutBitContext *pbc, uint32_t n, const char *name, const int *subscripts, uint32_t value) { uint32_t w, m, v, extra_bit; int position; if (value > n) { av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: " "%"PRIu32", but must be in [0,%"PRIu32"].\n", name, value, n); return AVERROR_INVALIDDATA; } if (ctx->trace_enable) position = put_bits_count(pbc); w = av_log2(n) + 1; m = (1 << w) - n; if (put_bits_left(pbc) < w) return AVERROR(ENOSPC); if (value < m) { v = value; put_bits(pbc, w - 1, v); } else { v = m + ((value - m) >> 1); extra_bit = (value - m) & 1; put_bits(pbc, w - 1, v); put_bits(pbc, 1, extra_bit); } if (ctx->trace_enable) { char bits[33]; int i; for (i = 0; i < w - 1; i++) bits[i] = (v >> i & 1) ? '1' : '0'; if (value >= m) bits[i++] = extra_bit ? '1' : '0'; bits[i] = 0; ff_cbs_trace_syntax_element(ctx, position, name, subscripts, bits, value); } return 0; } static int cbs_av1_read_increment(CodedBitstreamContext *ctx, GetBitContext *gbc, uint32_t range_min, uint32_t range_max, const char *name, uint32_t *write_to) { uint32_t value; int position, i; char bits[33]; av_assert0(range_min <= range_max && range_max - range_min < sizeof(bits) - 1); if (ctx->trace_enable) position = get_bits_count(gbc); for (i = 0, value = range_min; value < range_max;) { if (get_bits_left(gbc) < 1) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid increment value at " "%s: bitstream ended.\n", name); return AVERROR_INVALIDDATA; } if (get_bits1(gbc)) { bits[i++] = '1'; ++value; } else { bits[i++] = '0'; break; } } if (ctx->trace_enable) { bits[i] = 0; ff_cbs_trace_syntax_element(ctx, position, name, NULL, bits, value); } *write_to = value; return 0; } static int cbs_av1_write_increment(CodedBitstreamContext *ctx, PutBitContext *pbc, uint32_t range_min, uint32_t range_max, const char *name, uint32_t value) { int len; av_assert0(range_min <= range_max && range_max - range_min < 32); if (value < range_min || value > range_max) { av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: " "%"PRIu32", but must be in [%"PRIu32",%"PRIu32"].\n", name, value, range_min, range_max); return AVERROR_INVALIDDATA; } if (value == range_max) len = range_max - range_min; else len = value - range_min + 1; if (put_bits_left(pbc) < len) return AVERROR(ENOSPC); if (ctx->trace_enable) { char bits[33]; int i; for (i = 0; i < len; i++) { if (range_min + i == value) bits[i] = '0'; else bits[i] = '1'; } bits[i] = 0; ff_cbs_trace_syntax_element(ctx, put_bits_count(pbc), name, NULL, bits, value); } if (len > 0) put_bits(pbc, len, (1 << len) - 1 - (value != range_max)); return 0; } static int cbs_av1_read_subexp(CodedBitstreamContext *ctx, GetBitContext *gbc, uint32_t range_max, const char *name, const int *subscripts, uint32_t *write_to) { uint32_t value; int position, err; uint32_t max_len, len, range_offset, range_bits; if (ctx->trace_enable) position = get_bits_count(gbc); av_assert0(range_max > 0); max_len = av_log2(range_max - 1) - 3; err = cbs_av1_read_increment(ctx, gbc, 0, max_len, "subexp_more_bits", &len); if (err < 0) return err; if (len) { range_bits = 2 + len; range_offset = 1 << range_bits; } else { range_bits = 3; range_offset = 0; } if (len < max_len) { err = ff_cbs_read_unsigned(ctx, gbc, range_bits, "subexp_bits", NULL, &value, 0, MAX_UINT_BITS(range_bits)); if (err < 0) return err; } else { err = cbs_av1_read_ns(ctx, gbc, range_max - range_offset, "subexp_final_bits", NULL, &value); if (err < 0) return err; } value += range_offset; if (ctx->trace_enable) ff_cbs_trace_syntax_element(ctx, position, name, subscripts, "", value); *write_to = value; return err; } static int cbs_av1_write_subexp(CodedBitstreamContext *ctx, PutBitContext *pbc, uint32_t range_max, const char *name, const int *subscripts, uint32_t value) { int position, err; uint32_t max_len, len, range_offset, range_bits; if (value > range_max) { av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: " "%"PRIu32", but must be in [0,%"PRIu32"].\n", name, value, range_max); return AVERROR_INVALIDDATA; } if (ctx->trace_enable) position = put_bits_count(pbc); av_assert0(range_max > 0); max_len = av_log2(range_max - 1) - 3; if (value < 8) { range_bits = 3; range_offset = 0; len = 0; } else { range_bits = av_log2(value); len = range_bits - 2; if (len > max_len) { // The top bin is combined with the one below it. av_assert0(len == max_len + 1); --range_bits; len = max_len; } range_offset = 1 << range_bits; } err = cbs_av1_write_increment(ctx, pbc, 0, max_len, "subexp_more_bits", len); if (err < 0) return err; if (len < max_len) { err = ff_cbs_write_unsigned(ctx, pbc, range_bits, "subexp_bits", NULL, value - range_offset, 0, MAX_UINT_BITS(range_bits)); if (err < 0) return err; } else { err = cbs_av1_write_ns(ctx, pbc, range_max - range_offset, "subexp_final_bits", NULL, value - range_offset); if (err < 0) return err; } if (ctx->trace_enable) ff_cbs_trace_syntax_element(ctx, position, name, subscripts, "", value); return err; } static int cbs_av1_tile_log2(int blksize, int target) { int k; for (k = 0; (blksize << k) < target; k++); return k; } static int cbs_av1_get_relative_dist(const AV1RawSequenceHeader *seq, unsigned int a, unsigned int b) { unsigned int diff, m; if (!seq->enable_order_hint) return 0; diff = a - b; m = 1 << seq->order_hint_bits_minus_1; diff = (diff & (m - 1)) - (diff & m); return diff; } #define HEADER(name) do { \ ff_cbs_trace_header(ctx, name); \ } while (0) #define CHECK(call) do { \ err = (call); \ if (err < 0) \ return err; \ } while (0) #define FUNC_NAME(rw, codec, name) cbs_ ## codec ## _ ## rw ## _ ## name #define FUNC_AV1(rw, name) FUNC_NAME(rw, av1, name) #define FUNC(name) FUNC_AV1(READWRITE, name) #define SUBSCRIPTS(subs, ...) (subs > 0 ? ((int[subs + 1]){ subs, __VA_ARGS__ }) : NULL) #define fb(width, name) \ xf(width, name, current->name, 0, MAX_UINT_BITS(width), 0) #define fc(width, name, range_min, range_max) \ xf(width, name, current->name, range_min, range_max, 0) #define flag(name) fb(1, name) #define su(width, name) \ xsu(width, name, current->name, 0) #define fbs(width, name, subs, ...) \ xf(width, name, current->name, 0, MAX_UINT_BITS(width), subs, __VA_ARGS__) #define fcs(width, name, range_min, range_max, subs, ...) \ xf(width, name, current->name, range_min, range_max, subs, __VA_ARGS__) #define flags(name, subs, ...) \ xf(1, name, current->name, 0, 1, subs, __VA_ARGS__) #define sus(width, name, subs, ...) \ xsu(width, name, current->name, subs, __VA_ARGS__) #define fixed(width, name, value) do { \ av_unused uint32_t fixed_value = value; \ xf(width, name, fixed_value, value, value, 0); \ } while (0) #define READ #define READWRITE read #define RWContext GetBitContext #define xf(width, name, var, range_min, range_max, subs, ...) do { \ uint32_t value = range_min; \ CHECK(ff_cbs_read_unsigned(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ &value, range_min, range_max)); \ var = value; \ } while (0) #define xsu(width, name, var, subs, ...) do { \ int32_t value = 0; \ CHECK(cbs_av1_read_su(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), &value)); \ var = value; \ } while (0) #define uvlc(name, range_min, range_max) do { \ uint32_t value = range_min; \ CHECK(cbs_av1_read_uvlc(ctx, rw, #name, \ &value, range_min, range_max)); \ current->name = value; \ } while (0) #define ns(max_value, name, subs, ...) do { \ uint32_t value = 0; \ CHECK(cbs_av1_read_ns(ctx, rw, max_value, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), &value)); \ current->name = value; \ } while (0) #define increment(name, min, max) do { \ uint32_t value = 0; \ CHECK(cbs_av1_read_increment(ctx, rw, min, max, #name, &value)); \ current->name = value; \ } while (0) #define subexp(name, max, subs, ...) do { \ uint32_t value = 0; \ CHECK(cbs_av1_read_subexp(ctx, rw, max, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), &value)); \ current->name = value; \ } while (0) #define delta_q(name) do { \ uint8_t delta_coded; \ int8_t delta_q; \ xf(1, name.delta_coded, delta_coded, 0, 1, 0); \ if (delta_coded) \ xsu(1 + 6, name.delta_q, delta_q, 0); \ else \ delta_q = 0; \ current->name = delta_q; \ } while (0) #define leb128(name) do { \ uint64_t value = 0; \ CHECK(cbs_av1_read_leb128(ctx, rw, #name, &value)); \ current->name = value; \ } while (0) #define infer(name, value) do { \ current->name = value; \ } while (0) #define byte_alignment(rw) (get_bits_count(rw) % 8) #include "cbs_av1_syntax_template.c" #undef READ #undef READWRITE #undef RWContext #undef xf #undef xsu #undef uvlc #undef leb128 #undef ns #undef increment #undef subexp #undef delta_q #undef leb128 #undef infer #undef byte_alignment #define WRITE #define READWRITE write #define RWContext PutBitContext #define xf(width, name, var, range_min, range_max, subs, ...) do { \ CHECK(ff_cbs_write_unsigned(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ var, range_min, range_max)); \ } while (0) #define xsu(width, name, var, subs, ...) do { \ CHECK(cbs_av1_write_su(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), var)); \ } while (0) #define uvlc(name, range_min, range_max) do { \ CHECK(cbs_av1_write_uvlc(ctx, rw, #name, current->name, \ range_min, range_max)); \ } while (0) #define ns(max_value, name, subs, ...) do { \ CHECK(cbs_av1_write_ns(ctx, rw, max_value, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ current->name)); \ } while (0) #define increment(name, min, max) do { \ CHECK(cbs_av1_write_increment(ctx, rw, min, max, #name, \ current->name)); \ } while (0) #define subexp(name, max, subs, ...) do { \ CHECK(cbs_av1_write_subexp(ctx, rw, max, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ current->name)); \ } while (0) #define delta_q(name) do { \ xf(1, name.delta_coded, current->name != 0, 0, 1, 0); \ if (current->name) \ xsu(1 + 6, name.delta_q, current->name, 0); \ } while (0) #define leb128(name) do { \ CHECK(cbs_av1_write_leb128(ctx, rw, #name, current->name)); \ } while (0) #define infer(name, value) do { \ if (current->name != (value)) { \ av_log(ctx->log_ctx, AV_LOG_WARNING, "Warning: " \ "%s does not match inferred value: " \ "%"PRId64", but should be %"PRId64".\n", \ #name, (int64_t)current->name, (int64_t)(value)); \ } \ } while (0) #define byte_alignment(rw) (put_bits_count(rw) % 8) #include "cbs_av1_syntax_template.c" #undef READ #undef READWRITE #undef RWContext #undef xf #undef xsu #undef uvlc #undef leb128 #undef ns #undef increment #undef subexp #undef delta_q #undef infer #undef byte_alignment static int cbs_av1_split_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag, int header) { GetBitContext gbc; uint8_t *data; size_t size; uint64_t obu_length; int pos, err, trace; // Don't include this parsing in trace output. trace = ctx->trace_enable; ctx->trace_enable = 0; data = frag->data; size = frag->data_size; if (INT_MAX / 8 < size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid fragment: " "too large (%"SIZE_SPECIFIER" bytes).\n", size); err = AVERROR_INVALIDDATA; goto fail; } while (size > 0) { AV1RawOBUHeader header; uint64_t obu_size; init_get_bits(&gbc, data, 8 * size); err = cbs_av1_read_obu_header(ctx, &gbc, &header); if (err < 0) goto fail; if (get_bits_left(&gbc) < 8) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid OBU: fragment " "too short (%"SIZE_SPECIFIER" bytes).\n", size); err = AVERROR_INVALIDDATA; goto fail; } if (header.obu_has_size_field) { err = cbs_av1_read_leb128(ctx, &gbc, "obu_size", &obu_size); if (err < 0) goto fail; } else obu_size = size - 1 - header.obu_extension_flag; pos = get_bits_count(&gbc); av_assert0(pos % 8 == 0 && pos / 8 <= size); obu_length = pos / 8 + obu_size; if (size < obu_length) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid OBU length: " "%"PRIu64", but only %"SIZE_SPECIFIER" bytes remaining in fragment.\n", obu_length, size); err = AVERROR_INVALIDDATA; goto fail; } err = ff_cbs_insert_unit_data(ctx, frag, -1, header.obu_type, data, obu_length, frag->data_ref); if (err < 0) goto fail; data += obu_length; size -= obu_length; } err = 0; fail: ctx->trace_enable = trace; return err; } static void cbs_av1_free_tile_data(AV1RawTileData *td) { av_buffer_unref(&td->data_ref); } static void cbs_av1_free_metadata(AV1RawMetadata *md) { switch (md->metadata_type) { case AV1_METADATA_TYPE_ITUT_T35: av_buffer_unref(&md->metadata.itut_t35.payload_ref); break; } } static void cbs_av1_free_obu(void *unit, uint8_t *content) { AV1RawOBU *obu = (AV1RawOBU*)content; switch (obu->header.obu_type) { case AV1_OBU_TILE_GROUP: cbs_av1_free_tile_data(&obu->obu.tile_group.tile_data); break; case AV1_OBU_FRAME: cbs_av1_free_tile_data(&obu->obu.frame.tile_group.tile_data); break; case AV1_OBU_TILE_LIST: cbs_av1_free_tile_data(&obu->obu.tile_list.tile_data); break; case AV1_OBU_METADATA: cbs_av1_free_metadata(&obu->obu.metadata); break; } av_freep(&obu); } static int cbs_av1_ref_tile_data(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, GetBitContext *gbc, AV1RawTileData *td) { int pos; pos = get_bits_count(gbc); if (pos >= 8 * unit->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Bitstream ended before " "any data in tile group (%d bits read).\n", pos); return AVERROR_INVALIDDATA; } // Must be byte-aligned at this point. av_assert0(pos % 8 == 0); td->data_ref = av_buffer_ref(unit->data_ref); if (!td->data_ref) return AVERROR(ENOMEM); td->data = unit->data + pos / 8; td->data_size = unit->data_size - pos / 8; return 0; } static int cbs_av1_read_unit(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit) { CodedBitstreamAV1Context *priv = ctx->priv_data; AV1RawOBU *obu; GetBitContext gbc; int err, start_pos, end_pos; err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*obu), &cbs_av1_free_obu); if (err < 0) return err; obu = unit->content; err = init_get_bits(&gbc, unit->data, 8 * unit->data_size); if (err < 0) return err; err = cbs_av1_read_obu_header(ctx, &gbc, &obu->header); if (err < 0) return err; av_assert0(obu->header.obu_type == unit->type); if (obu->header.obu_has_size_field) { uint64_t obu_size; err = cbs_av1_read_leb128(ctx, &gbc, "obu_size", &obu_size); if (err < 0) return err; obu->obu_size = obu_size; } else { if (unit->data_size < 1 + obu->header.obu_extension_flag) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid OBU length: " "unit too short (%"SIZE_SPECIFIER").\n", unit->data_size); return AVERROR_INVALIDDATA; } obu->obu_size = unit->data_size - 1 - obu->header.obu_extension_flag; } start_pos = get_bits_count(&gbc); if (obu->header.obu_extension_flag) { priv->temporal_id = obu->header.temporal_id; priv->spatial_id = obu->header.temporal_id; if (obu->header.obu_type != AV1_OBU_SEQUENCE_HEADER && obu->header.obu_type != AV1_OBU_TEMPORAL_DELIMITER && priv->operating_point_idc) { int in_temporal_layer = (priv->operating_point_idc >> priv->temporal_id ) & 1; int in_spatial_layer = (priv->operating_point_idc >> (priv->spatial_id + 8)) & 1; if (!in_temporal_layer || !in_spatial_layer) { // Decoding will drop this OBU at this operating point. } } } else { priv->temporal_id = 0; priv->spatial_id = 0; } switch (obu->header.obu_type) { case AV1_OBU_SEQUENCE_HEADER: { err = cbs_av1_read_sequence_header_obu(ctx, &gbc, &obu->obu.sequence_header); if (err < 0) return err; av_buffer_unref(&priv->sequence_header_ref); priv->sequence_header = NULL; priv->sequence_header_ref = av_buffer_ref(unit->content_ref); if (!priv->sequence_header_ref) return AVERROR(ENOMEM); priv->sequence_header = &obu->obu.sequence_header; } break; case AV1_OBU_TEMPORAL_DELIMITER: { err = cbs_av1_read_temporal_delimiter_obu(ctx, &gbc); if (err < 0) return err; } break; case AV1_OBU_FRAME_HEADER: case AV1_OBU_REDUNDANT_FRAME_HEADER: { err = cbs_av1_read_frame_header_obu(ctx, &gbc, &obu->obu.frame_header, obu->header.obu_type == AV1_OBU_REDUNDANT_FRAME_HEADER, unit->data_ref); if (err < 0) return err; } break; case AV1_OBU_TILE_GROUP: { err = cbs_av1_read_tile_group_obu(ctx, &gbc, &obu->obu.tile_group); if (err < 0) return err; err = cbs_av1_ref_tile_data(ctx, unit, &gbc, &obu->obu.tile_group.tile_data); if (err < 0) return err; } break; case AV1_OBU_FRAME: { err = cbs_av1_read_frame_obu(ctx, &gbc, &obu->obu.frame, unit->data_ref); if (err < 0) return err; err = cbs_av1_ref_tile_data(ctx, unit, &gbc, &obu->obu.frame.tile_group.tile_data); if (err < 0) return err; } break; case AV1_OBU_TILE_LIST: { err = cbs_av1_read_tile_list_obu(ctx, &gbc, &obu->obu.tile_list); if (err < 0) return err; err = cbs_av1_ref_tile_data(ctx, unit, &gbc, &obu->obu.tile_list.tile_data); if (err < 0) return err; } break; case AV1_OBU_METADATA: { err = cbs_av1_read_metadata_obu(ctx, &gbc, &obu->obu.metadata); if (err < 0) return err; } break; case AV1_OBU_PADDING: default: return AVERROR(ENOSYS); } end_pos = get_bits_count(&gbc); av_assert0(end_pos <= unit->data_size * 8); if (obu->obu_size > 0 && obu->header.obu_type != AV1_OBU_TILE_GROUP && obu->header.obu_type != AV1_OBU_FRAME) { err = cbs_av1_read_trailing_bits(ctx, &gbc, obu->obu_size * 8 + start_pos - end_pos); if (err < 0) return err; } return 0; } static int cbs_av1_write_obu(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { CodedBitstreamAV1Context *priv = ctx->priv_data; AV1RawOBU *obu = unit->content; PutBitContext pbc_tmp; AV1RawTileData *td; size_t header_size; int err, start_pos, end_pos, data_pos; // OBUs in the normal bitstream format must contain a size field // in every OBU (in annex B it is optional, but we don't support // writing that). obu->header.obu_has_size_field = 1; err = cbs_av1_write_obu_header(ctx, pbc, &obu->header); if (err < 0) return err; if (obu->header.obu_has_size_field) { pbc_tmp = *pbc; // Add space for the size field to fill later. put_bits32(pbc, 0); put_bits32(pbc, 0); } td = NULL; start_pos = put_bits_count(pbc); switch (obu->header.obu_type) { case AV1_OBU_SEQUENCE_HEADER: { err = cbs_av1_write_sequence_header_obu(ctx, pbc, &obu->obu.sequence_header); if (err < 0) return err; av_buffer_unref(&priv->sequence_header_ref); priv->sequence_header = NULL; priv->sequence_header_ref = av_buffer_ref(unit->content_ref); if (!priv->sequence_header_ref) return AVERROR(ENOMEM); priv->sequence_header = &obu->obu.sequence_header; } break; case AV1_OBU_TEMPORAL_DELIMITER: { err = cbs_av1_write_temporal_delimiter_obu(ctx, pbc); if (err < 0) return err; } break; case AV1_OBU_FRAME_HEADER: case AV1_OBU_REDUNDANT_FRAME_HEADER: { err = cbs_av1_write_frame_header_obu(ctx, pbc, &obu->obu.frame_header, obu->header.obu_type == AV1_OBU_REDUNDANT_FRAME_HEADER, NULL); if (err < 0) return err; } break; case AV1_OBU_TILE_GROUP: { err = cbs_av1_write_tile_group_obu(ctx, pbc, &obu->obu.tile_group); if (err < 0) return err; td = &obu->obu.tile_group.tile_data; } break; case AV1_OBU_FRAME: { err = cbs_av1_write_frame_obu(ctx, pbc, &obu->obu.frame, NULL); if (err < 0) return err; td = &obu->obu.frame.tile_group.tile_data; } break; case AV1_OBU_TILE_LIST: { err = cbs_av1_write_tile_list_obu(ctx, pbc, &obu->obu.tile_list); if (err < 0) return err; td = &obu->obu.tile_list.tile_data; } break; case AV1_OBU_METADATA: { err = cbs_av1_write_metadata_obu(ctx, pbc, &obu->obu.metadata); if (err < 0) return err; } break; case AV1_OBU_PADDING: default: return AVERROR(ENOSYS); } end_pos = put_bits_count(pbc); header_size = (end_pos - start_pos + 7) / 8; if (td) { obu->obu_size = header_size + td->data_size; } else if (header_size > 0) { // Add trailing bits and recalculate. err = cbs_av1_write_trailing_bits(ctx, pbc, 8 - end_pos % 8); if (err < 0) return err; end_pos = put_bits_count(pbc); obu->obu_size = header_size = (end_pos - start_pos + 7) / 8; } else { // Empty OBU. obu->obu_size = 0; } end_pos = put_bits_count(pbc); // Must now be byte-aligned. av_assert0(end_pos % 8 == 0); flush_put_bits(pbc); start_pos /= 8; end_pos /= 8; *pbc = pbc_tmp; err = cbs_av1_write_leb128(ctx, pbc, "obu_size", obu->obu_size); if (err < 0) return err; data_pos = put_bits_count(pbc) / 8; flush_put_bits(pbc); av_assert0(data_pos <= start_pos); if (8 * obu->obu_size > put_bits_left(pbc)) return AVERROR(ENOSPC); if (obu->obu_size > 0) { memmove(priv->write_buffer + data_pos, priv->write_buffer + start_pos, header_size); skip_put_bytes(pbc, header_size); if (td) { memcpy(priv->write_buffer + data_pos + header_size, td->data, td->data_size); skip_put_bytes(pbc, td->data_size); } } return 0; } static int cbs_av1_write_unit(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit) { CodedBitstreamAV1Context *priv = ctx->priv_data; PutBitContext pbc; int err; if (!priv->write_buffer) { // Initial write buffer size is 1MB. priv->write_buffer_size = 1024 * 1024; reallocate_and_try_again: err = av_reallocp(&priv->write_buffer, priv->write_buffer_size); if (err < 0) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Unable to allocate a " "sufficiently large write buffer (last attempt " "%"SIZE_SPECIFIER" bytes).\n", priv->write_buffer_size); return err; } } init_put_bits(&pbc, priv->write_buffer, priv->write_buffer_size); err = cbs_av1_write_obu(ctx, unit, &pbc); if (err == AVERROR(ENOSPC)) { // Overflow. priv->write_buffer_size *= 2; goto reallocate_and_try_again; } if (err < 0) return err; // Overflow but we didn't notice. av_assert0(put_bits_count(&pbc) <= 8 * priv->write_buffer_size); // OBU data must be byte-aligned. av_assert0(put_bits_count(&pbc) % 8 == 0); unit->data_size = put_bits_count(&pbc) / 8; flush_put_bits(&pbc); err = ff_cbs_alloc_unit_data(ctx, unit, unit->data_size); if (err < 0) return err; memcpy(unit->data, priv->write_buffer, unit->data_size); return 0; } static int cbs_av1_assemble_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag) { size_t size, pos; int i; size = 0; for (i = 0; i < frag->nb_units; i++) size += frag->units[i].data_size; frag->data_ref = av_buffer_alloc(size + AV_INPUT_BUFFER_PADDING_SIZE); if (!frag->data_ref) return AVERROR(ENOMEM); frag->data = frag->data_ref->data; memset(frag->data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE); pos = 0; for (i = 0; i < frag->nb_units; i++) { memcpy(frag->data + pos, frag->units[i].data, frag->units[i].data_size); pos += frag->units[i].data_size; } av_assert0(pos == size); frag->data_size = size; return 0; } static void cbs_av1_close(CodedBitstreamContext *ctx) { CodedBitstreamAV1Context *priv = ctx->priv_data; av_buffer_unref(&priv->sequence_header_ref); av_buffer_unref(&priv->frame_header_ref); av_freep(&priv->write_buffer); } const CodedBitstreamType ff_cbs_type_av1 = { .codec_id = AV_CODEC_ID_AV1, .priv_data_size = sizeof(CodedBitstreamAV1Context), .split_fragment = &cbs_av1_split_fragment, .read_unit = &cbs_av1_read_unit, .write_unit = &cbs_av1_write_unit, .assemble_fragment = &cbs_av1_assemble_fragment, .close = &cbs_av1_close, };
./CrossVul/dataset_final_sorted/CWE-129/c/bad_705_0
crossvul-cpp_data_bad_217_0
/* * MOV, 3GP, MP4 muxer * Copyright (c) 2003 Thomas Raivio * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org> * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com> * * 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 <stdint.h> #include <inttypes.h> #include "movenc.h" #include "avformat.h" #include "avio_internal.h" #include "riff.h" #include "avio.h" #include "isom.h" #include "avc.h" #include "libavcodec/ac3_parser_internal.h" #include "libavcodec/dnxhddata.h" #include "libavcodec/flac.h" #include "libavcodec/get_bits.h" #include "libavcodec/internal.h" #include "libavcodec/put_bits.h" #include "libavcodec/vc1_common.h" #include "libavcodec/raw.h" #include "internal.h" #include "libavutil/avstring.h" #include "libavutil/intfloat.h" #include "libavutil/mathematics.h" #include "libavutil/libm.h" #include "libavutil/opt.h" #include "libavutil/dict.h" #include "libavutil/pixdesc.h" #include "libavutil/stereo3d.h" #include "libavutil/timecode.h" #include "libavutil/color_utils.h" #include "hevc.h" #include "rtpenc.h" #include "mov_chan.h" #include "vpcc.h" static const AVOption options[] = { { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 }, { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "negative_cts_offsets", "Use negative CTS offsets (reducing the need for edit lists)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags), { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM}, { "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "write_prft", "Write producer reference time box with specified time source", offsetof(MOVMuxContext, write_prft), AV_OPT_TYPE_INT, {.i64 = MOV_PRFT_NONE}, 0, MOV_PRFT_NB-1, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "empty_hdlr_name", "write zero-length name string in hdlr atoms within mdia and minf atoms", offsetof(MOVMuxContext, empty_hdlr_name), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { NULL }, }; #define MOV_CLASS(flavor)\ static const AVClass flavor ## _muxer_class = {\ .class_name = #flavor " muxer",\ .item_name = av_default_item_name,\ .option = options,\ .version = LIBAVUTIL_VERSION_INT,\ }; static int get_moov_size(AVFormatContext *s); static int utf8len(const uint8_t *b) { int len = 0; int val; while (*b) { GET_UTF8(val, *b++, return -1;) len++; } return len; } //FIXME support 64 bit variant with wide placeholders static int64_t update_size(AVIOContext *pb, int64_t pos) { int64_t curpos = avio_tell(pb); avio_seek(pb, pos, SEEK_SET); avio_wb32(pb, curpos - pos); /* rewrite size */ avio_seek(pb, curpos, SEEK_SET); return curpos - pos; } static int co64_required(const MOVTrack *track) { if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX) return 1; return 0; } static int is_cover_image(const AVStream *st) { /* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS * is encoded as sparse video track */ return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC; } static int rtp_hinting_needed(const AVStream *st) { /* Add hint tracks for each real audio and video stream */ if (is_cover_image(st)) return 0; return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO || st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO; } /* Chunk offset atom */ static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track) { int i; int mode64 = co64_required(track); // use 32 bit size variant if possible int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ if (mode64) ffio_wfourcc(pb, "co64"); else ffio_wfourcc(pb, "stco"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, track->chunkCount); /* entry count */ for (i = 0; i < track->entry; i++) { if (!track->cluster[i].chunkNum) continue; if (mode64 == 1) avio_wb64(pb, track->cluster[i].pos + track->data_offset); else avio_wb32(pb, track->cluster[i].pos + track->data_offset); } return update_size(pb, pos); } /* Sample size atom */ static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track) { int equalChunks = 1; int i, j, entries = 0, tst = -1, oldtst = -1; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsz"); avio_wb32(pb, 0); /* version & flags */ for (i = 0; i < track->entry; i++) { tst = track->cluster[i].size / track->cluster[i].entries; if (oldtst != -1 && tst != oldtst) equalChunks = 0; oldtst = tst; entries += track->cluster[i].entries; } if (equalChunks && track->entry) { int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0; sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0 avio_wb32(pb, sSize); // sample size avio_wb32(pb, entries); // sample count } else { avio_wb32(pb, 0); // sample size avio_wb32(pb, entries); // sample count for (i = 0; i < track->entry; i++) { for (j = 0; j < track->cluster[i].entries; j++) { avio_wb32(pb, track->cluster[i].size / track->cluster[i].entries); } } } return update_size(pb, pos); } /* Sample to chunk atom */ static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track) { int index = 0, oldval = -1, i; int64_t entryPos, curpos; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsc"); avio_wb32(pb, 0); // version & flags entryPos = avio_tell(pb); avio_wb32(pb, track->chunkCount); // entry count for (i = 0; i < track->entry; i++) { if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) { avio_wb32(pb, track->cluster[i].chunkNum); // first chunk avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk avio_wb32(pb, 0x1); // sample description index oldval = track->cluster[i].samples_in_chunk; index++; } } curpos = avio_tell(pb); avio_seek(pb, entryPos, SEEK_SET); avio_wb32(pb, index); // rewrite size avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } /* Sync sample atom */ static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag) { int64_t curpos, entryPos; int i, index = 0; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); // size ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps"); avio_wb32(pb, 0); // version & flags entryPos = avio_tell(pb); avio_wb32(pb, track->entry); // entry count for (i = 0; i < track->entry; i++) { if (track->cluster[i].flags & flag) { avio_wb32(pb, i + 1); index++; } } curpos = avio_tell(pb); avio_seek(pb, entryPos, SEEK_SET); avio_wb32(pb, index); // rewrite size avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } /* Sample dependency atom */ static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track) { int i; uint8_t leading, dependent, reference, redundancy; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); // size ffio_wfourcc(pb, "sdtp"); avio_wb32(pb, 0); // version & flags for (i = 0; i < track->entry; i++) { dependent = MOV_SAMPLE_DEPENDENCY_YES; leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN; if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) { reference = MOV_SAMPLE_DEPENDENCY_NO; } if (track->cluster[i].flags & MOV_SYNC_SAMPLE) { dependent = MOV_SAMPLE_DEPENDENCY_NO; } avio_w8(pb, (leading << 6) | (dependent << 4) | (reference << 2) | redundancy); } return update_size(pb, pos); } static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 0x11); /* size */ if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr"); else ffio_wfourcc(pb, "damr"); ffio_wfourcc(pb, "FFMP"); avio_w8(pb, 0); /* decoder version */ avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */ avio_w8(pb, 0x00); /* Mode change period (no restriction) */ avio_w8(pb, 0x01); /* Frames per sample */ return 0x11; } static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track) { GetBitContext gbc; PutBitContext pbc; uint8_t buf[3]; int fscod, bsid, bsmod, acmod, lfeon, frmsizecod; if (track->vos_len < 7) return -1; avio_wb32(pb, 11); ffio_wfourcc(pb, "dac3"); init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8); fscod = get_bits(&gbc, 2); frmsizecod = get_bits(&gbc, 6); bsid = get_bits(&gbc, 5); bsmod = get_bits(&gbc, 3); acmod = get_bits(&gbc, 3); if (acmod == 2) { skip_bits(&gbc, 2); // dsurmod } else { if ((acmod & 1) && acmod != 1) skip_bits(&gbc, 2); // cmixlev if (acmod & 4) skip_bits(&gbc, 2); // surmixlev } lfeon = get_bits1(&gbc); init_put_bits(&pbc, buf, sizeof(buf)); put_bits(&pbc, 2, fscod); put_bits(&pbc, 5, bsid); put_bits(&pbc, 3, bsmod); put_bits(&pbc, 3, acmod); put_bits(&pbc, 1, lfeon); put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code put_bits(&pbc, 5, 0); // reserved flush_put_bits(&pbc); avio_write(pb, buf, sizeof(buf)); return 11; } struct eac3_info { AVPacket pkt; uint8_t ec3_done; uint8_t num_blocks; /* Layout of the EC3SpecificBox */ /* maximum bitrate */ uint16_t data_rate; /* number of independent substreams */ uint8_t num_ind_sub; struct { /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */ uint8_t fscod; /* bit stream identification 5 bits */ uint8_t bsid; /* one bit reserved */ /* audio service mixing (not supported yet) 1 bit */ /* bit stream mode 3 bits */ uint8_t bsmod; /* audio coding mode 3 bits */ uint8_t acmod; /* sub woofer on 1 bit */ uint8_t lfeon; /* 3 bits reserved */ /* number of dependent substreams associated with this substream 4 bits */ uint8_t num_dep_sub; /* channel locations of the dependent substream(s), if any, 9 bits */ uint16_t chan_loc; /* if there is no dependent substream, then one bit reserved instead */ } substream[1]; /* TODO: support 8 independent substreams */ }; #if CONFIG_AC3_PARSER static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { //info->num_ind_sub++; avpriv_request_sample(track->par, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; } #endif static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track) { PutBitContext pbc; uint8_t *buf; struct eac3_info *info; int size, i; if (!track->eac3_priv) return AVERROR(EINVAL); info = track->eac3_priv; size = 2 + 4 * (info->num_ind_sub + 1); buf = av_malloc(size); if (!buf) { size = AVERROR(ENOMEM); goto end; } init_put_bits(&pbc, buf, size); put_bits(&pbc, 13, info->data_rate); put_bits(&pbc, 3, info->num_ind_sub); for (i = 0; i <= info->num_ind_sub; i++) { put_bits(&pbc, 2, info->substream[i].fscod); put_bits(&pbc, 5, info->substream[i].bsid); put_bits(&pbc, 1, 0); /* reserved */ put_bits(&pbc, 1, 0); /* asvc */ put_bits(&pbc, 3, info->substream[i].bsmod); put_bits(&pbc, 3, info->substream[i].acmod); put_bits(&pbc, 1, info->substream[i].lfeon); put_bits(&pbc, 5, 0); /* reserved */ put_bits(&pbc, 4, info->substream[i].num_dep_sub); if (!info->substream[i].num_dep_sub) { put_bits(&pbc, 1, 0); /* reserved */ size--; } else { put_bits(&pbc, 9, info->substream[i].chan_loc); } } flush_put_bits(&pbc); avio_wb32(pb, size + 8); ffio_wfourcc(pb, "dec3"); avio_write(pb, buf, size); av_free(buf); end: av_packet_unref(&info->pkt); av_freep(&track->eac3_priv); return size; } /** * This function writes extradata "as is". * Extradata must be formatted like a valid atom (with size and tag). */ static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track) { avio_write(pb, track->par->extradata, track->par->extradata_size); return track->par->extradata_size; } static int mov_write_enda_tag(AVIOContext *pb) { avio_wb32(pb, 10); ffio_wfourcc(pb, "enda"); avio_wb16(pb, 1); /* little endian */ return 10; } static int mov_write_enda_tag_be(AVIOContext *pb) { avio_wb32(pb, 10); ffio_wfourcc(pb, "enda"); avio_wb16(pb, 0); /* big endian */ return 10; } static void put_descr(AVIOContext *pb, int tag, unsigned int size) { int i = 3; avio_w8(pb, tag); for (; i > 0; i--) avio_w8(pb, (size >> (7 * i)) | 0x80); avio_w8(pb, size & 0x7F); } static unsigned compute_avg_bitrate(MOVTrack *track) { uint64_t size = 0; int i; if (!track->track_duration) return 0; for (i = 0; i < track->entry; i++) size += track->cluster[i].size; return size * 8 * track->timescale / track->track_duration; } static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic { AVCPBProperties *props; int64_t pos = avio_tell(pb); int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0; unsigned avg_bitrate; avio_wb32(pb, 0); // size ffio_wfourcc(pb, "esds"); avio_wb32(pb, 0); // Version // ES descriptor put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1); avio_wb16(pb, track->track_id); avio_w8(pb, 0x00); // flags (= no flags) // DecoderConfig descriptor put_descr(pb, 0x04, 13 + decoder_specific_info_len); // Object type indication if ((track->par->codec_id == AV_CODEC_ID_MP2 || track->par->codec_id == AV_CODEC_ID_MP3) && track->par->sample_rate > 24000) avio_w8(pb, 0x6B); // 11172-3 else avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id)); // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio) // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved) if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream) else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) avio_w8(pb, 0x15); // flags (= Audiostream) else avio_w8(pb, 0x11); // flags (= Visualstream) props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL); avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB avg_bitrate = compute_avg_bitrate(track); avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window) avio_wb32(pb, avg_bitrate); if (track->vos_len) { // DecoderSpecific info descriptor put_descr(pb, 0x05, track->vos_len); avio_write(pb, track->vos_data, track->vos_len); } // SL descriptor put_descr(pb, 0x06, 1); avio_w8(pb, 0x02); return update_size(pb, pos); } static int mov_pcm_le_gt16(enum AVCodecID codec_id) { return codec_id == AV_CODEC_ID_PCM_S24LE || codec_id == AV_CODEC_ID_PCM_S32LE || codec_id == AV_CODEC_ID_PCM_F32LE || codec_id == AV_CODEC_ID_PCM_F64LE; } static int mov_pcm_be_gt16(enum AVCodecID codec_id) { return codec_id == AV_CODEC_ID_PCM_S24BE || codec_id == AV_CODEC_ID_PCM_S32BE || codec_id == AV_CODEC_ID_PCM_F32BE || codec_id == AV_CODEC_ID_PCM_F64BE; } static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int ret; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); avio_wl32(pb, track->tag); // store it byteswapped track->par->codec_tag = av_bswap16(track->tag >> 16); if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0) return ret; return update_size(pb, pos); } static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int ret; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "wfex"); if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0) return ret; return update_size(pb, pos); } static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "dfLa"); avio_w8(pb, 0); /* version */ avio_wb24(pb, 0); /* flags */ /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */ if (track->par->extradata_size != FLAC_STREAMINFO_SIZE) return AVERROR_INVALIDDATA; /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */ avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */ avio_wb24(pb, track->par->extradata_size); /* Length */ avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */ return update_size(pb, pos); } static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "dOps"); avio_w8(pb, 0); /* Version */ if (track->par->extradata_size < 19) { av_log(pb, AV_LOG_ERROR, "invalid extradata size\n"); return AVERROR_INVALIDDATA; } /* extradata contains an Ogg OpusHead, other than byte-ordering and OpusHead's preceeding magic/version, OpusSpecificBox is currently identical. */ avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */ avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */ avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */ avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */ /* Write the rest of the header out without byte-swapping. */ avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18); return update_size(pb, pos); } static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { uint32_t layout_tag, bitmap; int64_t pos = avio_tell(pb); layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id, track->par->channel_layout, &bitmap); if (!layout_tag) { av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to " "lack of channel information\n"); return 0; } if (track->multichannel_as_mono) return 0; avio_wb32(pb, 0); // Size ffio_wfourcc(pb, "chan"); // Type avio_w8(pb, 0); // Version avio_wb24(pb, 0); // Flags avio_wb32(pb, layout_tag); // mChannelLayoutTag avio_wb32(pb, bitmap); // mChannelBitmap avio_wb32(pb, 0); // mNumberChannelDescriptions return update_size(pb, pos); } static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "wave"); if (track->par->codec_id != AV_CODEC_ID_QDM2) { avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "frma"); avio_wl32(pb, track->tag); } if (track->par->codec_id == AV_CODEC_ID_AAC) { /* useless atom needed by mplayer, ipod, not needed by quicktime */ avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "mp4a"); avio_wb32(pb, 0); mov_write_esds_tag(pb, track); } else if (mov_pcm_le_gt16(track->par->codec_id)) { mov_write_enda_tag(pb); } else if (mov_pcm_be_gt16(track->par->codec_id)) { mov_write_enda_tag_be(pb); } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) { mov_write_amr_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_AC3) { mov_write_ac3_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_EAC3) { mov_write_eac3_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_ALAC || track->par->codec_id == AV_CODEC_ID_QDM2) { mov_write_extradata_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) { mov_write_ms_tag(s, pb, track); } avio_wb32(pb, 8); /* size */ avio_wb32(pb, 0); /* null tag */ return update_size(pb, pos); } static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf) { uint8_t *unescaped; const uint8_t *start, *next, *end = track->vos_data + track->vos_len; int unescaped_size, seq_found = 0; int level = 0, interlace = 0; int packet_seq = track->vc1_info.packet_seq; int packet_entry = track->vc1_info.packet_entry; int slices = track->vc1_info.slices; PutBitContext pbc; if (track->start_dts == AV_NOPTS_VALUE) { /* No packets written yet, vc1_info isn't authoritative yet. */ /* Assume inline sequence and entry headers. */ packet_seq = packet_entry = 1; av_log(NULL, AV_LOG_WARNING, "moov atom written before any packets, unable to write correct " "dvc1 atom. Set the delay_moov flag to fix this.\n"); } unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE); if (!unescaped) return AVERROR(ENOMEM); start = find_next_marker(track->vos_data, end); for (next = start; next < end; start = next) { GetBitContext gb; int size; next = find_next_marker(start + 4, end); size = next - start - 4; if (size <= 0) continue; unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped); init_get_bits(&gb, unescaped, 8 * unescaped_size); if (AV_RB32(start) == VC1_CODE_SEQHDR) { int profile = get_bits(&gb, 2); if (profile != PROFILE_ADVANCED) { av_free(unescaped); return AVERROR(ENOSYS); } seq_found = 1; level = get_bits(&gb, 3); /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag, * width, height */ skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12); skip_bits(&gb, 1); /* broadcast */ interlace = get_bits1(&gb); skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */ } } if (!seq_found) { av_free(unescaped); return AVERROR(ENOSYS); } init_put_bits(&pbc, buf, 7); /* VC1DecSpecStruc */ put_bits(&pbc, 4, 12); /* profile - advanced */ put_bits(&pbc, 3, level); put_bits(&pbc, 1, 0); /* reserved */ /* VC1AdvDecSpecStruc */ put_bits(&pbc, 3, level); put_bits(&pbc, 1, 0); /* cbr */ put_bits(&pbc, 6, 0); /* reserved */ put_bits(&pbc, 1, !interlace); /* no interlace */ put_bits(&pbc, 1, !packet_seq); /* no multiple seq */ put_bits(&pbc, 1, !packet_entry); /* no multiple entry */ put_bits(&pbc, 1, !slices); /* no slice code */ put_bits(&pbc, 1, 0); /* no bframe */ put_bits(&pbc, 1, 0); /* reserved */ /* framerate */ if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0) put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den); else put_bits32(&pbc, 0xffffffff); flush_put_bits(&pbc); av_free(unescaped); return 0; } static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track) { uint8_t buf[7] = { 0 }; int ret; if ((ret = mov_write_dvc1_structs(track, buf)) < 0) return ret; avio_wb32(pb, track->vos_len + 8 + sizeof(buf)); ffio_wfourcc(pb, "dvc1"); avio_write(pb, buf, sizeof(buf)); avio_write(pb, track->vos_data, track->vos_len); return 0; } static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, track->vos_len + 8); ffio_wfourcc(pb, "glbl"); avio_write(pb, track->vos_data, track->vos_len); return 8 + track->vos_len; } /** * Compute flags for 'lpcm' tag. * See CoreAudioTypes and AudioStreamBasicDescription at Apple. */ static int mov_get_lpcm_flags(enum AVCodecID codec_id) { switch (codec_id) { case AV_CODEC_ID_PCM_F32BE: case AV_CODEC_ID_PCM_F64BE: return 11; case AV_CODEC_ID_PCM_F32LE: case AV_CODEC_ID_PCM_F64LE: return 9; case AV_CODEC_ID_PCM_U8: return 10; case AV_CODEC_ID_PCM_S16BE: case AV_CODEC_ID_PCM_S24BE: case AV_CODEC_ID_PCM_S32BE: return 14; case AV_CODEC_ID_PCM_S8: case AV_CODEC_ID_PCM_S16LE: case AV_CODEC_ID_PCM_S24LE: case AV_CODEC_ID_PCM_S32LE: return 12; default: return 0; } } static int get_cluster_duration(MOVTrack *track, int cluster_idx) { int64_t next_dts; if (cluster_idx >= track->entry) return 0; if (cluster_idx + 1 == track->entry) next_dts = track->track_duration + track->start_dts; else next_dts = track->cluster[cluster_idx + 1].dts; next_dts -= track->cluster[cluster_idx].dts; av_assert0(next_dts >= 0); av_assert0(next_dts <= INT_MAX); return next_dts; } static int get_samples_per_packet(MOVTrack *track) { int i, first_duration; // return track->par->frame_size; /* use 1 for raw PCM */ if (!track->audio_vbr) return 1; /* check to see if duration is constant for all clusters */ if (!track->entry) return 0; first_duration = get_cluster_duration(track, 0); for (i = 1; i < track->entry; i++) { if (get_cluster_duration(track, i) != first_duration) return 0; } return first_duration; } static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int version = 0; uint32_t tag = track->tag; if (track->mode == MODE_MOV) { if (track->timescale > UINT16_MAX) { if (mov_get_lpcm_flags(track->par->codec_id)) tag = AV_RL32("lpcm"); version = 2; } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) || mov_pcm_be_gt16(track->par->codec_id) || track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || track->par->codec_id == AV_CODEC_ID_QDM2) { version = 1; } } avio_wb32(pb, 0); /* size */ if (mov->encryption_scheme != MOV_ENC_NONE) { ffio_wfourcc(pb, "enca"); } else { avio_wl32(pb, tag); // store it byteswapped } avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */ /* SoundDescription */ avio_wb16(pb, version); /* Version */ avio_wb16(pb, 0); /* Revision level */ avio_wb32(pb, 0); /* Reserved */ if (version == 2) { avio_wb16(pb, 3); avio_wb16(pb, 16); avio_wb16(pb, 0xfffe); avio_wb16(pb, 0); avio_wb32(pb, 0x00010000); avio_wb32(pb, 72); avio_wb64(pb, av_double2int(track->par->sample_rate)); avio_wb32(pb, track->par->channels); avio_wb32(pb, 0x7F000000); avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id)); avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id)); avio_wb32(pb, track->sample_size); avio_wb32(pb, get_samples_per_packet(track)); } else { if (track->mode == MODE_MOV) { avio_wb16(pb, track->par->channels); if (track->par->codec_id == AV_CODEC_ID_PCM_U8 || track->par->codec_id == AV_CODEC_ID_PCM_S8) avio_wb16(pb, 8); /* bits per sample */ else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726) avio_wb16(pb, track->par->bits_per_coded_sample); else avio_wb16(pb, 16); avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */ } else { /* reserved for mp4/3gp */ if (track->par->codec_id == AV_CODEC_ID_FLAC || track->par->codec_id == AV_CODEC_ID_OPUS) { avio_wb16(pb, track->par->channels); } else { avio_wb16(pb, 2); } if (track->par->codec_id == AV_CODEC_ID_FLAC) { avio_wb16(pb, track->par->bits_per_raw_sample); } else { avio_wb16(pb, 16); } avio_wb16(pb, 0); } avio_wb16(pb, 0); /* packet size (= 0) */ if (track->par->codec_id == AV_CODEC_ID_OPUS) avio_wb16(pb, 48000); else avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ? track->par->sample_rate : 0); avio_wb16(pb, 0); /* Reserved */ } if (version == 1) { /* SoundDescription V1 extended info */ if (mov_pcm_le_gt16(track->par->codec_id) || mov_pcm_be_gt16(track->par->codec_id)) avio_wb32(pb, 1); /* must be 1 for uncompressed formats */ else avio_wb32(pb, track->par->frame_size); /* Samples per packet */ avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */ avio_wb32(pb, track->sample_size); /* Bytes per frame */ avio_wb32(pb, 2); /* Bytes per sample */ } if (track->mode == MODE_MOV && (track->par->codec_id == AV_CODEC_ID_AAC || track->par->codec_id == AV_CODEC_ID_AC3 || track->par->codec_id == AV_CODEC_ID_EAC3 || track->par->codec_id == AV_CODEC_ID_AMR_NB || track->par->codec_id == AV_CODEC_ID_ALAC || track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || track->par->codec_id == AV_CODEC_ID_QDM2 || (mov_pcm_le_gt16(track->par->codec_id) && version==1) || (mov_pcm_be_gt16(track->par->codec_id) && version==1))) mov_write_wave_tag(s, pb, track); else if (track->tag == MKTAG('m','p','4','a')) mov_write_esds_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) mov_write_amr_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_AC3) mov_write_ac3_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_EAC3) mov_write_eac3_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_ALAC) mov_write_extradata_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) mov_write_wfex_tag(s, pb, track); else if (track->par->codec_id == AV_CODEC_ID_FLAC) mov_write_dfla_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_OPUS) mov_write_dops_tag(pb, track); else if (track->vos_len > 0) mov_write_glbl_tag(pb, track); if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_chan_tag(s, pb, track); if (mov->encryption_scheme != MOV_ENC_NONE) { ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid); } return update_size(pb, pos); } static int mov_write_d263_tag(AVIOContext *pb) { avio_wb32(pb, 0xf); /* size */ ffio_wfourcc(pb, "d263"); ffio_wfourcc(pb, "FFMP"); avio_w8(pb, 0); /* decoder version */ /* FIXME use AVCodecContext level/profile, when encoder will set values */ avio_w8(pb, 0xa); /* level */ avio_w8(pb, 0); /* profile */ return 0xf; } static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "avcC"); ff_isom_write_avcc(pb, track->vos_data, track->vos_len); return update_size(pb, pos); } static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "vpcC"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); /* flags */ ff_isom_write_vpcc(s, pb, track->par); return update_size(pb, pos); } static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "hvcC"); if (track->tag == MKTAG('h','v','c','1')) ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1); else ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0); return update_size(pb, pos); } /* also used by all avid codecs (dv, imx, meridien) and their variants */ static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track) { int i; int interlaced; int cid; int display_width = track->par->width; if (track->vos_data && track->vos_len > 0x29) { if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) { /* looks like a DNxHD bit stream */ interlaced = (track->vos_data[5] & 2); cid = AV_RB32(track->vos_data + 0x28); } else { av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n"); return 0; } } else { av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n"); return 0; } avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "ACLR"); ffio_wfourcc(pb, "ACLR"); ffio_wfourcc(pb, "0001"); if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */ track->par->color_range == AVCOL_RANGE_UNSPECIFIED) { avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */ } else { /* Full range (0-255) */ avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */ } avio_wb32(pb, 0); /* unknown */ if (track->tag == MKTAG('A','V','d','h')) { avio_wb32(pb, 32); ffio_wfourcc(pb, "ADHR"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, cid); avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 0); /* unknown */ return 0; } avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "APRG"); ffio_wfourcc(pb, "APRG"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 120); /* size */ ffio_wfourcc(pb, "ARES"); ffio_wfourcc(pb, "ARES"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, cid); /* dnxhd cid, some id ? */ if ( track->par->sample_aspect_ratio.num > 0 && track->par->sample_aspect_ratio.den > 0) display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den; avio_wb32(pb, display_width); /* values below are based on samples created with quicktime and avid codecs */ if (interlaced) { avio_wb32(pb, track->par->height / 2); avio_wb32(pb, 2); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 4); /* unknown */ } else { avio_wb32(pb, track->par->height); avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ if (track->par->height == 1080) avio_wb32(pb, 5); /* unknown */ else avio_wb32(pb, 6); /* unknown */ } /* padding */ for (i = 0; i < 10; i++) avio_wb64(pb, 0); return 0; } static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 12); ffio_wfourcc(pb, "DpxE"); if (track->par->extradata_size >= 12 && !memcmp(&track->par->extradata[4], "DpxE", 4)) { avio_wb32(pb, track->par->extradata[11]); } else { avio_wb32(pb, 1); } return 0; } static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag; if (track->par->width == 720) { /* SD */ if (track->par->height == 480) { /* NTSC */ if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n'); else tag = MKTAG('d','v','c',' '); }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p'); else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p'); else tag = MKTAG('d','v','p','p'); } else if (track->par->height == 720) { /* HD 720 line */ if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q'); else tag = MKTAG('d','v','h','p'); } else if (track->par->height == 1080) { /* HD 1080 line */ if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5'); else tag = MKTAG('d','v','h','6'); } else { av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n"); return 0; } return tag; } static AVRational find_fps(AVFormatContext *s, AVStream *st) { AVRational rate = st->avg_frame_rate; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS rate = av_inv_q(st->codec->time_base); if (av_timecode_check_frame_rate(rate) < 0) { av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n", rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den); rate = st->avg_frame_rate; } FF_ENABLE_DEPRECATION_WARNINGS #endif return rate; } static int defined_frame_rate(AVFormatContext *s, AVStream *st) { AVRational rational_framerate = find_fps(s, st); int rate = 0; if (rational_framerate.den != 0) rate = av_q2d(rational_framerate); return rate; } static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(s, st); if (!tag) tag = MKTAG('m', '2', 'v', '1'); //fallback tag if (track->par->format == AV_PIX_FMT_YUV420P) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','4'); else if (rate == 25) tag = MKTAG('x','d','v','5'); else if (rate == 30) tag = MKTAG('x','d','v','1'); else if (rate == 50) tag = MKTAG('x','d','v','a'); else if (rate == 60) tag = MKTAG('x','d','v','9'); } } else if (track->par->width == 1440 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','6'); else if (rate == 25) tag = MKTAG('x','d','v','7'); else if (rate == 30) tag = MKTAG('x','d','v','8'); } else { if (rate == 25) tag = MKTAG('x','d','v','3'); else if (rate == 30) tag = MKTAG('x','d','v','2'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','d'); else if (rate == 25) tag = MKTAG('x','d','v','e'); else if (rate == 30) tag = MKTAG('x','d','v','f'); } else { if (rate == 25) tag = MKTAG('x','d','v','c'); else if (rate == 30) tag = MKTAG('x','d','v','b'); } } } else if (track->par->format == AV_PIX_FMT_YUV422P) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','5','4'); else if (rate == 25) tag = MKTAG('x','d','5','5'); else if (rate == 30) tag = MKTAG('x','d','5','1'); else if (rate == 50) tag = MKTAG('x','d','5','a'); else if (rate == 60) tag = MKTAG('x','d','5','9'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','5','d'); else if (rate == 25) tag = MKTAG('x','d','5','e'); else if (rate == 30) tag = MKTAG('x','d','5','f'); } else { if (rate == 25) tag = MKTAG('x','d','5','c'); else if (rate == 30) tag = MKTAG('x','d','5','b'); } } } return tag; } static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(s, st); if (!tag) tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag if (track->par->format == AV_PIX_FMT_YUV420P10) { if (track->par->width == 960 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','5','p'); else if (rate == 25) tag = MKTAG('a','i','5','q'); else if (rate == 30) tag = MKTAG('a','i','5','p'); else if (rate == 50) tag = MKTAG('a','i','5','q'); else if (rate == 60) tag = MKTAG('a','i','5','p'); } } else if (track->par->width == 1440 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','5','3'); else if (rate == 25) tag = MKTAG('a','i','5','2'); else if (rate == 30) tag = MKTAG('a','i','5','3'); } else { if (rate == 50) tag = MKTAG('a','i','5','5'); else if (rate == 60) tag = MKTAG('a','i','5','6'); } } } else if (track->par->format == AV_PIX_FMT_YUV422P10) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','1','p'); else if (rate == 25) tag = MKTAG('a','i','1','q'); else if (rate == 30) tag = MKTAG('a','i','1','p'); else if (rate == 50) tag = MKTAG('a','i','1','q'); else if (rate == 60) tag = MKTAG('a','i','1','p'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','1','3'); else if (rate == 25) tag = MKTAG('a','i','1','2'); else if (rate == 30) tag = MKTAG('a','i','1','3'); } else { if (rate == 25) tag = MKTAG('a','i','1','5'); else if (rate == 50) tag = MKTAG('a','i','1','5'); else if (rate == 60) tag = MKTAG('a','i','1','6'); } } else if ( track->par->width == 4096 && track->par->height == 2160 || track->par->width == 3840 && track->par->height == 2160 || track->par->width == 2048 && track->par->height == 1080) { tag = MKTAG('a','i','v','x'); } } return tag; } static const struct { enum AVPixelFormat pix_fmt; uint32_t tag; unsigned bps; } mov_pix_fmt_tags[] = { { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 }, { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 }, { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 }, { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 }, { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 }, { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 }, { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 }, { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 }, { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 }, { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 }, { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 }, { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 }, { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 }, { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 }, { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 }, }; static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = MKTAG('A','V','d','n'); if (track->par->profile != FF_PROFILE_UNKNOWN && track->par->profile != FF_PROFILE_DNXHD) tag = MKTAG('A','V','d','h'); return tag; } static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int i; enum AVPixelFormat pix_fmt; for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) { if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) { tag = mov_pix_fmt_tags[i].tag; track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps; if (track->par->codec_tag == mov_pix_fmt_tags[i].tag) break; } } pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov, track->par->bits_per_coded_sample); if (tag == MKTAG('r','a','w',' ') && track->par->format != pix_fmt && track->par->format != AV_PIX_FMT_GRAY8 && track->par->format != AV_PIX_FMT_NONE) av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n", av_get_pix_fmt_name(track->par->format)); return tag; } static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL && (track->par->codec_id == AV_CODEC_ID_DVVIDEO || track->par->codec_id == AV_CODEC_ID_RAWVIDEO || track->par->codec_id == AV_CODEC_ID_H263 || track->par->codec_id == AV_CODEC_ID_H264 || track->par->codec_id == AV_CODEC_ID_DNXHD || track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO || av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio if (track->par->codec_id == AV_CODEC_ID_DVVIDEO) tag = mov_get_dv_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) tag = mov_get_rawvideo_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO) tag = mov_get_mpeg2_xdcam_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_H264) tag = mov_get_h264_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_DNXHD) tag = mov_get_dnxhd_codec_tag(s, track); else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id); if (!tag) { // if no mac fcc found, try with Microsoft tags tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id); if (tag) av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, " "the file may be unplayable!\n"); } } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id); if (!tag) { // if no mac fcc found, try with Microsoft tags int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id); if (ms_tag) { tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff)); av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, " "the file may be unplayable!\n"); } } } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id); } return tag; } static const AVCodecTag codec_cover_image_tags[] = { { AV_CODEC_ID_MJPEG, 0xD }, { AV_CODEC_ID_PNG, 0xE }, { AV_CODEC_ID_BMP, 0x1B }, { AV_CODEC_ID_NONE, 0 }, }; static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag; if (is_cover_image(track->st)) return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id); if (track->mode == MODE_MP4 || track->mode == MODE_PSP) tag = track->par->codec_tag; else if (track->mode == MODE_ISM) tag = track->par->codec_tag; else if (track->mode == MODE_IPOD) { if (!av_match_ext(s->url, "m4a") && !av_match_ext(s->url, "m4v") && !av_match_ext(s->url, "m4b")) av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v " "Quicktime/Ipod might not play the file\n"); tag = track->par->codec_tag; } else if (track->mode & MODE_3GP) tag = track->par->codec_tag; else if (track->mode == MODE_F4V) tag = track->par->codec_tag; else tag = mov_get_codec_tag(s, track); return tag; } /** Write uuid atom. * Needed to make file play in iPods running newest firmware * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1 */ static int mov_write_uuid_tag_ipod(AVIOContext *pb) { avio_wb32(pb, 28); ffio_wfourcc(pb, "uuid"); avio_wb32(pb, 0x6b6840f2); avio_wb32(pb, 0x5f244fc5); avio_wb32(pb, 0xba39a51b); avio_wb32(pb, 0xcf0323f3); avio_wb32(pb, 0x0); return 28; } static const uint16_t fiel_data[] = { 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e }; static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order) { unsigned mov_field_order = 0; if (field_order < FF_ARRAY_ELEMS(fiel_data)) mov_field_order = fiel_data[field_order]; else return 0; avio_wb32(pb, 10); ffio_wfourcc(pb, "fiel"); avio_wb16(pb, mov_field_order); return 10; } static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ avio_wl32(pb, track->tag); // store it byteswapped avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) mov_write_esds_tag(pb, track); else if (track->par->extradata_size) avio_write(pb, track->par->extradata, track->par->extradata_size); return update_size(pb, pos); } static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d) { int8_t stereo_mode; if (stereo_3d->flags != 0) { av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags); return 0; } switch (stereo_3d->type) { case AV_STEREO3D_2D: stereo_mode = 0; break; case AV_STEREO3D_TOPBOTTOM: stereo_mode = 1; break; case AV_STEREO3D_SIDEBYSIDE: stereo_mode = 2; break; default: av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type)); return 0; } avio_wb32(pb, 13); /* size */ ffio_wfourcc(pb, "st3d"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_w8(pb, stereo_mode); return 13; } static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping) { int64_t sv3d_pos, svhd_pos, proj_pos; const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT; if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR && spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE && spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) { av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection); return 0; } sv3d_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "sv3d"); svhd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "svhd"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_put_str(pb, metadata_source); update_size(pb, svhd_pos); proj_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "proj"); avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "prhd"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, spherical_mapping->yaw); avio_wb32(pb, spherical_mapping->pitch); avio_wb32(pb, spherical_mapping->roll); switch (spherical_mapping->projection) { case AV_SPHERICAL_EQUIRECTANGULAR: case AV_SPHERICAL_EQUIRECTANGULAR_TILE: avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "equi"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, spherical_mapping->bound_top); avio_wb32(pb, spherical_mapping->bound_bottom); avio_wb32(pb, spherical_mapping->bound_left); avio_wb32(pb, spherical_mapping->bound_right); break; case AV_SPHERICAL_CUBEMAP: avio_wb32(pb, 20); /* size */ ffio_wfourcc(pb, "cbmp"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, 0); /* layout */ avio_wb32(pb, spherical_mapping->padding); /* padding */ break; } update_size(pb, proj_pos); return update_size(pb, sv3d_pos); } static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 40); ffio_wfourcc(pb, "clap"); avio_wb32(pb, track->par->width); /* apertureWidth_N */ avio_wb32(pb, 1); /* apertureWidth_D (= 1) */ avio_wb32(pb, track->height); /* apertureHeight_N */ avio_wb32(pb, 1); /* apertureHeight_D (= 1) */ avio_wb32(pb, 0); /* horizOff_N (= 0) */ avio_wb32(pb, 1); /* horizOff_D (= 1) */ avio_wb32(pb, 0); /* vertOff_N (= 0) */ avio_wb32(pb, 1); /* vertOff_D (= 1) */ return 40; } static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track) { AVRational sar; av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num, track->par->sample_aspect_ratio.den, INT_MAX); avio_wb32(pb, 16); ffio_wfourcc(pb, "pasp"); avio_wb32(pb, sar.num); avio_wb32(pb, sar.den); return 16; } static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma) { uint32_t gama = 0; if (gamma <= 0.0) { gamma = avpriv_get_gamma_from_trc(track->par->color_trc); } av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma); if (gamma > 1e-6) { gama = (uint32_t)lrint((double)(1<<16) * gamma); av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama); av_assert0(track->mode == MODE_MOV); avio_wb32(pb, 12); ffio_wfourcc(pb, "gama"); avio_wb32(pb, gama); return 12; } else { av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n"); } return 0; } static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track) { // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9 // Ref (MP4): ISO/IEC 14496-12:2012 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED && track->par->color_trc == AVCOL_TRC_UNSPECIFIED && track->par->color_space == AVCOL_SPC_UNSPECIFIED) { if ((track->par->width >= 1920 && track->par->height >= 1080) || (track->par->width == 1280 && track->par->height == 720)) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n"); track->par->color_primaries = AVCOL_PRI_BT709; } else if (track->par->width == 720 && track->height == 576) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n"); track->par->color_primaries = AVCOL_PRI_BT470BG; } else if (track->par->width == 720 && (track->height == 486 || track->height == 480)) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n"); track->par->color_primaries = AVCOL_PRI_SMPTE170M; } else { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n"); } switch (track->par->color_primaries) { case AVCOL_PRI_BT709: track->par->color_trc = AVCOL_TRC_BT709; track->par->color_space = AVCOL_SPC_BT709; break; case AVCOL_PRI_SMPTE170M: case AVCOL_PRI_BT470BG: track->par->color_trc = AVCOL_TRC_BT709; track->par->color_space = AVCOL_SPC_SMPTE170M; break; } } /* We should only ever be called by MOV or MP4. */ av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4); avio_wb32(pb, 18 + (track->mode == MODE_MP4)); ffio_wfourcc(pb, "colr"); if (track->mode == MODE_MP4) ffio_wfourcc(pb, "nclx"); else ffio_wfourcc(pb, "nclc"); switch (track->par->color_primaries) { case AVCOL_PRI_BT709: avio_wb16(pb, 1); break; case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break; case AVCOL_PRI_SMPTE170M: case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break; case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break; case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break; case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break; default: avio_wb16(pb, 2); } switch (track->par->color_trc) { case AVCOL_TRC_BT709: avio_wb16(pb, 1); break; case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break; case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break; case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break; case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break; default: avio_wb16(pb, 2); } switch (track->par->color_space) { case AVCOL_SPC_BT709: avio_wb16(pb, 1); break; case AVCOL_SPC_BT470BG: case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break; case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break; case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break; default: avio_wb16(pb, 2); } if (track->mode == MODE_MP4) { int full_range = track->par->color_range == AVCOL_RANGE_JPEG; avio_w8(pb, full_range << 7); return 19; } else { return 18; } } static void find_compressor(char * compressor_name, int len, MOVTrack *track) { AVDictionaryEntry *encoder; int xdcam_res = (track->par->width == 1280 && track->par->height == 720) || (track->par->width == 1440 && track->par->height == 1080) || (track->par->width == 1920 && track->par->height == 1080); if (track->mode == MODE_MOV && (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) { av_strlcpy(compressor_name, encoder->value, 32); } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) { int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(NULL, st); av_strlcatf(compressor_name, len, "XDCAM"); if (track->par->format == AV_PIX_FMT_YUV422P) { av_strlcatf(compressor_name, len, " HD422"); } else if(track->par->width == 1440) { av_strlcatf(compressor_name, len, " HD"); } else av_strlcatf(compressor_name, len, " EX"); av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p'); av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1)); } } static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); char compressor_name[32] = { 0 }; int avid = 0; int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422) || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422) || track->par->codec_id == AV_CODEC_ID_V308 || track->par->codec_id == AV_CODEC_ID_V408 || track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210); avio_wb32(pb, 0); /* size */ if (mov->encryption_scheme != MOV_ENC_NONE) { ffio_wfourcc(pb, "encv"); } else { avio_wl32(pb, track->tag); // store it byteswapped } avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ if (uncompressed_ycbcr) { avio_wb16(pb, 2); /* Codec stream version */ } else { avio_wb16(pb, 0); /* Codec stream version */ } avio_wb16(pb, 0); /* Codec stream revision (=0) */ if (track->mode == MODE_MOV) { ffio_wfourcc(pb, "FFMP"); /* Vendor */ if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) { avio_wb32(pb, 0); /* Temporal Quality */ avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/ } else { avio_wb32(pb, 0x200); /* Temporal Quality = normal */ avio_wb32(pb, 0x200); /* Spatial Quality = normal */ } } else { avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 0); /* Reserved */ } avio_wb16(pb, track->par->width); /* Video width */ avio_wb16(pb, track->height); /* Video height */ avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */ avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */ avio_wb32(pb, 0); /* Data size (= 0) */ avio_wb16(pb, 1); /* Frame count (= 1) */ /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */ find_compressor(compressor_name, 32, track); avio_w8(pb, strlen(compressor_name)); avio_write(pb, compressor_name, 31); if (track->mode == MODE_MOV && (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210)) avio_wb16(pb, 0x18); else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample) avio_wb16(pb, track->par->bits_per_coded_sample | (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0)); else avio_wb16(pb, 0x18); /* Reserved */ if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) { int pal_size = 1 << track->par->bits_per_coded_sample; int i; avio_wb16(pb, 0); /* Color table ID */ avio_wb32(pb, 0); /* Color table seed */ avio_wb16(pb, 0x8000); /* Color table flags */ avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */ for (i = 0; i < pal_size; i++) { uint32_t rgb = track->palette[i]; uint16_t r = (rgb >> 16) & 0xff; uint16_t g = (rgb >> 8) & 0xff; uint16_t b = rgb & 0xff; avio_wb16(pb, 0); avio_wb16(pb, (r << 8) | r); avio_wb16(pb, (g << 8) | g); avio_wb16(pb, (b << 8) | b); } } else avio_wb16(pb, 0xffff); /* Reserved */ if (track->tag == MKTAG('m','p','4','v')) mov_write_esds_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_H263) mov_write_d263_tag(pb); else if (track->par->codec_id == AV_CODEC_ID_AVUI || track->par->codec_id == AV_CODEC_ID_SVQ3) { mov_write_extradata_tag(pb, track); avio_wb32(pb, 0); } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) { mov_write_avid_tag(pb, track); avid = 1; } else if (track->par->codec_id == AV_CODEC_ID_HEVC) mov_write_hvcc_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) { mov_write_avcc_tag(pb, track); if (track->mode == MODE_IPOD) mov_write_uuid_tag_ipod(pb); } else if (track->par->codec_id == AV_CODEC_ID_VP9) { mov_write_vpcc_tag(mov->fc, pb, track); } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0) mov_write_dvc1_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_VP6F || track->par->codec_id == AV_CODEC_ID_VP6A) { /* Don't write any potential extradata here - the cropping * is signalled via the normal width/height fields. */ } else if (track->par->codec_id == AV_CODEC_ID_R10K) { if (track->par->codec_tag == MKTAG('R','1','0','k')) mov_write_dpxe_tag(pb, track); } else if (track->vos_len > 0) mov_write_glbl_tag(pb, track); if (track->par->codec_id != AV_CODEC_ID_H264 && track->par->codec_id != AV_CODEC_ID_MPEG4 && track->par->codec_id != AV_CODEC_ID_DNXHD) { int field_order = track->par->field_order; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN) field_order = track->st->codec->field_order; FF_ENABLE_DEPRECATION_WARNINGS #endif if (field_order != AV_FIELD_UNKNOWN) mov_write_fiel_tag(pb, track, field_order); } if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) { if (track->mode == MODE_MOV) mov_write_gama_tag(pb, track, mov->gamma); else av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n"); } if (mov->flags & FF_MOV_FLAG_WRITE_COLR) { if (track->mode == MODE_MOV || track->mode == MODE_MP4) mov_write_colr_tag(pb, track); else av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n"); } if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) { AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL); AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL); if (stereo_3d) mov_write_st3d_tag(pb, stereo_3d); if (spherical_mapping) mov_write_sv3d_tag(mov->fc, pb, spherical_mapping); } if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) { mov_write_pasp_tag(pb, track); } if (uncompressed_ycbcr){ mov_write_clap_tag(pb, track); } if (mov->encryption_scheme != MOV_ENC_NONE) { ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid); } /* extra padding for avid stsd */ /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */ if (avid) avio_wb32(pb, 0); return update_size(pb, pos); } static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "rtp "); avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ avio_wb16(pb, 1); /* Hint track version */ avio_wb16(pb, 1); /* Highest compatible version */ avio_wb32(pb, track->max_packet_size); /* Max packet size */ avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "tims"); avio_wb32(pb, track->timescale); return update_size(pb, pos); } static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name) { uint64_t str_size =strlen(reel_name); int64_t pos = avio_tell(pb); if (str_size >= UINT16_MAX){ av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size); avio_wb16(pb, 0); return AVERROR(EINVAL); } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "name"); /* Data format */ avio_wb16(pb, str_size); /* string size */ avio_wb16(pb, track->language); /* langcode */ avio_write(pb, reel_name, str_size); /* reel name */ return update_size(pb,pos); } static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); #if 1 int frame_duration; int nb_frames; AVDictionaryEntry *t = NULL; if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) { #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den); nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num); FF_ENABLE_DEPRECATION_WARNINGS #else av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n"); return AVERROR(EINVAL); #endif } else { frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den); nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num); } if (nb_frames > 255) { av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames); return AVERROR(EINVAL); } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); /* Data format */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 1); /* Data reference index */ avio_wb32(pb, 0); /* Flags */ avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */ avio_wb32(pb, track->timescale); /* Timescale */ avio_wb32(pb, frame_duration); /* Frame duration */ avio_w8(pb, nb_frames); /* Number of frames */ avio_w8(pb, 0); /* Reserved */ t = av_dict_get(track->st->metadata, "reel_name", NULL, 0); if (t && utf8len(t->value) && track->mode != MODE_MP4) mov_write_source_reference_tag(pb, track, t->value); else avio_wb16(pb, 0); /* zero size */ #else avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); /* Data format */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 1); /* Data reference index */ if (track->par->extradata_size) avio_write(pb, track->par->extradata, track->par->extradata_size); #endif return update_size(pb, pos); } static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gpmd"); avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ avio_wb32(pb, 0); /* Reserved */ return update_size(pb, pos); } static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsd"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, 1); /* entry count */ if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) mov_write_video_tag(pb, mov, track); else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_audio_tag(s, pb, mov, track); else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) mov_write_subtitle_tag(pb, track); else if (track->par->codec_tag == MKTAG('r','t','p',' ')) mov_write_rtp_tag(pb, track); else if (track->par->codec_tag == MKTAG('t','m','c','d')) mov_write_tmcd_tag(pb, track); else if (track->par->codec_tag == MKTAG('g','p','m','d')) mov_write_gpmd_tag(pb, track); return update_size(pb, pos); } static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; MOVStts *ctts_entries; uint32_t entries = 0; uint32_t atom_size; int i; ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */ if (!ctts_entries) return AVERROR(ENOMEM); ctts_entries[0].count = 1; ctts_entries[0].duration = track->cluster[0].cts; for (i = 1; i < track->entry; i++) { if (track->cluster[i].cts == ctts_entries[entries].duration) { ctts_entries[entries].count++; /* compress */ } else { entries++; ctts_entries[entries].duration = track->cluster[i].cts; ctts_entries[entries].count = 1; } } entries++; /* last one */ atom_size = 16 + (entries * 8); avio_wb32(pb, atom_size); /* size */ ffio_wfourcc(pb, "ctts"); if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) avio_w8(pb, 1); /* version */ else avio_w8(pb, 0); /* version */ avio_wb24(pb, 0); /* flags */ avio_wb32(pb, entries); /* entry count */ for (i = 0; i < entries; i++) { avio_wb32(pb, ctts_entries[i].count); avio_wb32(pb, ctts_entries[i].duration); } av_free(ctts_entries); return atom_size; } /* Time to sample atom */ static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track) { MOVStts *stts_entries = NULL; uint32_t entries = -1; uint32_t atom_size; int i; if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) { stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */ if (!stts_entries) return AVERROR(ENOMEM); stts_entries[0].count = track->sample_count; stts_entries[0].duration = 1; entries = 1; } else { if (track->entry) { stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */ if (!stts_entries) return AVERROR(ENOMEM); } for (i = 0; i < track->entry; i++) { int duration = get_cluster_duration(track, i); if (i && duration == stts_entries[entries].duration) { stts_entries[entries].count++; /* compress */ } else { entries++; stts_entries[entries].duration = duration; stts_entries[entries].count = 1; } } entries++; /* last one */ } atom_size = 16 + (entries * 8); avio_wb32(pb, atom_size); /* size */ ffio_wfourcc(pb, "stts"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, entries); /* entry count */ for (i = 0; i < entries; i++) { avio_wb32(pb, stts_entries[i].count); avio_wb32(pb, stts_entries[i].duration); } av_free(stts_entries); return atom_size; } static int mov_write_dref_tag(AVIOContext *pb) { avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "dref"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, 1); /* entry count */ avio_wb32(pb, 0xc); /* size */ //FIXME add the alis and rsrc atom ffio_wfourcc(pb, "url "); avio_wb32(pb, 1); /* version & flags */ return 28; } static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track) { struct sgpd_entry { int count; int16_t roll_distance; int group_description_index; }; struct sgpd_entry *sgpd_entries = NULL; int entries = -1; int group = 0; int i, j; const int OPUS_SEEK_PREROLL_MS = 80; int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS, (AVRational){1, 1000}, (AVRational){1, 48000}); if (!track->entry) return 0; sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries)); if (!sgpd_entries) return AVERROR(ENOMEM); av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC); if (track->par->codec_id == AV_CODEC_ID_OPUS) { for (i = 0; i < track->entry; i++) { int roll_samples_remaining = roll_samples; int distance = 0; for (j = i - 1; j >= 0; j--) { roll_samples_remaining -= get_cluster_duration(track, j); distance++; if (roll_samples_remaining <= 0) break; } /* We don't have enough preceeding samples to compute a valid roll_distance here, so this sample can't be independently decoded. */ if (roll_samples_remaining > 0) distance = 0; /* Verify distance is a minimum of 2 (60ms) packets and a maximum of 32 (2.5ms) packets. */ av_assert0(distance == 0 || (distance >= 2 && distance <= 32)); if (i && distance == sgpd_entries[entries].roll_distance) { sgpd_entries[entries].count++; } else { entries++; sgpd_entries[entries].count = 1; sgpd_entries[entries].roll_distance = distance; sgpd_entries[entries].group_description_index = distance ? ++group : 0; } } } else { entries++; sgpd_entries[entries].count = track->sample_count; sgpd_entries[entries].roll_distance = 1; sgpd_entries[entries].group_description_index = ++group; } entries++; if (!group) { av_free(sgpd_entries); return 0; } /* Write sgpd tag */ avio_wb32(pb, 24 + (group * 2)); /* size */ ffio_wfourcc(pb, "sgpd"); avio_wb32(pb, 1 << 24); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, 2); /* default_length */ avio_wb32(pb, group); /* entry_count */ for (i = 0; i < entries; i++) { if (sgpd_entries[i].group_description_index) { avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */ } } /* Write sbgp tag */ avio_wb32(pb, 20 + (entries * 8)); /* size */ ffio_wfourcc(pb, "sbgp"); avio_wb32(pb, 0); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, entries); /* entry_count */ for (i = 0; i < entries; i++) { avio_wb32(pb, sgpd_entries[i].count); /* sample_count */ avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */ } av_free(sgpd_entries); return 0; } static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stbl"); mov_write_stsd_tag(s, pb, mov, track); mov_write_stts_tag(pb, track); if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO || track->par->codec_tag == MKTAG('r','t','p',' ')) && track->has_keyframes && track->has_keyframes < track->entry) mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable) mov_write_sdtp_tag(pb, track); if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS) mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->flags & MOV_TRACK_CTTS && track->entry) { if ((ret = mov_write_ctts_tag(s, pb, track)) < 0) return ret; } mov_write_stsc_tag(pb, track); mov_write_stsz_tag(pb, track); mov_write_stco_tag(pb, track); if (track->cenc.aes_ctr) { ff_mov_cenc_write_stbl_atoms(&track->cenc, pb); } if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) { mov_preroll_write_stbl_atoms(pb, track); } return update_size(pb, pos); } static int mov_write_dinf_tag(AVIOContext *pb) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "dinf"); mov_write_dref_tag(pb); return update_size(pb, pos); } static int mov_write_nmhd_tag(AVIOContext *pb) { avio_wb32(pb, 12); ffio_wfourcc(pb, "nmhd"); avio_wb32(pb, 0); return 12; } static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); const char *font = "Lucida Grande"; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */ avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0); /* text font */ avio_wb16(pb, 0); /* text face */ avio_wb16(pb, 12); /* text size */ avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */ avio_wb16(pb, 0x0000); /* text color (red) */ avio_wb16(pb, 0x0000); /* text color (green) */ avio_wb16(pb, 0x0000); /* text color (blue) */ avio_wb16(pb, 0xffff); /* background color (red) */ avio_wb16(pb, 0xffff); /* background color (green) */ avio_wb16(pb, 0xffff); /* background color (blue) */ avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */ avio_write(pb, font, strlen(font)); /* font name */ return update_size(pb, pos); } static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gmhd"); avio_wb32(pb, 0x18); /* gmin size */ ffio_wfourcc(pb, "gmin");/* generic media info */ avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0x40); /* graphics mode = */ avio_wb16(pb, 0x8000); /* opColor (r?) */ avio_wb16(pb, 0x8000); /* opColor (g?) */ avio_wb16(pb, 0x8000); /* opColor (b?) */ avio_wb16(pb, 0); /* balance */ avio_wb16(pb, 0); /* reserved */ /* * This special text atom is required for * Apple Quicktime chapters. The contents * don't appear to be documented, so the * bytes are copied verbatim. */ if (track->tag != MKTAG('c','6','0','8')) { avio_wb32(pb, 0x2C); /* size */ ffio_wfourcc(pb, "text"); avio_wb16(pb, 0x01); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x01); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00004000); avio_wb16(pb, 0x0000); } if (track->par->codec_tag == MKTAG('t','m','c','d')) { int64_t tmcd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); mov_write_tcmi_tag(pb, track); update_size(pb, tmcd_pos); } else if (track->par->codec_tag == MKTAG('g','p','m','d')) { int64_t gpmd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gpmd"); avio_wb32(pb, 0); /* version */ update_size(pb, gpmd_pos); } return update_size(pb, pos); } static int mov_write_smhd_tag(AVIOContext *pb) { avio_wb32(pb, 16); /* size */ ffio_wfourcc(pb, "smhd"); avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0); /* reserved (balance, normally = 0) */ avio_wb16(pb, 0); /* reserved */ return 16; } static int mov_write_vmhd_tag(AVIOContext *pb) { avio_wb32(pb, 0x14); /* size (always 0x14) */ ffio_wfourcc(pb, "vmhd"); avio_wb32(pb, 0x01); /* version & flags */ avio_wb64(pb, 0); /* reserved (graphics mode = copy) */ return 0x14; } static int is_clcp_track(MOVTrack *track) { return track->tag == MKTAG('c','7','0','8') || track->tag == MKTAG('c','6','0','8'); } static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; const char *hdlr, *descr = NULL, *hdlr_type = NULL; int64_t pos = avio_tell(pb); hdlr = "dhlr"; hdlr_type = "url "; descr = "DataHandler"; if (track) { hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0"; if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { hdlr_type = "vide"; descr = "VideoHandler"; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { hdlr_type = "soun"; descr = "SoundHandler"; } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) { if (is_clcp_track(track)) { hdlr_type = "clcp"; descr = "ClosedCaptionHandler"; } else { if (track->tag == MKTAG('t','x','3','g')) { hdlr_type = "sbtl"; } else if (track->tag == MKTAG('m','p','4','s')) { hdlr_type = "subp"; } else { hdlr_type = "text"; } descr = "SubtitleHandler"; } } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) { hdlr_type = "hint"; descr = "HintHandler"; } else if (track->par->codec_tag == MKTAG('t','m','c','d')) { hdlr_type = "tmcd"; descr = "TimeCodeHandler"; } else if (track->par->codec_tag == MKTAG('g','p','m','d')) { hdlr_type = "meta"; descr = "GoPro MET"; // GoPro Metadata } else { av_log(s, AV_LOG_WARNING, "Unknown hldr_type for %s, writing dummy values\n", av_fourcc2str(track->par->codec_tag)); } if (track->st) { // hdlr.name is used by some players to identify the content title // of the track. So if an alternate handler description is // specified, use it. AVDictionaryEntry *t; t = av_dict_get(track->st->metadata, "handler_name", NULL, 0); if (t && utf8len(t->value)) descr = t->value; } } if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */ descr = ""; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); /* Version & flags */ avio_write(pb, hdlr, 4); /* handler */ ffio_wfourcc(pb, hdlr_type); /* handler type */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ if (!track || track->mode == MODE_MOV) avio_w8(pb, strlen(descr)); /* pascal string */ avio_write(pb, descr, strlen(descr)); /* handler description */ if (track && track->mode != MODE_MOV) avio_w8(pb, 0); /* c string */ return update_size(pb, pos); } static int mov_write_hmhd_tag(AVIOContext *pb) { /* This atom must be present, but leaving the values at zero * seems harmless. */ avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "hmhd"); avio_wb32(pb, 0); /* version, flags */ avio_wb16(pb, 0); /* maxPDUsize */ avio_wb16(pb, 0); /* avgPDUsize */ avio_wb32(pb, 0); /* maxbitrate */ avio_wb32(pb, 0); /* avgbitrate */ avio_wb32(pb, 0); /* reserved */ return 28; } static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "minf"); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) mov_write_vmhd_tag(pb); else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_smhd_tag(pb); else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) { if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) { mov_write_gmhd_tag(pb, track); } else { mov_write_nmhd_tag(pb); } } else if (track->tag == MKTAG('r','t','p',' ')) { mov_write_hmhd_tag(pb); } else if (track->tag == MKTAG('t','m','c','d')) { if (track->mode != MODE_MOV) mov_write_nmhd_tag(pb); else mov_write_gmhd_tag(pb, track); } else if (track->tag == MKTAG('g','p','m','d')) { mov_write_gmhd_tag(pb, track); } if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */ mov_write_hdlr_tag(s, pb, NULL); mov_write_dinf_tag(pb); if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0) return ret; return update_size(pb, pos); } static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int version = track->track_duration < INT32_MAX ? 0 : 1; if (track->mode == MODE_ISM) version = 1; (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */ ffio_wfourcc(pb, "mdhd"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ if (version == 1) { avio_wb64(pb, track->time); avio_wb64(pb, track->time); } else { avio_wb32(pb, track->time); /* creation time */ avio_wb32(pb, track->time); /* modification time */ } avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */ if (!track->entry && mov->mode == MODE_ISM) (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff); else if (!track->entry) (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0); else (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */ avio_wb16(pb, track->language); /* language */ avio_wb16(pb, 0); /* reserved (quality) */ if (version != 0 && track->mode == MODE_MOV) { av_log(NULL, AV_LOG_ERROR, "FATAL error, file duration too long for timebase, this file will not be\n" "playable with quicktime. Choose a different timebase or a different\n" "container format\n"); } return 32; } static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "mdia"); mov_write_mdhd_tag(pb, mov, track); mov_write_hdlr_tag(s, pb, track); if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0) return ret; return update_size(pb, pos); } /* transformation matrix |a b u| |c d v| |tx ty w| */ static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c, int16_t d, int16_t tx, int16_t ty) { avio_wb32(pb, a << 16); /* 16.16 format */ avio_wb32(pb, b << 16); /* 16.16 format */ avio_wb32(pb, 0); /* u in 2.30 format */ avio_wb32(pb, c << 16); /* 16.16 format */ avio_wb32(pb, d << 16); /* 16.16 format */ avio_wb32(pb, 0); /* v in 2.30 format */ avio_wb32(pb, tx << 16); /* 16.16 format */ avio_wb32(pb, ty << 16); /* 16.16 format */ avio_wb32(pb, 1 << 30); /* w in 2.30 format */ } static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, AVStream *st) { int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE, track->timescale, AV_ROUND_UP); int version = duration < INT32_MAX ? 0 : 1; int flags = MOV_TKHD_FLAG_IN_MOVIE; int rotation = 0; int group = 0; uint32_t *display_matrix = NULL; int display_matrix_size, i; if (st) { if (mov->per_stream_grouping) group = st->index; else group = st->codecpar->codec_type; display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &display_matrix_size); if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix)) display_matrix = NULL; } if (track->flags & MOV_TRACK_ENABLED) flags |= MOV_TKHD_FLAG_ENABLED; if (track->mode == MODE_ISM) version = 1; (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */ ffio_wfourcc(pb, "tkhd"); avio_w8(pb, version); avio_wb24(pb, flags); if (version == 1) { avio_wb64(pb, track->time); avio_wb64(pb, track->time); } else { avio_wb32(pb, track->time); /* creation time */ avio_wb32(pb, track->time); /* modification time */ } avio_wb32(pb, track->track_id); /* track-id */ avio_wb32(pb, 0); /* reserved */ if (!track->entry && mov->mode == MODE_ISM) (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff); else if (!track->entry) (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0); else (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration); avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb16(pb, 0); /* layer */ avio_wb16(pb, group); /* alternate group) */ /* Volume, only for audio */ if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) avio_wb16(pb, 0x0100); else avio_wb16(pb, 0); avio_wb16(pb, 0); /* reserved */ /* Matrix structure */ #if FF_API_OLD_ROTATE_API if (st && st->metadata) { AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0); rotation = (rot && rot->value) ? atoi(rot->value) : 0; } #endif if (display_matrix) { for (i = 0; i < 9; i++) avio_wb32(pb, display_matrix[i]); #if FF_API_OLD_ROTATE_API } else if (rotation == 90) { write_matrix(pb, 0, 1, -1, 0, track->par->height, 0); } else if (rotation == 180) { write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height); } else if (rotation == 270) { write_matrix(pb, 0, -1, 1, 0, 0, track->par->width); #endif } else { write_matrix(pb, 1, 0, 0, 1, 0, 0); } /* Track width and height, for visual only */ if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO || track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) { int64_t track_width_1616; if (track->mode == MODE_MOV) { track_width_1616 = track->par->width * 0x10000ULL; } else { track_width_1616 = av_rescale(st->sample_aspect_ratio.num, track->par->width * 0x10000LL, st->sample_aspect_ratio.den); if (!track_width_1616 || track->height != track->par->height || track_width_1616 > UINT32_MAX) track_width_1616 = track->par->width * 0x10000ULL; } if (track_width_1616 > UINT32_MAX) { av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n"); track_width_1616 = 0; } avio_wb32(pb, track_width_1616); if (track->height > 0xFFFF) { av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n"); avio_wb32(pb, 0); } else avio_wb32(pb, track->height * 0x10000U); } else { avio_wb32(pb, 0); avio_wb32(pb, 0); } return 0x5c; } static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track) { int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width, track->par->sample_aspect_ratio.den); int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tapt"); avio_wb32(pb, 20); ffio_wfourcc(pb, "clef"); avio_wb32(pb, 0); avio_wb32(pb, width << 16); avio_wb32(pb, track->par->height << 16); avio_wb32(pb, 20); ffio_wfourcc(pb, "prof"); avio_wb32(pb, 0); avio_wb32(pb, width << 16); avio_wb32(pb, track->par->height << 16); avio_wb32(pb, 20); ffio_wfourcc(pb, "enof"); avio_wb32(pb, 0); avio_wb32(pb, track->par->width << 16); avio_wb32(pb, track->par->height << 16); return update_size(pb, pos); } // This box seems important for the psp playback ... without it the movie seems to hang static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE, track->timescale, AV_ROUND_UP); int version = duration < INT32_MAX ? 0 : 1; int entry_size, entry_count, size; int64_t delay, start_ct = track->start_cts; int64_t start_dts = track->start_dts; if (track->entry) { if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) { av_log(mov->fc, AV_LOG_DEBUG, "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n", track->cluster[0].dts, track->cluster[0].cts, start_dts, start_ct, track->track_id); start_dts = track->cluster[0].dts; start_ct = track->cluster[0].cts; } } delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN); version |= delay < INT32_MAX ? 0 : 1; entry_size = (version == 1) ? 20 : 12; entry_count = 1 + (delay > 0); size = 24 + entry_count * entry_size; /* write the atom data */ avio_wb32(pb, size); ffio_wfourcc(pb, "edts"); avio_wb32(pb, size - 8); ffio_wfourcc(pb, "elst"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ avio_wb32(pb, entry_count); if (delay > 0) { /* add an empty edit to delay presentation */ /* In the positive delay case, the delay includes the cts * offset, and the second edit list entry below trims out * the same amount from the actual content. This makes sure * that the offset last sample is included in the edit * list duration as well. */ if (version == 1) { avio_wb64(pb, delay); avio_wb64(pb, -1); } else { avio_wb32(pb, delay); avio_wb32(pb, -1); } avio_wb32(pb, 0x00010000); } else { /* Avoid accidentally ending up with start_ct = -1 which has got a * special meaning. Normally start_ct should end up positive or zero * here, but use FFMIN in case dts is a small positive integer * rounded to 0 when represented in MOV_TIMESCALE units. */ av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0); start_ct = -FFMIN(start_dts, 0); /* Note, this delay is calculated from the pts of the first sample, * ensuring that we don't reduce the duration for cases with * dts<0 pts=0. */ duration += delay; } /* For fragmented files, we don't know the full length yet. Setting * duration to 0 allows us to only specify the offset, including * the rest of the content (from all future fragments) without specifying * an explicit duration. */ if (mov->flags & FF_MOV_FLAG_FRAGMENT) duration = 0; /* duration */ if (version == 1) { avio_wb64(pb, duration); avio_wb64(pb, start_ct); } else { avio_wb32(pb, duration); avio_wb32(pb, start_ct); } avio_wb32(pb, 0x00010000); return size; } static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 20); // size ffio_wfourcc(pb, "tref"); avio_wb32(pb, 12); // size (subatom) avio_wl32(pb, track->tref_tag); avio_wb32(pb, track->tref_id); return 20; } // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it) static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov) { avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "USMT"); avio_wb32(pb, 0x21d24fce); avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); avio_wb32(pb, 0x1c); // another size here! ffio_wfourcc(pb, "MTDT"); avio_wb32(pb, 0x00010012); avio_wb32(pb, 0x0a); avio_wb32(pb, 0x55c40000); avio_wb32(pb, 0x1); avio_wb32(pb, 0x0); return 0x34; } static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track) { AVFormatContext *ctx = track->rtp_ctx; char buf[1000] = ""; int len; ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track, NULL, NULL, 0, 0, ctx); av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id); len = strlen(buf); avio_wb32(pb, len + 24); ffio_wfourcc(pb, "udta"); avio_wb32(pb, len + 16); ffio_wfourcc(pb, "hnti"); avio_wb32(pb, len + 8); ffio_wfourcc(pb, "sdp "); avio_write(pb, buf, len); return len + 24; } static int mov_write_track_metadata(AVIOContext *pb, AVStream *st, const char *tag, const char *str) { int64_t pos = avio_tell(pb); AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0); if (!t || !utf8len(t->value)) return 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, tag); /* type */ avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */ return update_size(pb, pos); } static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov, AVStream *st) { AVIOContext *pb_buf; int ret, size; uint8_t *buf; if (!st) return 0; ret = avio_open_dyn_buf(&pb_buf); if (ret < 0) return ret; if (mov->mode & (MODE_MP4|MODE_MOV)) mov_write_track_metadata(pb_buf, st, "name", "title"); if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) { avio_wb32(pb, size + 8); ffio_wfourcc(pb, "udta"); avio_write(pb, buf, size); } av_free(buf); return 0; } static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, AVStream *st) { int64_t pos = avio_tell(pb); int entry_backup = track->entry; int chunk_backup = track->chunkCount; int ret; /* If we want to have an empty moov, but some samples already have been * buffered (delay_moov), pretend that no samples have been written yet. */ if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) track->chunkCount = track->entry = 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "trak"); mov_write_tkhd_tag(pb, mov, track, st); av_assert2(mov->use_editlist >= 0); if (track->start_dts != AV_NOPTS_VALUE) { if (mov->use_editlist) mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track)) av_log(mov->fc, AV_LOG_WARNING, "Not writing any edit list even though one would have been required\n"); } if (track->tref_tag) mov_write_tref_tag(pb, track); if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0) return ret; if (track->mode == MODE_PSP) mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box if (track->tag == MKTAG('r','t','p',' ')) mov_write_udta_sdp(pb, track); if (track->mode == MODE_MOV) { if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio); if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) { mov_write_tapt_tag(pb, track); } } if (is_clcp_track(track) && st->sample_aspect_ratio.num) { mov_write_tapt_tag(pb, track); } } mov_write_track_udta_tag(pb, mov, st); track->entry = entry_backup; track->chunkCount = chunk_backup; return update_size(pb, pos); } static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov) { int i, has_audio = 0, has_video = 0; int64_t pos = avio_tell(pb); int audio_profile = mov->iods_audio_profile; int video_profile = mov->iods_video_profile; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO; has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO; } } if (audio_profile < 0) audio_profile = 0xFF - has_audio; if (video_profile < 0) video_profile = 0xFF - has_video; avio_wb32(pb, 0x0); /* size */ ffio_wfourcc(pb, "iods"); avio_wb32(pb, 0); /* version & flags */ put_descr(pb, 0x10, 7); avio_wb16(pb, 0x004f); avio_w8(pb, 0xff); avio_w8(pb, 0xff); avio_w8(pb, audio_profile); avio_w8(pb, video_profile); avio_w8(pb, 0xff); return update_size(pb, pos); } static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 0x20); /* size */ ffio_wfourcc(pb, "trex"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, track->track_id); /* track ID */ avio_wb32(pb, 1); /* default sample description index */ avio_wb32(pb, 0); /* default sample duration */ avio_wb32(pb, 0); /* default sample size */ avio_wb32(pb, 0); /* default sample flags */ return 0; } static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0x0); /* size */ ffio_wfourcc(pb, "mvex"); for (i = 0; i < mov->nb_streams; i++) mov_write_trex_tag(pb, &mov->tracks[i]); return update_size(pb, pos); } static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov) { int max_track_id = 1, i; int64_t max_track_len = 0; int version; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) { int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration, MOV_TIMESCALE, mov->tracks[i].timescale, AV_ROUND_UP); if (max_track_len < max_track_len_temp) max_track_len = max_track_len_temp; if (max_track_id < mov->tracks[i].track_id) max_track_id = mov->tracks[i].track_id; } } /* If using delay_moov, make sure the output is the same as if no * samples had been written yet. */ if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { max_track_len = 0; max_track_id = 1; } version = max_track_len < UINT32_MAX ? 0 : 1; avio_wb32(pb, version == 1 ? 120 : 108); /* size */ ffio_wfourcc(pb, "mvhd"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ if (version == 1) { avio_wb64(pb, mov->time); avio_wb64(pb, mov->time); } else { avio_wb32(pb, mov->time); /* creation time */ avio_wb32(pb, mov->time); /* modification time */ } avio_wb32(pb, MOV_TIMESCALE); (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */ avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */ avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */ avio_wb16(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ /* Matrix structure */ write_matrix(pb, 1, 0, 0, 1, 0, 0); avio_wb32(pb, 0); /* reserved (preview time) */ avio_wb32(pb, 0); /* reserved (preview duration) */ avio_wb32(pb, 0); /* reserved (poster time) */ avio_wb32(pb, 0); /* reserved (selection time) */ avio_wb32(pb, 0); /* reserved (selection duration) */ avio_wb32(pb, 0); /* reserved (current time) */ avio_wb32(pb, max_track_id + 1); /* Next track id */ return 0x6c; } static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { avio_wb32(pb, 33); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); avio_wb32(pb, 0); ffio_wfourcc(pb, "mdir"); ffio_wfourcc(pb, "appl"); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_w8(pb, 0); return 33; } /* helper function to write a data tag with the specified string as data */ static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style) { if (long_style) { int size = 16 + strlen(data); avio_wb32(pb, size); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 1); avio_wb32(pb, 0); avio_write(pb, data, strlen(data)); return size; } else { if (!lang) lang = ff_mov_iso639_to_lang("und", 1); avio_wb16(pb, strlen(data)); /* string length */ avio_wb16(pb, lang); avio_write(pb, data, strlen(data)); return strlen(data) + 4; } } static int mov_write_string_tag(AVIOContext *pb, const char *name, const char *value, int lang, int long_style) { int size = 0; if (value && value[0]) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, name); mov_write_string_data_tag(pb, value, lang, long_style); size = update_size(pb, pos); } return size; } static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s, const char *tag, int *lang) { int l, len, len2; AVDictionaryEntry *t, *t2 = NULL; char tag2[16]; *lang = 0; if (!(t = av_dict_get(s->metadata, tag, NULL, 0))) return NULL; len = strlen(t->key); snprintf(tag2, sizeof(tag2), "%s-", tag); while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) { len2 = strlen(t2->key); if (len2 == len + 4 && !strcmp(t->value, t2->value) && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) { *lang = l; return t; } } return t; } static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb, const char *name, const char *tag, int long_style) { int lang; AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang); if (!t) return 0; return mov_write_string_tag(pb, name, t->value, lang, long_style); } /* iTunes bpm number */ static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s) { AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0); int size = 0, tmpo = t ? atoi(t->value) : 0; if (tmpo) { size = 26; avio_wb32(pb, size); ffio_wfourcc(pb, "tmpo"); avio_wb32(pb, size-8); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 0x15); //type specifier avio_wb32(pb, 0); avio_wb16(pb, tmpo); // data } return size; } /* 3GPP TS 26.244 */ static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb) { int lang; int64_t pos = avio_tell(pb); double latitude, longitude, altitude; int32_t latitude_fix, longitude_fix, altitude_fix; AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang); const char *ptr, *place = ""; char *end; static const char *astronomical_body = "earth"; if (!t) return 0; ptr = t->value; longitude = strtod(ptr, &end); if (end == ptr) { av_log(s, AV_LOG_WARNING, "malformed location metadata\n"); return 0; } ptr = end; latitude = strtod(ptr, &end); if (end == ptr) { av_log(s, AV_LOG_WARNING, "malformed location metadata\n"); return 0; } ptr = end; altitude = strtod(ptr, &end); /* If no altitude was present, the default 0 should be fine */ if (*end == '/') place = end + 1; latitude_fix = (int32_t) ((1 << 16) * latitude); longitude_fix = (int32_t) ((1 << 16) * longitude); altitude_fix = (int32_t) ((1 << 16) * altitude); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "loci"); /* type */ avio_wb32(pb, 0); /* version + flags */ avio_wb16(pb, lang); avio_write(pb, place, strlen(place) + 1); avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */ avio_wb32(pb, latitude_fix); avio_wb32(pb, longitude_fix); avio_wb32(pb, altitude_fix); avio_write(pb, astronomical_body, strlen(astronomical_body) + 1); avio_w8(pb, 0); /* additional notes, null terminated string */ return update_size(pb, pos); } /* iTunes track or disc number */ static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s, int disc) { AVDictionaryEntry *t = av_dict_get(s->metadata, disc ? "disc" : "track", NULL, 0); int size = 0, track = t ? atoi(t->value) : 0; if (track) { int tracks = 0; char *slash = strchr(t->value, '/'); if (slash) tracks = atoi(slash + 1); avio_wb32(pb, 32); /* size */ ffio_wfourcc(pb, disc ? "disk" : "trkn"); avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 0); // 8 bytes empty avio_wb32(pb, 0); avio_wb16(pb, 0); // empty avio_wb16(pb, track); // track / disc number avio_wb16(pb, tracks); // total track / disc number avio_wb16(pb, 0); // empty size = 32; } return size; } static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb, const char *name, const char *tag, int len) { AVDictionaryEntry *t = NULL; uint8_t num; int size = 24 + len; if (len != 1 && len != 4) return -1; if (!(t = av_dict_get(s->metadata, tag, NULL, 0))) return 0; num = atoi(t->value); avio_wb32(pb, size); ffio_wfourcc(pb, name); avio_wb32(pb, size - 8); ffio_wfourcc(pb, "data"); avio_wb32(pb, 0x15); avio_wb32(pb, 0); if (len==4) avio_wb32(pb, num); else avio_w8 (pb, num); return size; } static int mov_write_covr(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int64_t pos = 0; int i; for (i = 0; i < s->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; if (!is_cover_image(trk->st) || trk->cover_image.size <= 0) continue; if (!pos) { pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "covr"); } avio_wb32(pb, 16 + trk->cover_image.size); ffio_wfourcc(pb, "data"); avio_wb32(pb, trk->tag); avio_wb32(pb , 0); avio_write(pb, trk->cover_image.data, trk->cover_image.size); } return pos ? update_size(pb, pos) : 0; } /* iTunes meta data list */ static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ilst"); mov_write_string_metadata(s, pb, "\251nam", "title" , 1); mov_write_string_metadata(s, pb, "\251ART", "artist" , 1); mov_write_string_metadata(s, pb, "aART", "album_artist", 1); mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1); mov_write_string_metadata(s, pb, "\251alb", "album" , 1); mov_write_string_metadata(s, pb, "\251day", "date" , 1); if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) { if (!(s->flags & AVFMT_FLAG_BITEXACT)) mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1); } mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1); mov_write_string_metadata(s, pb, "\251gen", "genre" , 1); mov_write_string_metadata(s, pb, "cprt", "copyright", 1); mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1); mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1); mov_write_string_metadata(s, pb, "desc", "description",1); mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1); mov_write_string_metadata(s, pb, "tvsh", "show" , 1); mov_write_string_metadata(s, pb, "tven", "episode_id",1); mov_write_string_metadata(s, pb, "tvnn", "network" , 1); mov_write_string_metadata(s, pb, "keyw", "keywords" , 1); mov_write_int8_metadata (s, pb, "tves", "episode_sort",4); mov_write_int8_metadata (s, pb, "tvsn", "season_number",4); mov_write_int8_metadata (s, pb, "stik", "media_type",1); mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1); mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1); mov_write_int8_metadata (s, pb, "cpil", "compilation", 1); mov_write_covr(pb, s); mov_write_trkn_tag(pb, mov, s, 0); // track number mov_write_trkn_tag(pb, mov, s, 1); // disc number mov_write_tmpo_tag(pb, s); return update_size(pb, pos); } static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { avio_wb32(pb, 33); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); avio_wb32(pb, 0); ffio_wfourcc(pb, "mdta"); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_w8(pb, 0); return 33; } static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVDictionaryEntry *t = NULL; int64_t pos = avio_tell(pb); int64_t curpos, entry_pos; int count = 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "keys"); avio_wb32(pb, 0); entry_pos = avio_tell(pb); avio_wb32(pb, 0); /* entry count */ while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) { avio_wb32(pb, strlen(t->key) + 8); ffio_wfourcc(pb, "mdta"); avio_write(pb, t->key, strlen(t->key)); count += 1; } curpos = avio_tell(pb); avio_seek(pb, entry_pos, SEEK_SET); avio_wb32(pb, count); // rewrite entry count avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVDictionaryEntry *t = NULL; int64_t pos = avio_tell(pb); int count = 1; /* keys are 1-index based */ avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ilst"); while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) { int64_t entry_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ avio_wb32(pb, count); /* key */ mov_write_string_data_tag(pb, t->value, 0, 1); update_size(pb, entry_pos); count += 1; } return update_size(pb, pos); } /* meta data tags */ static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int size = 0; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "meta"); avio_wb32(pb, 0); if (mov->flags & FF_MOV_FLAG_USE_MDTA) { mov_write_mdta_hdlr_tag(pb, mov, s); mov_write_mdta_keys_tag(pb, mov, s); mov_write_mdta_ilst_tag(pb, mov, s); } else { /* iTunes metadata tag */ mov_write_itunes_hdlr_tag(pb, mov, s); mov_write_ilst_tag(pb, mov, s); } size = update_size(pb, pos); return size; } static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb, const char *name, const char *key) { int len; AVDictionaryEntry *t; if (!(t = av_dict_get(s->metadata, key, NULL, 0))) return 0; len = strlen(t->value); if (len > 0) { int size = len + 8; avio_wb32(pb, size); ffio_wfourcc(pb, name); avio_write(pb, t->value, len); return size; } return 0; } static int ascii_to_wc(AVIOContext *pb, const uint8_t *b) { int val; while (*b) { GET_UTF8(val, *b++, return -1;) avio_wb16(pb, val); } avio_wb16(pb, 0x00); return 0; } static uint16_t language_code(const char *str) { return (((str[0] - 0x60) & 0x1F) << 10) + (((str[1] - 0x60) & 0x1F) << 5) + (( str[2] - 0x60) & 0x1F); } static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s, const char *tag, const char *str) { int64_t pos = avio_tell(pb); AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0); if (!t || !utf8len(t->value)) return 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, tag); /* type */ avio_wb32(pb, 0); /* version + flags */ if (!strcmp(tag, "yrrc")) avio_wb16(pb, atoi(t->value)); else { avio_wb16(pb, language_code("eng")); /* language */ avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */ if (!strcmp(tag, "albm") && (t = av_dict_get(s->metadata, "track", NULL, 0))) avio_w8(pb, atoi(t->value)); } return update_size(pb, pos); } static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s) { int64_t pos = avio_tell(pb); int i, nb_chapters = FFMIN(s->nb_chapters, 255); avio_wb32(pb, 0); // size ffio_wfourcc(pb, "chpl"); avio_wb32(pb, 0x01000000); // version + flags avio_wb32(pb, 0); // unknown avio_w8(pb, nb_chapters); for (i = 0; i < nb_chapters; i++) { AVChapter *c = s->chapters[i]; AVDictionaryEntry *t; avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000})); if ((t = av_dict_get(c->metadata, "title", NULL, 0))) { int len = FFMIN(strlen(t->value), 255); avio_w8(pb, len); avio_write(pb, t->value, len); } else avio_w8(pb, 0); } return update_size(pb, pos); } static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVIOContext *pb_buf; int ret, size; uint8_t *buf; ret = avio_open_dyn_buf(&pb_buf); if (ret < 0) return ret; if (mov->mode & MODE_3GP) { mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist"); mov_write_3gp_udta_tag(pb_buf, s, "titl", "title"); mov_write_3gp_udta_tag(pb_buf, s, "auth", "author"); mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre"); mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment"); mov_write_3gp_udta_tag(pb_buf, s, "albm", "album"); mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright"); mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date"); mov_write_loci_tag(s, pb_buf); } else if (mov->mode == MODE_MOV && !(mov->flags & FF_MOV_FLAG_USE_MDTA)) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0); mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0); mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0); mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0); mov_write_string_metadata(s, pb_buf, "\251day", "date", 0); mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0); // currently ignored by mov.c mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0); // add support for libquicktime, this atom is also actually read by mov.c mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0); mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0); mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0); mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0); mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0); mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0); mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0); mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp"); } else { /* iTunes meta data */ mov_write_meta_tag(pb_buf, mov, s); mov_write_loci_tag(s, pb_buf); } if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL)) mov_write_chpl_tag(pb_buf, s); if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) { avio_wb32(pb, size + 8); ffio_wfourcc(pb, "udta"); avio_write(pb, buf, size); } av_free(buf); return 0; } static void mov_write_psp_udta_tag(AVIOContext *pb, const char *str, const char *lang, int type) { int len = utf8len(str) + 1; if (len <= 0) return; avio_wb16(pb, len * 2 + 10); /* size */ avio_wb32(pb, type); /* type */ avio_wb16(pb, language_code(lang)); /* language */ avio_wb16(pb, 0x01); /* ? */ ascii_to_wc(pb, str); } static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s) { AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0); int64_t pos, pos2; if (title) { pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "USMT"); avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */ avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); pos2 = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "MTDT"); avio_wb16(pb, 4); // ? avio_wb16(pb, 0x0C); /* size */ avio_wb32(pb, 0x0B); /* type */ avio_wb16(pb, language_code("und")); /* language */ avio_wb16(pb, 0x0); /* ? */ avio_wb16(pb, 0x021C); /* data */ if (!(s->flags & AVFMT_FLAG_BITEXACT)) mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04); mov_write_psp_udta_tag(pb, title->value, "eng", 0x01); mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03); update_size(pb, pos2); return update_size(pb, pos); } return 0; } static void build_chunks(MOVTrack *trk) { int i; MOVIentry *chunk = &trk->cluster[0]; uint64_t chunkSize = chunk->size; chunk->chunkNum = 1; if (trk->chunkCount) return; trk->chunkCount = 1; for (i = 1; i<trk->entry; i++){ if (chunk->pos + chunkSize == trk->cluster[i].pos && chunkSize + trk->cluster[i].size < (1<<20)){ chunkSize += trk->cluster[i].size; chunk->samples_in_chunk += trk->cluster[i].entries; } else { trk->cluster[i].chunkNum = chunk->chunkNum+1; chunk=&trk->cluster[i]; chunkSize = chunk->size; trk->chunkCount++; } } } /** * Assign track ids. If option "use_stream_ids_as_track_ids" is set, * the stream ids are used as track ids. * * This assumes mov->tracks and s->streams are in the same order and * there are no gaps in either of them (so mov->tracks[n] refers to * s->streams[n]). * * As an exception, there can be more entries in * s->streams than in mov->tracks, in which case new track ids are * generated (starting after the largest found stream id). */ static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s) { int i; if (mov->track_ids_ok) return 0; if (mov->use_stream_ids_as_track_ids) { int next_generated_track_id = 0; for (i = 0; i < s->nb_streams; i++) { if (s->streams[i]->id > next_generated_track_id) next_generated_track_id = s->streams[i]->id; } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id; } } else { for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].track_id = i + 1; } } mov->track_ids_ok = 1; return 0; } static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int i; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "moov"); mov_setup_track_ids(mov, s); for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].time = mov->time; if (mov->tracks[i].entry) build_chunks(&mov->tracks[i]); } if (mov->chapter_track) for (i = 0; i < s->nb_streams; i++) { mov->tracks[i].tref_tag = MKTAG('c','h','a','p'); mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id; } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->tag == MKTAG('r','t','p',' ')) { track->tref_tag = MKTAG('h','i','n','t'); track->tref_id = mov->tracks[track->src_track].track_id; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { int * fallback, size; fallback = (int*)av_stream_get_side_data(track->st, AV_PKT_DATA_FALLBACK_TRACK, &size); if (fallback != NULL && size == sizeof(int)) { if (*fallback >= 0 && *fallback < mov->nb_streams) { track->tref_tag = MKTAG('f','a','l','l'); track->tref_id = mov->tracks[*fallback].track_id; } } } } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].tag == MKTAG('t','m','c','d')) { int src_trk = mov->tracks[i].src_track; mov->tracks[src_trk].tref_tag = mov->tracks[i].tag; mov->tracks[src_trk].tref_id = mov->tracks[i].track_id; //src_trk may have a different timescale than the tmcd track mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration, mov->tracks[i].timescale, mov->tracks[src_trk].timescale); } } mov_write_mvhd_tag(pb, mov); if (mov->mode != MODE_MOV && !mov->iods_skip) mov_write_iods_tag(pb, mov); for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) { int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL); if (ret < 0) return ret; } } if (mov->flags & FF_MOV_FLAG_FRAGMENT) mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */ if (mov->mode == MODE_PSP) mov_write_uuidusmt_tag(pb, s); else mov_write_udta_tag(pb, mov, s); return update_size(pb, pos); } static void param_write_int(AVIOContext *pb, const char *name, int value) { avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value); } static void param_write_string(AVIOContext *pb, const char *name, const char *value) { avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value); } static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len) { char buf[150]; len = FFMIN(sizeof(buf) / 2 - 1, len); ff_data_to_hex(buf, value, len, 0); buf[2 * len] = '\0'; avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf); } static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int64_t pos = avio_tell(pb); int i; int64_t manifest_bit_rate = 0; AVCPBProperties *props = NULL; static const uint8_t uuid[] = { 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd, 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }; avio_wb32(pb, 0); ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_wb32(pb, 0); avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n"); avio_printf(pb, "<head>\n"); if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT)) avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n", LIBAVFORMAT_IDENT); avio_printf(pb, "</head>\n"); avio_printf(pb, "<body>\n"); avio_printf(pb, "<switch>\n"); mov_setup_track_ids(mov, s); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; const char *type; int track_id = track->track_id; char track_name_buf[32] = { 0 }; AVStream *st = track->st; AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) { type = "video"; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { type = "audio"; } else { continue; } props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL); if (track->par->bit_rate) { manifest_bit_rate = track->par->bit_rate; } else if (props) { manifest_bit_rate = props->max_bitrate; } avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type, manifest_bit_rate); param_write_int(pb, "systemBitrate", manifest_bit_rate); param_write_int(pb, "trackID", track_id); param_write_string(pb, "systemLanguage", lang ? lang->value : "und"); /* Build track name piece by piece: */ /* 1. track type */ av_strlcat(track_name_buf, type, sizeof(track_name_buf)); /* 2. track language, if available */ if (lang) av_strlcatf(track_name_buf, sizeof(track_name_buf), "_%s", lang->value); /* 3. special type suffix */ /* "_cc" = closed captions, "_ad" = audio_description */ if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED) av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf)); else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED) av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf)); param_write_string(pb, "trackName", track_name_buf); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { if (track->par->codec_id == AV_CODEC_ID_H264) { uint8_t *ptr; int size = track->par->extradata_size; if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr, &size)) { param_write_hex(pb, "CodecPrivateData", ptr ? ptr : track->par->extradata, size); av_free(ptr); } param_write_string(pb, "FourCC", "H264"); } else if (track->par->codec_id == AV_CODEC_ID_VC1) { param_write_string(pb, "FourCC", "WVC1"); param_write_hex(pb, "CodecPrivateData", track->par->extradata, track->par->extradata_size); } param_write_int(pb, "MaxWidth", track->par->width); param_write_int(pb, "MaxHeight", track->par->height); param_write_int(pb, "DisplayWidth", track->par->width); param_write_int(pb, "DisplayHeight", track->par->height); } else { if (track->par->codec_id == AV_CODEC_ID_AAC) { switch (track->par->profile) { case FF_PROFILE_AAC_HE_V2: param_write_string(pb, "FourCC", "AACP"); break; case FF_PROFILE_AAC_HE: param_write_string(pb, "FourCC", "AACH"); break; default: param_write_string(pb, "FourCC", "AACL"); } } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) { param_write_string(pb, "FourCC", "WMAP"); } param_write_hex(pb, "CodecPrivateData", track->par->extradata, track->par->extradata_size); param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id)); param_write_int(pb, "Channels", track->par->channels); param_write_int(pb, "SamplingRate", track->par->sample_rate); param_write_int(pb, "BitsPerSample", 16); param_write_int(pb, "PacketSize", track->par->block_align ? track->par->block_align : 4); } avio_printf(pb, "</%s>\n", type); } avio_printf(pb, "</switch>\n"); avio_printf(pb, "</body>\n"); avio_printf(pb, "</smil>\n"); return update_size(pb, pos); } static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov) { avio_wb32(pb, 16); ffio_wfourcc(pb, "mfhd"); avio_wb32(pb, 0); avio_wb32(pb, mov->fragments); return 0; } static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry) { return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO : (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC); } static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int64_t moof_offset) { int64_t pos = avio_tell(pb); uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION | MOV_TFHD_BASE_DATA_OFFSET; if (!track->entry) { flags |= MOV_TFHD_DURATION_IS_EMPTY; } else { flags |= MOV_TFHD_DEFAULT_FLAGS; } if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET) flags &= ~MOV_TFHD_BASE_DATA_OFFSET; if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) { flags &= ~MOV_TFHD_BASE_DATA_OFFSET; flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF; } /* Don't set a default sample size, the silverlight player refuses * to play files with that set. Don't set a default sample duration, * WMP freaks out if it is set. Don't set a base data offset, PIFF * file format says it MUST NOT be set. */ if (track->mode == MODE_ISM) flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION | MOV_TFHD_BASE_DATA_OFFSET); avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "tfhd"); avio_w8(pb, 0); /* version */ avio_wb24(pb, flags); avio_wb32(pb, track->track_id); /* track-id */ if (flags & MOV_TFHD_BASE_DATA_OFFSET) avio_wb64(pb, moof_offset); if (flags & MOV_TFHD_DEFAULT_DURATION) { track->default_duration = get_cluster_duration(track, 0); avio_wb32(pb, track->default_duration); } if (flags & MOV_TFHD_DEFAULT_SIZE) { track->default_size = track->entry ? track->cluster[0].size : 1; avio_wb32(pb, track->default_size); } else track->default_size = -1; if (flags & MOV_TFHD_DEFAULT_FLAGS) { /* Set the default flags based on the second sample, if available. * If the first sample is different, that can be signaled via a separate field. */ if (track->entry > 1) track->default_sample_flags = get_sample_flags(track, &track->cluster[1]); else track->default_sample_flags = track->par->codec_type == AVMEDIA_TYPE_VIDEO ? (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) : MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO; avio_wb32(pb, track->default_sample_flags); } return update_size(pb, pos); } static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int moof_size, int first, int end) { int64_t pos = avio_tell(pb); uint32_t flags = MOV_TRUN_DATA_OFFSET; int i; for (i = first; i < end; i++) { if (get_cluster_duration(track, i) != track->default_duration) flags |= MOV_TRUN_SAMPLE_DURATION; if (track->cluster[i].size != track->default_size) flags |= MOV_TRUN_SAMPLE_SIZE; if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags) flags |= MOV_TRUN_SAMPLE_FLAGS; } if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 && get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags) flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS; if (track->flags & MOV_TRACK_CTTS) flags |= MOV_TRUN_SAMPLE_CTS; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "trun"); if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) avio_w8(pb, 1); /* version */ else avio_w8(pb, 0); /* version */ avio_wb24(pb, flags); avio_wb32(pb, end - first); /* sample count */ if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET && !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) && !mov->first_trun) avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */ else avio_wb32(pb, moof_size + 8 + track->data_offset + track->cluster[first].pos); /* data offset */ if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) avio_wb32(pb, get_sample_flags(track, &track->cluster[first])); for (i = first; i < end; i++) { if (flags & MOV_TRUN_SAMPLE_DURATION) avio_wb32(pb, get_cluster_duration(track, i)); if (flags & MOV_TRUN_SAMPLE_SIZE) avio_wb32(pb, track->cluster[i].size); if (flags & MOV_TRUN_SAMPLE_FLAGS) avio_wb32(pb, get_sample_flags(track, &track->cluster[i])); if (flags & MOV_TRUN_SAMPLE_CTS) avio_wb32(pb, track->cluster[i].cts); } mov->first_trun = 0; return update_size(pb, pos); } static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); static const uint8_t uuid[] = { 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6, 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2 }; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_w8(pb, 1); avio_wb24(pb, 0); avio_wb64(pb, track->start_dts + track->frag_start + track->cluster[0].cts); avio_wb64(pb, track->end_pts - (track->cluster[0].dts + track->cluster[0].cts)); return update_size(pb, pos); } static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int entry) { int n = track->nb_frag_info - 1 - entry, i; int size = 8 + 16 + 4 + 1 + 16*n; static const uint8_t uuid[] = { 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95, 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f }; if (entry < 0) return 0; avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET); avio_wb32(pb, size); ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_w8(pb, 1); avio_wb24(pb, 0); avio_w8(pb, n); for (i = 0; i < n; i++) { int index = entry + 1 + i; avio_wb64(pb, track->frag_info[index].time); avio_wb64(pb, track->frag_info[index].duration); } if (n < mov->ism_lookahead) { int free_size = 16 * (mov->ism_lookahead - n); avio_wb32(pb, free_size); ffio_wfourcc(pb, "free"); ffio_fill(pb, 0, free_size - 8); } return 0; } static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int i; for (i = 0; i < mov->ism_lookahead; i++) { /* Update the tfrf tag for the last ism_lookahead fragments, * nb_frag_info - 1 is the next fragment to be written. */ mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i); } avio_seek(pb, pos, SEEK_SET); return 0; } static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks, int size) { int i; for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; MOVFragmentInfo *info; if ((tracks >= 0 && i != tracks) || !track->entry) continue; track->nb_frag_info++; if (track->nb_frag_info >= track->frag_info_capacity) { unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT; if (av_reallocp_array(&track->frag_info, new_capacity, sizeof(*track->frag_info))) return AVERROR(ENOMEM); track->frag_info_capacity = new_capacity; } info = &track->frag_info[track->nb_frag_info - 1]; info->offset = avio_tell(pb); info->size = size; // Try to recreate the original pts for the first packet // from the fields we have stored info->time = track->start_dts + track->frag_start + track->cluster[0].cts; info->duration = track->end_pts - (track->cluster[0].dts + track->cluster[0].cts); // If the pts is less than zero, we will have trimmed // away parts of the media track using an edit list, // and the corresponding start presentation time is zero. if (info->time < 0) { info->duration += info->time; info->time = 0; } info->tfrf_offset = 0; mov_write_tfrf_tags(pb, mov, track); } return 0; } static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max) { int i; for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if ((tracks >= 0 && i != tracks) || !track->entry) continue; if (track->nb_frag_info > max) { memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info)); track->nb_frag_info = max; } } } static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tfdt"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb64(pb, track->frag_start); return update_size(pb, pos); } static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int64_t moof_offset, int moof_size) { int64_t pos = avio_tell(pb); int i, start = 0; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "traf"); mov_write_tfhd_tag(pb, mov, track, moof_offset); if (mov->mode != MODE_ISM) mov_write_tfdt_tag(pb, track); for (i = 1; i < track->entry; i++) { if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) { mov_write_trun_tag(pb, mov, track, moof_size, start, i); start = i; } } mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry); if (mov->mode == MODE_ISM) { mov_write_tfxd_tag(pb, track); if (mov->ism_lookahead) { int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead; if (track->nb_frag_info > 0) { MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1]; if (!info->tfrf_offset) info->tfrf_offset = avio_tell(pb); } avio_wb32(pb, 8 + size); ffio_wfourcc(pb, "free"); for (i = 0; i < size; i++) avio_w8(pb, 0); } } return update_size(pb, pos); } static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov, int tracks, int moof_size) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "moof"); mov->first_trun = 1; mov_write_mfhd_tag(pb, mov); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (tracks >= 0 && i != tracks) continue; if (!track->entry) continue; mov_write_traf_tag(pb, mov, track, pos, moof_size); } return update_size(pb, pos); } static int mov_write_sidx_tag(AVIOContext *pb, MOVTrack *track, int ref_size, int total_sidx_size) { int64_t pos = avio_tell(pb), offset_pos, end_pos; int64_t presentation_time, duration, offset; int starts_with_SAP, i, entries; if (track->entry) { entries = 1; presentation_time = track->start_dts + track->frag_start + track->cluster[0].cts; duration = track->end_pts - (track->cluster[0].dts + track->cluster[0].cts); starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE; // pts<0 should be cut away using edts if (presentation_time < 0) { duration += presentation_time; presentation_time = 0; } } else { entries = track->nb_frag_info; if (entries <= 0) return 0; presentation_time = track->frag_info[0].time; } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "sidx"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb32(pb, track->track_id); /* reference_ID */ avio_wb32(pb, track->timescale); /* timescale */ avio_wb64(pb, presentation_time); /* earliest_presentation_time */ offset_pos = avio_tell(pb); avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */ avio_wb16(pb, 0); /* reserved */ avio_wb16(pb, entries); /* reference_count */ for (i = 0; i < entries; i++) { if (!track->entry) { if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) { av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n"); } duration = track->frag_info[i].duration; ref_size = track->frag_info[i].size; starts_with_SAP = 1; } avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */ avio_wb32(pb, duration); /* subsegment_duration */ avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */ } end_pos = avio_tell(pb); offset = pos + total_sidx_size - end_pos; avio_seek(pb, offset_pos, SEEK_SET); avio_wb64(pb, offset); avio_seek(pb, end_pos, SEEK_SET); return update_size(pb, pos); } static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov, int tracks, int ref_size) { int i, round, ret; AVIOContext *avio_buf; int total_size = 0; for (round = 0; round < 2; round++) { // First run one round to calculate the total size of all // sidx atoms. // This would be much simpler if we'd only write one sidx // atom, for the first track in the moof. if (round == 0) { if ((ret = ffio_open_null_buf(&avio_buf)) < 0) return ret; } else { avio_buf = pb; } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (tracks >= 0 && i != tracks) continue; // When writing a sidx for the full file, entry is 0, but // we want to include all tracks. ref_size is 0 in this case, // since we read it from frag_info instead. if (!track->entry && ref_size > 0) continue; total_size -= mov_write_sidx_tag(avio_buf, track, ref_size, total_size); } if (round == 0) total_size = ffio_close_null_buf(avio_buf); } return 0; } static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks) { int64_t pos = avio_tell(pb), pts_us, ntp_ts; MOVTrack *first_track; /* PRFT should be associated with at most one track. So, choosing only the * first track. */ if (tracks > 0) return 0; first_track = &(mov->tracks[0]); if (!first_track->entry) { av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n"); return 0; } if (first_track->cluster[0].pts == AV_NOPTS_VALUE) { av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n"); return 0; } if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) { ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time()); } else if (mov->write_prft == MOV_PRFT_SRC_PTS) { pts_us = av_rescale_q(first_track->cluster[0].pts, first_track->st->time_base, AV_TIME_BASE_Q); ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US); } else { av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n", mov->write_prft); return 0; } avio_wb32(pb, 0); // Size place holder ffio_wfourcc(pb, "prft"); // Type avio_w8(pb, 1); // Version avio_wb24(pb, 0); // Flags avio_wb32(pb, first_track->track_id); // reference track ID avio_wb64(pb, ntp_ts); // NTP time stamp avio_wb64(pb, first_track->cluster[0].pts); //media time return update_size(pb, pos); } static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks, int64_t mdat_size) { AVIOContext *avio_buf; int ret, moof_size; if ((ret = ffio_open_null_buf(&avio_buf)) < 0) return ret; mov_write_moof_tag_internal(avio_buf, mov, tracks, 0); moof_size = ffio_close_null_buf(avio_buf); if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size); if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB) mov_write_prft_tag(pb, mov, tracks); if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX || !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) || mov->ism_lookahead) { if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0) return ret; if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) && mov->flags & FF_MOV_FLAG_SKIP_TRAILER) { mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1); } } return mov_write_moof_tag_internal(pb, mov, tracks, moof_size); } static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "tfra"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb32(pb, track->track_id); avio_wb32(pb, 0); /* length of traf/trun/sample num */ avio_wb32(pb, track->nb_frag_info); for (i = 0; i < track->nb_frag_info; i++) { avio_wb64(pb, track->frag_info[i].time); avio_wb64(pb, track->frag_info[i].offset + track->data_offset); avio_w8(pb, 1); /* traf number */ avio_w8(pb, 1); /* trun number */ avio_w8(pb, 1); /* sample number */ } return update_size(pb, pos); } static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "mfra"); /* An empty mfra atom is enough to indicate to the publishing point that * the stream has ended. */ if (mov->flags & FF_MOV_FLAG_ISML) return update_size(pb, pos); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->nb_frag_info) mov_write_tfra_tag(pb, track); } avio_wb32(pb, 16); ffio_wfourcc(pb, "mfro"); avio_wb32(pb, 0); /* version + flags */ avio_wb32(pb, avio_tell(pb) + 4 - pos); return update_size(pb, pos); } static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov) { avio_wb32(pb, 8); // placeholder for extended size field (64 bit) ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free"); mov->mdat_pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "mdat"); return 0; } /* TODO: This needs to be more general */ static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int64_t pos = avio_tell(pb); int has_h264 = 0, has_video = 0; int minor = 0x200; int i; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (is_cover_image(st)) continue; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) has_video = 1; if (st->codecpar->codec_id == AV_CODEC_ID_H264) has_h264 = 1; } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ftyp"); if (mov->major_brand && strlen(mov->major_brand) >= 4) ffio_wfourcc(pb, mov->major_brand); else if (mov->mode == MODE_3GP) { ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4"); minor = has_h264 ? 0x100 : 0x200; } else if (mov->mode & MODE_3G2) { ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a"); minor = has_h264 ? 0x20000 : 0x10000; } else if (mov->mode == MODE_PSP) ffio_wfourcc(pb, "MSNV"); else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) ffio_wfourcc(pb, "iso4"); else if (mov->mode == MODE_MP4) ffio_wfourcc(pb, "isom"); else if (mov->mode == MODE_IPOD) ffio_wfourcc(pb, has_video ? "M4V ":"M4A "); else if (mov->mode == MODE_ISM) ffio_wfourcc(pb, "isml"); else if (mov->mode == MODE_F4V) ffio_wfourcc(pb, "f4v "); else ffio_wfourcc(pb, "qt "); avio_wb32(pb, minor); if (mov->mode == MODE_MOV) ffio_wfourcc(pb, "qt "); else if (mov->mode == MODE_ISM) { ffio_wfourcc(pb, "piff"); } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) { ffio_wfourcc(pb, "isom"); ffio_wfourcc(pb, "iso2"); if (has_h264) ffio_wfourcc(pb, "avc1"); } // We add tfdt atoms when fragmenting, signal this with the iso6 compatible // brand. This is compatible with users that don't understand tfdt. if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM) ffio_wfourcc(pb, "iso6"); if (mov->mode == MODE_3GP) ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4"); else if (mov->mode & MODE_3G2) ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a"); else if (mov->mode == MODE_PSP) ffio_wfourcc(pb, "MSNV"); else if (mov->mode == MODE_MP4) ffio_wfourcc(pb, "mp41"); if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) ffio_wfourcc(pb, "dash"); return update_size(pb, pos); } static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s) { AVStream *video_st = s->streams[0]; AVCodecParameters *video_par = s->streams[0]->codecpar; AVCodecParameters *audio_par = s->streams[1]->codecpar; int audio_rate = audio_par->sample_rate; int64_t frame_rate = video_st->avg_frame_rate.den ? (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den : 0; int audio_kbitrate = audio_par->bit_rate / 1000; int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate); if (frame_rate < 0 || frame_rate > INT32_MAX) { av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000); return AVERROR(EINVAL); } avio_wb32(pb, 0x94); /* size */ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "PROF"); avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */ avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x3); /* 3 sections ? */ avio_wb32(pb, 0x14); /* size */ ffio_wfourcc(pb, "FPRF"); avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x2c); /* size */ ffio_wfourcc(pb, "APRF"); /* audio */ avio_wb32(pb, 0x0); avio_wb32(pb, 0x2); /* TrackID */ ffio_wfourcc(pb, "mp4a"); avio_wb32(pb, 0x20f); avio_wb32(pb, 0x0); avio_wb32(pb, audio_kbitrate); avio_wb32(pb, audio_kbitrate); avio_wb32(pb, audio_rate); avio_wb32(pb, audio_par->channels); avio_wb32(pb, 0x34); /* size */ ffio_wfourcc(pb, "VPRF"); /* video */ avio_wb32(pb, 0x0); avio_wb32(pb, 0x1); /* TrackID */ if (video_par->codec_id == AV_CODEC_ID_H264) { ffio_wfourcc(pb, "avc1"); avio_wb16(pb, 0x014D); avio_wb16(pb, 0x0015); } else { ffio_wfourcc(pb, "mp4v"); avio_wb16(pb, 0x0000); avio_wb16(pb, 0x0103); } avio_wb32(pb, 0x0); avio_wb32(pb, video_kbitrate); avio_wb32(pb, video_kbitrate); avio_wb32(pb, frame_rate); avio_wb32(pb, frame_rate); avio_wb16(pb, video_par->width); avio_wb16(pb, video_par->height); avio_wb32(pb, 0x010001); /* ? */ return 0; } static int mov_write_identification(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; mov_write_ftyp_tag(pb,s); if (mov->mode == MODE_PSP) { int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (is_cover_image(st)) continue; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) video_streams_nb++; else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) audio_streams_nb++; else other_streams_nb++; } if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) { av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n"); return AVERROR(EINVAL); } return mov_write_uuidprof_tag(pb, s); } return 0; } static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags) { uint32_t c = -1; int i, closed_gop = 0; for (i = 0; i < pkt->size - 4; i++) { c = (c << 8) + pkt->data[i]; if (c == 0x1b8) { // gop closed_gop = pkt->data[i + 4] >> 6 & 0x01; } else if (c == 0x100) { // pic int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6); if (!temp_ref || closed_gop) // I picture is not reordered *flags = MOV_SYNC_SAMPLE; else *flags = MOV_PARTIAL_SYNC_SAMPLE; break; } } return 0; } static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk) { const uint8_t *start, *next, *end = pkt->data + pkt->size; int seq = 0, entry = 0; int key = pkt->flags & AV_PKT_FLAG_KEY; start = find_next_marker(pkt->data, end); for (next = start; next < end; start = next) { next = find_next_marker(start + 4, end); switch (AV_RB32(start)) { case VC1_CODE_SEQHDR: seq = 1; break; case VC1_CODE_ENTRYPOINT: entry = 1; break; case VC1_CODE_SLICE: trk->vc1_info.slices = 1; break; } } if (!trk->entry && trk->vc1_info.first_packet_seen) trk->vc1_info.first_frag_written = 1; if (!trk->entry && !trk->vc1_info.first_frag_written) { /* First packet in first fragment */ trk->vc1_info.first_packet_seq = seq; trk->vc1_info.first_packet_entry = entry; trk->vc1_info.first_packet_seen = 1; } else if ((seq && !trk->vc1_info.packet_seq) || (entry && !trk->vc1_info.packet_entry)) { int i; for (i = 0; i < trk->entry; i++) trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE; trk->has_keyframes = 0; if (seq) trk->vc1_info.packet_seq = 1; if (entry) trk->vc1_info.packet_entry = 1; if (!trk->vc1_info.first_frag_written) { /* First fragment */ if ((!seq || trk->vc1_info.first_packet_seq) && (!entry || trk->vc1_info.first_packet_entry)) { /* First packet had the same headers as this one, readd the * sync sample flag. */ trk->cluster[0].flags |= MOV_SYNC_SAMPLE; trk->has_keyframes = 1; } } } if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry) key = seq && entry; else if (trk->vc1_info.packet_seq) key = seq; else if (trk->vc1_info.packet_entry) key = entry; if (key) { trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE; trk->has_keyframes++; } } static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; int ret, buf_size; uint8_t *buf; int i, offset; if (!track->mdat_buf) return 0; if (!mov->mdat_buf) { if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0) return ret; } buf_size = avio_close_dyn_buf(track->mdat_buf, &buf); track->mdat_buf = NULL; offset = avio_tell(mov->mdat_buf); avio_write(mov->mdat_buf, buf, buf_size); av_free(buf); for (i = track->entries_flushed; i < track->entry; i++) track->cluster[i].pos += offset; track->entries_flushed = track->entry; return 0; } static int mov_flush_fragment(AVFormatContext *s, int force) { MOVMuxContext *mov = s->priv_data; int i, first_track = -1; int64_t mdat_size = 0; int ret; int has_video = 0, starts_with_key = 0, first_video_track = 1; if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) return 0; // Try to fill in the duration of the last packet in each stream // from queued packets in the interleave queues. If the flushing // of fragments was triggered automatically by an AVPacket, we // already have reliable info for the end of that track, but other // tracks may need to be filled in. for (i = 0; i < s->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (!track->end_reliable) { AVPacket pkt; if (!ff_interleaved_peek(s, i, &pkt, 1)) { if (track->dts_shift != AV_NOPTS_VALUE) pkt.dts += track->dts_shift; track->track_duration = pkt.dts - track->start_dts; if (pkt.pts != AV_NOPTS_VALUE) track->end_pts = pkt.pts; else track->end_pts = pkt.dts; } } } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->entry <= 1) continue; // Sample durations are calculated as the diff of dts values, // but for the last sample in a fragment, we don't know the dts // of the first sample in the next fragment, so we have to rely // on what was set as duration in the AVPacket. Not all callers // set this though, so we might want to replace it with an // estimate if it currently is zero. if (get_cluster_duration(track, track->entry - 1) != 0) continue; // Use the duration (i.e. dts diff) of the second last sample for // the last one. This is a wild guess (and fatal if it turns out // to be too long), but probably the best we can do - having a zero // duration is bad as well. track->track_duration += get_cluster_duration(track, track->entry - 2); track->end_pts += get_cluster_duration(track, track->entry - 2); if (!mov->missing_duration_warned) { av_log(s, AV_LOG_WARNING, "Estimating the duration of the last packet in a " "fragment, consider setting the duration field in " "AVPacket instead.\n"); mov->missing_duration_warned = 1; } } if (!mov->moov_written) { int64_t pos = avio_tell(s->pb); uint8_t *buf; int buf_size, moov_size; for (i = 0; i < mov->nb_streams; i++) if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st)) break; /* Don't write the initial moov unless all tracks have data */ if (i < mov->nb_streams && !force) return 0; moov_size = get_moov_size(s); for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset = pos + moov_size + 8; avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER); if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) mov_write_identification(s->pb, s); if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0) return ret; if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) { if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(s->pb); avio_flush(s->pb); mov->moov_written = 1; return 0; } buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf); mov->mdat_buf = NULL; avio_wb32(s->pb, buf_size + 8); ffio_wfourcc(s->pb, "mdat"); avio_write(s->pb, buf, buf_size); av_free(buf); if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(s->pb); mov->moov_written = 1; mov->mdat_size = 0; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry) mov->tracks[i].frag_start += mov->tracks[i].start_dts + mov->tracks[i].track_duration - mov->tracks[i].cluster[0].dts; mov->tracks[i].entry = 0; mov->tracks[i].end_reliable = 0; } avio_flush(s->pb); return 0; } if (mov->frag_interleave) { for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; int ret; if ((ret = mov_flush_fragment_interleaving(s, track)) < 0) return ret; } if (!mov->mdat_buf) return 0; mdat_size = avio_tell(mov->mdat_buf); } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave) track->data_offset = 0; else track->data_offset = mdat_size; if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { has_video = 1; if (first_video_track) { if (track->entry) starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE; first_video_track = 0; } } if (!track->entry) continue; if (track->mdat_buf) mdat_size += avio_tell(track->mdat_buf); if (first_track < 0) first_track = i; } if (!mdat_size) return 0; avio_write_marker(s->pb, av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale), (has_video ? starts_with_key : mov->tracks[first_track].cluster[0].flags & MOV_SYNC_SAMPLE) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; int buf_size, write_moof = 1, moof_tracks = -1; uint8_t *buf; int64_t duration = 0; if (track->entry) duration = track->start_dts + track->track_duration - track->cluster[0].dts; if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) { if (!track->mdat_buf) continue; mdat_size = avio_tell(track->mdat_buf); moof_tracks = i; } else { write_moof = i == first_track; } if (write_moof) { avio_flush(s->pb); mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size); mov->fragments++; avio_wb32(s->pb, mdat_size + 8); ffio_wfourcc(s->pb, "mdat"); } if (track->entry) track->frag_start += duration; track->entry = 0; track->entries_flushed = 0; track->end_reliable = 0; if (!mov->frag_interleave) { if (!track->mdat_buf) continue; buf_size = avio_close_dyn_buf(track->mdat_buf, &buf); track->mdat_buf = NULL; } else { if (!mov->mdat_buf) continue; buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf); mov->mdat_buf = NULL; } avio_write(s->pb, buf, buf_size); av_free(buf); } mov->mdat_size = 0; avio_flush(s->pb); return 0; } static int mov_auto_flush_fragment(AVFormatContext *s, int force) { MOVMuxContext *mov = s->priv_data; int had_moov = mov->moov_written; int ret = mov_flush_fragment(s, force); if (ret < 0) return ret; // If using delay_moov, the first flush only wrote the moov, // not the actual moof+mdat pair, thus flush once again. if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV) ret = mov_flush_fragment(s, force); return ret; } static int check_pkt(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk = &mov->tracks[pkt->stream_index]; int64_t ref; uint64_t duration; if (trk->entry) { ref = trk->cluster[trk->entry - 1].dts; } else if ( trk->start_dts != AV_NOPTS_VALUE && !trk->frag_discont) { ref = trk->start_dts + trk->track_duration; } else ref = pkt->dts; // Skip tests for the first packet if (trk->dts_shift != AV_NOPTS_VALUE) { /* With negative CTS offsets we have set an offset to the DTS, * reverse this for the check. */ ref -= trk->dts_shift; } duration = pkt->dts - ref; if (pkt->dts < ref || duration >= INT_MAX) { av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n", duration, pkt->dts ); pkt->dts = ref + 1; pkt->pts = AV_NOPTS_VALUE; } if (pkt->duration < 0 || pkt->duration > INT_MAX) { av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration); return AVERROR(EINVAL); } return 0; } int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; AVIOContext *pb = s->pb; MOVTrack *trk = &mov->tracks[pkt->stream_index]; AVCodecParameters *par = trk->par; unsigned int samples_in_chunk = 0; int size = pkt->size, ret = 0; uint8_t *reformatted_data = NULL; ret = check_pkt(s, pkt); if (ret < 0) return ret; if (mov->flags & FF_MOV_FLAG_FRAGMENT) { int ret; if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { if (mov->frag_interleave && mov->fragments > 0) { if (trk->entry - trk->entries_flushed >= mov->frag_interleave) { if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0) return ret; } } if (!trk->mdat_buf) { if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0) return ret; } pb = trk->mdat_buf; } else { if (!mov->mdat_buf) { if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0) return ret; } pb = mov->mdat_buf; } } if (par->codec_id == AV_CODEC_ID_AMR_NB) { /* We must find out how many AMR blocks there are in one packet */ static const uint16_t packed_size[16] = {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1}; int len = 0; while (len < size && samples_in_chunk < 100) { len += packed_size[(pkt->data[len] >> 3) & 0x0F]; samples_in_chunk++; } if (samples_in_chunk > 1) { av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n"); return -1; } } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS || par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) { samples_in_chunk = trk->par->frame_size; } else if (trk->sample_size) samples_in_chunk = size / trk->sample_size; else samples_in_chunk = 1; /* copy extradata if it exists */ if (trk->vos_len == 0 && par->extradata_size > 0 && !TAG_IS_AVCI(trk->tag) && (par->codec_id != AV_CODEC_ID_DNXHD)) { trk->vos_len = par->extradata_size; trk->vos_data = av_malloc(trk->vos_len); if (!trk->vos_data) { ret = AVERROR(ENOMEM); goto err; } memcpy(trk->vos_data, par->extradata, trk->vos_len); } if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { if (!s->streams[pkt->stream_index]->nb_frames) { av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: " "use the audio bitstream filter 'aac_adtstoasc' to fix it " "('-bsf:a aac_adtstoasc' option with ffmpeg)\n"); return -1; } av_log(s, AV_LOG_WARNING, "aac bitstream error\n"); } if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) { /* from x264 or from bytestream H.264 */ /* NAL reformatting needed */ if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) { ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data, &size); avio_write(pb, reformatted_data, size); } else { if (trk->cenc.aes_ctr) { size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size); if (size < 0) { ret = size; goto err; } } else { size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size); } } } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 && (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) { /* extradata is Annex B, assume the bitstream is too and convert it */ if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) { ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL); avio_write(pb, reformatted_data, size); } else { size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL); } #if CONFIG_AC3_PARSER } else if (par->codec_id == AV_CODEC_ID_EAC3) { size = handle_eac3(mov, pkt, trk); if (size < 0) return size; else if (!size) goto end; avio_write(pb, pkt->data, size); #endif } else { if (trk->cenc.aes_ctr) { if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) { int nal_size_length = (par->extradata[4] & 0x3) + 1; ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size); } else { ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size); } if (ret) { goto err; } } else { avio_write(pb, pkt->data, size); } } if ((par->codec_id == AV_CODEC_ID_DNXHD || par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) { /* copy frame to create needed atoms */ trk->vos_len = size; trk->vos_data = av_malloc(size); if (!trk->vos_data) { ret = AVERROR(ENOMEM); goto err; } memcpy(trk->vos_data, pkt->data, size); } if (trk->entry >= trk->cluster_capacity) { unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE); if (av_reallocp_array(&trk->cluster, new_capacity, sizeof(*trk->cluster))) { ret = AVERROR(ENOMEM); goto err; } trk->cluster_capacity = new_capacity; } trk->cluster[trk->entry].pos = avio_tell(pb) - size; trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk; trk->cluster[trk->entry].chunkNum = 0; trk->cluster[trk->entry].size = size; trk->cluster[trk->entry].entries = samples_in_chunk; trk->cluster[trk->entry].dts = pkt->dts; trk->cluster[trk->entry].pts = pkt->pts; if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) { if (!trk->frag_discont) { /* First packet of a new fragment. We already wrote the duration * of the last packet of the previous fragment based on track_duration, * which might not exactly match our dts. Therefore adjust the dts * of this packet to be what the previous packets duration implies. */ trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration; /* We also may have written the pts and the corresponding duration * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with * the next fragment. This means the cts of the first sample must * be the same in all fragments, unless end_pts was updated by * the packet causing the fragment to be written. */ if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) || mov->mode == MODE_ISM) pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts; } else { /* New fragment, but discontinuous from previous fragments. * Pretend the duration sum of the earlier fragments is * pkt->dts - trk->start_dts. */ trk->frag_start = pkt->dts - trk->start_dts; trk->end_pts = AV_NOPTS_VALUE; trk->frag_discont = 0; } } if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) { /* Not using edit lists and shifting the first track to start from zero. * If the other streams start from a later timestamp, we won't be able * to signal the difference in starting time without an edit list. * Thus move the timestamp for this first sample to 0, increasing * its duration instead. */ trk->cluster[trk->entry].dts = trk->start_dts = 0; } if (trk->start_dts == AV_NOPTS_VALUE) { trk->start_dts = pkt->dts; if (trk->frag_discont) { if (mov->use_editlist) { /* Pretend the whole stream started at pts=0, with earlier fragments * already written. If the stream started at pts=0, the duration sum * of earlier fragments would have been pkt->pts. */ trk->frag_start = pkt->pts; trk->start_dts = pkt->dts - pkt->pts; } else { /* Pretend the whole stream started at dts=0, with earlier fragments * already written, with a duration summing up to pkt->dts. */ trk->frag_start = pkt->dts; trk->start_dts = 0; } trk->frag_discont = 0; } else if (pkt->dts && mov->moov_written) av_log(s, AV_LOG_WARNING, "Track %d starts with a nonzero dts %"PRId64", while the moov " "already has been written. Set the delay_moov flag to handle " "this case.\n", pkt->stream_index, pkt->dts); } trk->track_duration = pkt->dts - trk->start_dts + pkt->duration; trk->last_sample_is_subtitle_end = 0; if (pkt->pts == AV_NOPTS_VALUE) { av_log(s, AV_LOG_WARNING, "pts has no value\n"); pkt->pts = pkt->dts; } if (pkt->dts != pkt->pts) trk->flags |= MOV_TRACK_CTTS; trk->cluster[trk->entry].cts = pkt->pts - pkt->dts; trk->cluster[trk->entry].flags = 0; if (trk->start_cts == AV_NOPTS_VALUE) trk->start_cts = pkt->pts - pkt->dts; if (trk->end_pts == AV_NOPTS_VALUE) trk->end_pts = trk->cluster[trk->entry].dts + trk->cluster[trk->entry].cts + pkt->duration; else trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts + trk->cluster[trk->entry].cts + pkt->duration); if (par->codec_id == AV_CODEC_ID_VC1) { mov_parse_vc1_frame(pkt, trk); } else if (pkt->flags & AV_PKT_FLAG_KEY) { if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO && trk->entry > 0) { // force sync sample for the first key frame mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags); if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE) trk->flags |= MOV_TRACK_STPS; } else { trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE; } if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE) trk->has_keyframes++; } if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) { trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE; trk->has_disposable++; } trk->entry++; trk->sample_count += samples_in_chunk; mov->mdat_size += size; if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry, reformatted_data, size); end: err: av_free(reformatted_data); return ret; } static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk = &mov->tracks[pkt->stream_index]; AVCodecParameters *par = trk->par; int64_t frag_duration = 0; int size = pkt->size; int ret = check_pkt(s, pkt); if (ret < 0) return ret; if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) { int i; for (i = 0; i < s->nb_streams; i++) mov->tracks[i].frag_discont = 1; mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT; } if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) { if (trk->dts_shift == AV_NOPTS_VALUE) trk->dts_shift = pkt->pts - pkt->dts; pkt->dts += trk->dts_shift; } if (trk->par->codec_id == AV_CODEC_ID_MP4ALS || trk->par->codec_id == AV_CODEC_ID_AAC || trk->par->codec_id == AV_CODEC_ID_FLAC) { int side_size = 0; uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size); if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) { void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!newextra) return AVERROR(ENOMEM); av_free(par->extradata); par->extradata = newextra; memcpy(par->extradata, side, side_size); par->extradata_size = side_size; if (!pkt->size) // Flush packet mov->need_rewrite_extradata = 1; } } if (!pkt->size) { if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) { trk->start_dts = pkt->dts; if (pkt->pts != AV_NOPTS_VALUE) trk->start_cts = pkt->pts - pkt->dts; else trk->start_cts = 0; } return 0; /* Discard 0 sized packets */ } if (trk->entry && pkt->stream_index < s->nb_streams) frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts, s->streams[pkt->stream_index]->time_base, AV_TIME_BASE_Q); if ((mov->max_fragment_duration && frag_duration >= mov->max_fragment_duration) || (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) || (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME && par->codec_type == AVMEDIA_TYPE_VIDEO && trk->entry && pkt->flags & AV_PKT_FLAG_KEY) || (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) { if (frag_duration >= mov->min_fragment_duration) { // Set the duration of this track to line up with the next // sample in this track. This avoids relying on AVPacket // duration, but only helps for this particular track, not // for the other ones that are flushed at the same time. trk->track_duration = pkt->dts - trk->start_dts; if (pkt->pts != AV_NOPTS_VALUE) trk->end_pts = pkt->pts; else trk->end_pts = pkt->dts; trk->end_reliable = 1; mov_auto_flush_fragment(s, 0); } } return ff_mov_write_packet(s, pkt); } static int mov_write_subtitle_end_packet(AVFormatContext *s, int stream_index, int64_t dts) { AVPacket end; uint8_t data[2] = {0}; int ret; av_init_packet(&end); end.size = sizeof(data); end.data = data; end.pts = dts; end.dts = dts; end.duration = 0; end.stream_index = stream_index; ret = mov_write_single_packet(s, &end); av_packet_unref(&end); return ret; } static int mov_write_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk; if (!pkt) { mov_flush_fragment(s, 1); return 1; } trk = &mov->tracks[pkt->stream_index]; if (is_cover_image(trk->st)) { int ret; if (trk->st->nb_frames >= 1) { if (trk->st->nb_frames == 1) av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d," " ignoring.\n", pkt->stream_index); return 0; } if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0) return ret; return 0; } else { int i; if (!pkt->size) return mov_write_single_packet(s, pkt); /* Passthrough. */ /* * Subtitles require special handling. * * 1) For full complaince, every track must have a sample at * dts == 0, which is rarely true for subtitles. So, as soon * as we see any packet with dts > 0, write an empty subtitle * at dts == 0 for any subtitle track with no samples in it. * * 2) For each subtitle track, check if the current packet's * dts is past the duration of the last subtitle sample. If * so, we now need to write an end sample for that subtitle. * * This must be done conditionally to allow for subtitles that * immediately replace each other, in which case an end sample * is not needed, and is, in fact, actively harmful. * * 3) See mov_write_trailer for how the final end sample is * handled. */ for (i = 0; i < mov->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; int ret; if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT && trk->track_duration < pkt->dts && (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) { ret = mov_write_subtitle_end_packet(s, i, trk->track_duration); if (ret < 0) return ret; trk->last_sample_is_subtitle_end = 1; } } if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) { AVPacket *opkt = pkt; int reshuffle_ret, ret; if (trk->is_unaligned_qt_rgb) { int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16; int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2; reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride); if (reshuffle_ret < 0) return reshuffle_ret; } else reshuffle_ret = 0; if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) { ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette); if (ret < 0) goto fail; if (ret) trk->pal_done++; } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO && (trk->par->format == AV_PIX_FMT_GRAY8 || trk->par->format == AV_PIX_FMT_MONOBLACK)) { for (i = 0; i < pkt->size; i++) pkt->data[i] = ~pkt->data[i]; } if (reshuffle_ret) { ret = mov_write_single_packet(s, pkt); fail: if (reshuffle_ret) av_packet_free(&pkt); return ret; } } return mov_write_single_packet(s, pkt); } } // QuickTime chapters involve an additional text track with the chapter names // as samples, and a tref pointing from the other tracks to the chapter one. static int mov_create_chapter_track(AVFormatContext *s, int tracknum) { AVIOContext *pb; MOVMuxContext *mov = s->priv_data; MOVTrack *track = &mov->tracks[tracknum]; AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY }; int i, len; track->mode = mov->mode; track->tag = MKTAG('t','e','x','t'); track->timescale = MOV_TIMESCALE; track->par = avcodec_parameters_alloc(); if (!track->par) return AVERROR(ENOMEM); track->par->codec_type = AVMEDIA_TYPE_SUBTITLE; #if 0 // These properties are required to make QT recognize the chapter track uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, }; if (ff_alloc_extradata(track->par, sizeof(chapter_properties))) return AVERROR(ENOMEM); memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties)); #else if (avio_open_dyn_buf(&pb) >= 0) { int size; uint8_t *buf; /* Stub header (usually for Quicktime chapter track) */ // TextSampleEntry avio_wb32(pb, 0x01); // displayFlags avio_w8(pb, 0x00); // horizontal justification avio_w8(pb, 0x00); // vertical justification avio_w8(pb, 0x00); // bgColourRed avio_w8(pb, 0x00); // bgColourGreen avio_w8(pb, 0x00); // bgColourBlue avio_w8(pb, 0x00); // bgColourAlpha // BoxRecord avio_wb16(pb, 0x00); // defTextBoxTop avio_wb16(pb, 0x00); // defTextBoxLeft avio_wb16(pb, 0x00); // defTextBoxBottom avio_wb16(pb, 0x00); // defTextBoxRight // StyleRecord avio_wb16(pb, 0x00); // startChar avio_wb16(pb, 0x00); // endChar avio_wb16(pb, 0x01); // fontID avio_w8(pb, 0x00); // fontStyleFlags avio_w8(pb, 0x00); // fontSize avio_w8(pb, 0x00); // fgColourRed avio_w8(pb, 0x00); // fgColourGreen avio_w8(pb, 0x00); // fgColourBlue avio_w8(pb, 0x00); // fgColourAlpha // FontTableBox avio_wb32(pb, 0x0D); // box size ffio_wfourcc(pb, "ftab"); // box atom name avio_wb16(pb, 0x01); // entry count // FontRecord avio_wb16(pb, 0x01); // font ID avio_w8(pb, 0x00); // font name length if ((size = avio_close_dyn_buf(pb, &buf)) > 0) { track->par->extradata = buf; track->par->extradata_size = size; } else { av_freep(&buf); } } #endif for (i = 0; i < s->nb_chapters; i++) { AVChapter *c = s->chapters[i]; AVDictionaryEntry *t; int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE}); pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE}); pkt.duration = end - pkt.dts; if ((t = av_dict_get(c->metadata, "title", NULL, 0))) { static const char encd[12] = { 0x00, 0x00, 0x00, 0x0C, 'e', 'n', 'c', 'd', 0x00, 0x00, 0x01, 0x00 }; len = strlen(t->value); pkt.size = len + 2 + 12; pkt.data = av_malloc(pkt.size); if (!pkt.data) return AVERROR(ENOMEM); AV_WB16(pkt.data, len); memcpy(pkt.data + 2, t->value, len); memcpy(pkt.data + len + 2, encd, sizeof(encd)); ff_mov_write_packet(s, &pkt); av_freep(&pkt.data); } } return 0; } static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr) { int ret; /* compute the frame number */ ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s); return ret; } static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc) { int ret; MOVMuxContext *mov = s->priv_data; MOVTrack *track = &mov->tracks[index]; AVStream *src_st = s->streams[src_index]; AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4}; AVRational rate = find_fps(s, src_st); /* tmcd track based on video stream */ track->mode = mov->mode; track->tag = MKTAG('t','m','c','d'); track->src_track = src_index; track->timescale = mov->tracks[src_index].timescale; if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME) track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME; /* set st to src_st for metadata access*/ track->st = src_st; /* encode context: tmcd data stream */ track->par = avcodec_parameters_alloc(); if (!track->par) return AVERROR(ENOMEM); track->par->codec_type = AVMEDIA_TYPE_DATA; track->par->codec_tag = track->tag; track->st->avg_frame_rate = av_inv_q(rate); /* the tmcd track just contains one packet with the frame number */ pkt.data = av_malloc(pkt.size); if (!pkt.data) return AVERROR(ENOMEM); AV_WB32(pkt.data, tc.start); ret = ff_mov_write_packet(s, &pkt); av_free(pkt.data); return ret; } /* * st->disposition controls the "enabled" flag in the tkhd tag. * QuickTime will not play a track if it is not enabled. So make sure * that one track of each type (audio, video, subtitle) is enabled. * * Subtitles are special. For audio and video, setting "enabled" also * makes the track "default" (i.e. it is rendered when played). For * subtitles, an "enabled" subtitle is not rendered by default, but * if no subtitle is enabled, the subtitle menu in QuickTime will be * empty! */ static void enable_tracks(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; int enabled[AVMEDIA_TYPE_NB]; int first[AVMEDIA_TYPE_NB]; for (i = 0; i < AVMEDIA_TYPE_NB; i++) { enabled[i] = 0; first[i] = -1; } for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN || st->codecpar->codec_type >= AVMEDIA_TYPE_NB || is_cover_image(st)) continue; if (first[st->codecpar->codec_type] < 0) first[st->codecpar->codec_type] = i; if (st->disposition & AV_DISPOSITION_DEFAULT) { mov->tracks[i].flags |= MOV_TRACK_ENABLED; enabled[st->codecpar->codec_type]++; } } for (i = 0; i < AVMEDIA_TYPE_NB; i++) { switch (i) { case AVMEDIA_TYPE_VIDEO: case AVMEDIA_TYPE_AUDIO: case AVMEDIA_TYPE_SUBTITLE: if (enabled[i] > 1) mov->per_stream_grouping = 1; if (!enabled[i] && first[i] >= 0) mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED; break; } } } static void mov_free(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; if (mov->chapter_track) { if (mov->tracks[mov->chapter_track].par) av_freep(&mov->tracks[mov->chapter_track].par->extradata); av_freep(&mov->tracks[mov->chapter_track].par); } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) ff_mov_close_hinting(&mov->tracks[i]); else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd) av_freep(&mov->tracks[i].par); av_freep(&mov->tracks[i].cluster); av_freep(&mov->tracks[i].frag_info); av_packet_unref(&mov->tracks[i].cover_image); if (mov->tracks[i].vos_len) av_freep(&mov->tracks[i].vos_data); ff_mov_cenc_free(&mov->tracks[i].cenc); } av_freep(&mov->tracks); } static uint32_t rgb_to_yuv(uint32_t rgb) { uint8_t r, g, b; int y, cb, cr; r = (rgb >> 16) & 0xFF; g = (rgb >> 8) & 0xFF; b = (rgb ) & 0xFF; y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000); cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000); cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000); return (y << 16) | (cr << 8) | cb; } static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track, AVStream *st) { int i, width = 720, height = 480; int have_palette = 0, have_size = 0; uint32_t palette[16]; char *cur = st->codecpar->extradata; while (cur && *cur) { if (strncmp("palette:", cur, 8) == 0) { int i, count; count = sscanf(cur + 8, "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"", &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3], &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7], &palette[ 8], &palette[ 9], &palette[10], &palette[11], &palette[12], &palette[13], &palette[14], &palette[15]); for (i = 0; i < count; i++) { palette[i] = rgb_to_yuv(palette[i]); } have_palette = 1; } else if (!strncmp("size:", cur, 5)) { sscanf(cur + 5, "%dx%d", &width, &height); have_size = 1; } if (have_palette && have_size) break; cur += strcspn(cur, "\n\r"); cur += strspn(cur, "\n\r"); } if (have_palette) { track->vos_data = av_malloc(16*4); if (!track->vos_data) return AVERROR(ENOMEM); for (i = 0; i < 16; i++) { AV_WB32(track->vos_data + i * 4, palette[i]); } track->vos_len = 16 * 4; } st->codecpar->width = width; st->codecpar->height = track->height = height; return 0; } static int mov_init(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0); int i, ret; mov->fc = s; /* Default mode == MP4 */ mov->mode = MODE_MP4; if (s->oformat) { if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP; else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2; else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV; else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP; else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD; else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM; else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V; } if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) mov->flags |= FF_MOV_FLAG_EMPTY_MOOV; /* Set the FRAGMENT flag if any of the fragmentation methods are * enabled. */ if (mov->max_fragment_duration || mov->max_fragment_size || mov->flags & (FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_FRAG_KEYFRAME | FF_MOV_FLAG_FRAG_CUSTOM | FF_MOV_FLAG_FRAG_EVERY_FRAME)) mov->flags |= FF_MOV_FLAG_FRAGMENT; /* Set other implicit flags immediately */ if (mov->mode == MODE_ISM) mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF | FF_MOV_FLAG_FRAGMENT; if (mov->flags & FF_MOV_FLAG_DASH) mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_DEFAULT_BASE_MOOF; if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) { av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n"); s->flags &= ~AVFMT_FLAG_AUTO_BSF; } if (mov->flags & FF_MOV_FLAG_FASTSTART) { mov->reserved_moov_size = -1; } if (mov->use_editlist < 0) { mov->use_editlist = 1; if (mov->flags & FF_MOV_FLAG_FRAGMENT && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { // If we can avoid needing an edit list by shifting the // tracks, prefer that over (trying to) write edit lists // in fragmented output. if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) mov->use_editlist = 0; } } if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist) av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n"); if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO) s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO; /* Clear the omit_tfhd_offset flag if default_base_moof is set; * if the latter is set that's enough and omit_tfhd_offset doesn't * add anything extra on top of that. */ if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET; if (mov->frag_interleave && mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) { av_log(s, AV_LOG_ERROR, "Sample interleaving in fragments is mutually exclusive with " "omit_tfhd_offset and separate_moof\n"); return AVERROR(EINVAL); } /* Non-seekable output is ok if using fragmentation. If ism_lookahead * is enabled, we don't support non-seekable output at all. */ if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) { av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n"); return AVERROR(EINVAL); } mov->nb_streams = s->nb_streams; if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) mov->chapter_track = mov->nb_streams++; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { for (i = 0; i < s->nb_streams; i++) if (rtp_hinting_needed(s->streams[i])) mov->nb_streams++; } if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4) || mov->write_tmcd == 1) { /* +1 tmcd track for each video stream with a timecode */ for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; AVDictionaryEntry *t = global_tcr; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) { AVTimecode tc; ret = mov_check_timecode_track(s, &tc, i, t->value); if (ret >= 0) mov->nb_meta_tmcd++; } } /* check if there is already a tmcd track to remux */ if (mov->nb_meta_tmcd) { for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) { av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track " "so timecode metadata are now ignored\n"); mov->nb_meta_tmcd = 0; } } } mov->nb_streams += mov->nb_meta_tmcd; } // Reserve an extra stream for chapters for the case where chapters // are written in the trailer mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks)); if (!mov->tracks) return AVERROR(ENOMEM); if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) { if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) { mov->encryption_scheme = MOV_ENC_CENC_AES_CTR; if (mov->encryption_key_len != AES_CTR_KEY_SIZE) { av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n", mov->encryption_key_len, AES_CTR_KEY_SIZE); return AVERROR(EINVAL); } if (mov->encryption_kid_len != CENC_KID_SIZE) { av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n", mov->encryption_kid_len, CENC_KID_SIZE); return AVERROR(EINVAL); } } else { av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n", mov->encryption_scheme_str); return AVERROR(EINVAL); } } for (i = 0; i < s->nb_streams; i++) { AVStream *st= s->streams[i]; MOVTrack *track= &mov->tracks[i]; AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0); track->st = st; track->par = st->codecpar; track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV); if (track->language < 0) track->language = 0; track->mode = mov->mode; track->tag = mov_find_codec_tag(s, track); if (!track->tag) { av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, " "codec not currently supported in container\n", avcodec_get_name(st->codecpar->codec_id), i); return AVERROR(EINVAL); } /* If hinting of this track is enabled by a later hint track, * this is updated. */ track->hint_track = -1; track->start_dts = AV_NOPTS_VALUE; track->start_cts = AV_NOPTS_VALUE; track->end_pts = AV_NOPTS_VALUE; track->dts_shift = AV_NOPTS_VALUE; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') || track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') || track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) { if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) { av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n"); return AVERROR(EINVAL); } track->height = track->tag >> 24 == 'n' ? 486 : 576; } if (mov->video_track_timescale) { track->timescale = mov->video_track_timescale; } else { track->timescale = st->time_base.den; while(track->timescale < 10000) track->timescale *= 2; } if (st->codecpar->width > 65535 || st->codecpar->height > 65535) { av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height); return AVERROR(EINVAL); } if (track->mode == MODE_MOV && track->timescale > 100000) av_log(s, AV_LOG_WARNING, "WARNING codec timebase is very high. If duration is too long,\n" "file may not be playable by quicktime. Specify a shorter timebase\n" "or choose different container.\n"); if (track->mode == MODE_MOV && track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->tag == MKTAG('r','a','w',' ')) { enum AVPixelFormat pix_fmt = track->par->format; if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1) pix_fmt = AV_PIX_FMT_MONOWHITE; track->is_unaligned_qt_rgb = pix_fmt == AV_PIX_FMT_RGB24 || pix_fmt == AV_PIX_FMT_BGR24 || pix_fmt == AV_PIX_FMT_PAL8 || pix_fmt == AV_PIX_FMT_GRAY8 || pix_fmt == AV_PIX_FMT_MONOWHITE || pix_fmt == AV_PIX_FMT_MONOBLACK; } if (track->par->codec_id == AV_CODEC_ID_VP9) { if (track->mode != MODE_MP4) { av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n"); return AVERROR(EINVAL); } } else if (track->par->codec_id == AV_CODEC_ID_AV1) { /* spec is not finished, so forbid for now */ av_log(s, AV_LOG_ERROR, "AV1 muxing is currently not supported.\n"); return AVERROR_PATCHWELCOME; } else if (track->par->codec_id == AV_CODEC_ID_VP8) { /* altref frames handling is not defined in the spec as of version v1.0, * so just forbid muxing VP8 streams altogether until a new version does */ av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n"); return AVERROR_PATCHWELCOME; } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { track->timescale = st->codecpar->sample_rate; if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) { av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i); track->audio_vbr = 1; }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS || st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || st->codecpar->codec_id == AV_CODEC_ID_ILBC){ if (!st->codecpar->block_align) { av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i); return AVERROR(EINVAL); } track->sample_size = st->codecpar->block_align; }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */ track->audio_vbr = 1; }else{ track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels; } if (st->codecpar->codec_id == AV_CODEC_ID_ILBC || st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) { track->audio_vbr = 1; } if (track->mode != MODE_MOV && track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) { if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) { av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n", i, track->par->sample_rate); return AVERROR(EINVAL); } else { av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n", i, track->par->sample_rate); } } if (track->par->codec_id == AV_CODEC_ID_FLAC || track->par->codec_id == AV_CODEC_ID_OPUS) { if (track->mode != MODE_MP4) { av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id)); return AVERROR(EINVAL); } if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { av_log(s, AV_LOG_ERROR, "%s in MP4 support is experimental, add " "'-strict %d' if you want to use it.\n", avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL); return AVERROR_EXPERIMENTAL; } } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) { track->timescale = st->time_base.den; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) { track->timescale = st->time_base.den; } else { track->timescale = MOV_TIMESCALE; } if (!track->height) track->height = st->codecpar->height; /* The ism specific timescale isn't mandatory, but is assumed by * some tools, such as mp4split. */ if (mov->mode == MODE_ISM) track->timescale = 10000000; avpriv_set_pts_info(st, 64, 1, track->timescale); if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) { ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key, track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT); if (ret) return ret; } } enable_tracks(s); return 0; } static int mov_write_header(AVFormatContext *s) { AVIOContext *pb = s->pb; MOVMuxContext *mov = s->priv_data; AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0); int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams; if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) nb_tracks++; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { hint_track = nb_tracks; for (i = 0; i < s->nb_streams; i++) if (rtp_hinting_needed(s->streams[i])) nb_tracks++; } if (mov->mode == MODE_MOV || mov->mode == MODE_MP4) tmcd_track = nb_tracks; for (i = 0; i < s->nb_streams; i++) { int j; AVStream *st= s->streams[i]; MOVTrack *track= &mov->tracks[i]; /* copy extradata if it exists */ if (st->codecpar->extradata_size) { if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) mov_create_dvd_sub_decoder_specific_info(track, st); else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) { track->vos_len = st->codecpar->extradata_size; track->vos_data = av_malloc(track->vos_len); if (!track->vos_data) { return AVERROR(ENOMEM); } memcpy(track->vos_data, st->codecpar->extradata, track->vos_len); } } if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || track->par->channel_layout != AV_CH_LAYOUT_MONO) continue; for (j = 0; j < s->nb_streams; j++) { AVStream *stj= s->streams[j]; MOVTrack *trackj= &mov->tracks[j]; if (j == i) continue; if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || trackj->par->channel_layout != AV_CH_LAYOUT_MONO || trackj->language != track->language || trackj->tag != track->tag ) continue; track->multichannel_as_mono++; } } if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { if ((ret = mov_write_identification(pb, s)) < 0) return ret; } if (mov->reserved_moov_size){ mov->reserved_header_pos = avio_tell(pb); if (mov->reserved_moov_size > 0) avio_skip(pb, mov->reserved_moov_size); } if (mov->flags & FF_MOV_FLAG_FRAGMENT) { /* If no fragmentation options have been set, set a default. */ if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME | FF_MOV_FLAG_FRAG_CUSTOM | FF_MOV_FLAG_FRAG_EVERY_FRAME)) && !mov->max_fragment_duration && !mov->max_fragment_size) mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME; } else { if (mov->flags & FF_MOV_FLAG_FASTSTART) mov->reserved_header_pos = avio_tell(pb); mov_write_mdat_tag(pb, mov); } ff_parse_creation_time_metadata(s, &mov->time, 1); if (mov->time) mov->time += 0x7C25B080; // 1970 based -> 1904 based if (mov->chapter_track) if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0) return ret; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { for (i = 0; i < s->nb_streams; i++) { if (rtp_hinting_needed(s->streams[i])) { if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0) return ret; hint_track++; } } } if (mov->nb_meta_tmcd) { /* Initialize the tmcd tracks */ for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; t = global_tcr; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { AVTimecode tc; if (!t) t = av_dict_get(st->metadata, "timecode", NULL, 0); if (!t) continue; if (mov_check_timecode_track(s, &tc, i, t->value) < 0) continue; if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0) return ret; tmcd_track++; } } } avio_flush(pb); if (mov->flags & FF_MOV_FLAG_ISML) mov_write_isml_manifest(pb, mov, s); if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { if ((ret = mov_write_moov_tag(pb, mov, s)) < 0) return ret; avio_flush(pb); mov->moov_written = 1; if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(pb); } return 0; } static int get_moov_size(AVFormatContext *s) { int ret; AVIOContext *moov_buf; MOVMuxContext *mov = s->priv_data; if ((ret = ffio_open_null_buf(&moov_buf)) < 0) return ret; if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0) return ret; return ffio_close_null_buf(moov_buf); } static int get_sidx_size(AVFormatContext *s) { int ret; AVIOContext *buf; MOVMuxContext *mov = s->priv_data; if ((ret = ffio_open_null_buf(&buf)) < 0) return ret; mov_write_sidx_tags(buf, mov, -1, 0); return ffio_close_null_buf(buf); } /* * This function gets the moov size if moved to the top of the file: the chunk * offset table can switch between stco (32-bit entries) to co64 (64-bit * entries) when the moov is moved to the beginning, so the size of the moov * would change. It also updates the chunk offset tables. */ static int compute_moov_size(AVFormatContext *s) { int i, moov_size, moov_size2; MOVMuxContext *mov = s->priv_data; moov_size = get_moov_size(s); if (moov_size < 0) return moov_size; for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += moov_size; moov_size2 = get_moov_size(s); if (moov_size2 < 0) return moov_size2; /* if the size changed, we just switched from stco to co64 and need to * update the offsets */ if (moov_size2 != moov_size) for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += moov_size2 - moov_size; return moov_size2; } static int compute_sidx_size(AVFormatContext *s) { int i, sidx_size; MOVMuxContext *mov = s->priv_data; sidx_size = get_sidx_size(s); if (sidx_size < 0) return sidx_size; for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += sidx_size; return sidx_size; } static int shift_data(AVFormatContext *s) { int ret = 0, moov_size; MOVMuxContext *mov = s->priv_data; int64_t pos, pos_end = avio_tell(s->pb); uint8_t *buf, *read_buf[2]; int read_buf_id = 0; int read_size[2]; AVIOContext *read_pb; if (mov->flags & FF_MOV_FLAG_FRAGMENT) moov_size = compute_sidx_size(s); else moov_size = compute_moov_size(s); if (moov_size < 0) return moov_size; buf = av_malloc(moov_size * 2); if (!buf) return AVERROR(ENOMEM); read_buf[0] = buf; read_buf[1] = buf + moov_size; /* Shift the data: the AVIO context of the output can only be used for * writing, so we re-open the same output, but for reading. It also avoids * a read/seek/write/seek back and forth. */ avio_flush(s->pb); ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL); if (ret < 0) { av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for " "the second pass (faststart)\n", s->url); goto end; } /* mark the end of the shift to up to the last data we wrote, and get ready * for writing */ pos_end = avio_tell(s->pb); avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET); /* start reading at where the new moov will be placed */ avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET); pos = avio_tell(read_pb); #define READ_BLOCK do { \ read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \ read_buf_id ^= 1; \ } while (0) /* shift data by chunk of at most moov_size */ READ_BLOCK; do { int n; READ_BLOCK; n = read_size[read_buf_id]; if (n <= 0) break; avio_write(s->pb, read_buf[read_buf_id], n); pos += n; } while (pos < pos_end); ff_format_io_close(s, &read_pb); end: av_free(buf); return ret; } static int mov_write_trailer(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; AVIOContext *pb = s->pb; int res = 0; int i; int64_t moov_pos; if (mov->need_rewrite_extradata) { for (i = 0; i < s->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; AVCodecParameters *par = track->par; track->vos_len = par->extradata_size; track->vos_data = av_malloc(track->vos_len); if (!track->vos_data) return AVERROR(ENOMEM); memcpy(track->vos_data, par->extradata, track->vos_len); } mov->need_rewrite_extradata = 0; } /* * Before actually writing the trailer, make sure that there are no * dangling subtitles, that need a terminating sample. */ for (i = 0; i < mov->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT && !trk->last_sample_is_subtitle_end) { mov_write_subtitle_end_packet(s, i, trk->track_duration); trk->last_sample_is_subtitle_end = 1; } } // If there were no chapters when the header was written, but there // are chapters now, write them in the trailer. This only works // when we are not doing fragments. if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) { if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) { mov->chapter_track = mov->nb_streams++; if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0) return res; } } if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) { moov_pos = avio_tell(pb); /* Write size of mdat tag */ if (mov->mdat_size + 8 <= UINT32_MAX) { avio_seek(pb, mov->mdat_pos, SEEK_SET); avio_wb32(pb, mov->mdat_size + 8); } else { /* overwrite 'wide' placeholder atom */ avio_seek(pb, mov->mdat_pos - 8, SEEK_SET); /* special value: real atom size will be 64 bit value after * tag field */ avio_wb32(pb, 1); ffio_wfourcc(pb, "mdat"); avio_wb64(pb, mov->mdat_size + 16); } avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET); if (mov->flags & FF_MOV_FLAG_FASTSTART) { av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n"); res = shift_data(s); if (res < 0) return res; avio_seek(pb, mov->reserved_header_pos, SEEK_SET); if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; } else if (mov->reserved_moov_size > 0) { int64_t size; if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos); if (size < 8){ av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size); return AVERROR(EINVAL); } avio_wb32(pb, size); ffio_wfourcc(pb, "free"); ffio_fill(pb, 0, size - 8); avio_seek(pb, moov_pos, SEEK_SET); } else { if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; } res = 0; } else { mov_auto_flush_fragment(s, 1); for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset = 0; if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) { int64_t end; av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n"); res = shift_data(s); if (res < 0) return res; end = avio_tell(pb); avio_seek(pb, mov->reserved_header_pos, SEEK_SET); mov_write_sidx_tags(pb, mov, -1, 0); avio_seek(pb, end, SEEK_SET); avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER); mov_write_mfra_tag(pb, mov); } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) { avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER); mov_write_mfra_tag(pb, mov); } } return res; } static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt) { int ret = 1; AVStream *st = s->streams[pkt->stream_index]; if (st->codecpar->codec_id == AV_CODEC_ID_AAC) { if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL); } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) { ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL); } return ret; } static const AVCodecTag codec_3gp_tags[] = { { AV_CODEC_ID_H263, MKTAG('s','2','6','3') }, { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') }, { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') }, { AV_CODEC_ID_NONE, 0 }, }; const AVCodecTag codec_mp4_tags[] = { { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') }, { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') }, { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') }, { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') }, { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') }, { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') }, { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') }, { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') }, { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') }, { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') }, { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') }, { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') }, { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') }, { AV_CODEC_ID_NONE , 0 }, }; const AVCodecTag codec_ism_tags[] = { { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') }, { AV_CODEC_ID_NONE , 0 }, }; static const AVCodecTag codec_ipod_tags[] = { { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') }, { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') }, { AV_CODEC_ID_NONE, 0 }, }; static const AVCodecTag codec_f4v_tags[] = { { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') }, { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') }, { AV_CODEC_ID_NONE, 0 }, }; #if CONFIG_MOV_MUXER MOV_CLASS(mov) AVOutputFormat ff_mov_muxer = { .name = "mov", .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"), .extensions = "mov", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &mov_muxer_class, }; #endif #if CONFIG_TGP_MUXER MOV_CLASS(tgp) AVOutputFormat ff_tgp_muxer = { .name = "3gp", .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"), .extensions = "3gp", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AMR_NB, .video_codec = AV_CODEC_ID_H263, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &tgp_muxer_class, }; #endif #if CONFIG_MP4_MUXER MOV_CLASS(mp4) AVOutputFormat ff_mp4_muxer = { .name = "mp4", .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"), .mime_type = "video/mp4", .extensions = "mp4", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &mp4_muxer_class, }; #endif #if CONFIG_PSP_MUXER MOV_CLASS(psp) AVOutputFormat ff_psp_muxer = { .name = "psp", .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"), .extensions = "mp4,psp", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &psp_muxer_class, }; #endif #if CONFIG_TG2_MUXER MOV_CLASS(tg2) AVOutputFormat ff_tg2_muxer = { .name = "3g2", .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"), .extensions = "3g2", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AMR_NB, .video_codec = AV_CODEC_ID_H263, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &tg2_muxer_class, }; #endif #if CONFIG_IPOD_MUXER MOV_CLASS(ipod) AVOutputFormat ff_ipod_muxer = { .name = "ipod", .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"), .mime_type = "video/mp4", .extensions = "m4v,m4a,m4b", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &ipod_muxer_class, }; #endif #if CONFIG_ISMV_MUXER MOV_CLASS(ismv) AVOutputFormat ff_ismv_muxer = { .name = "ismv", .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"), .mime_type = "video/mp4", .extensions = "ismv,isma", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, codec_ism_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &ismv_muxer_class, }; #endif #if CONFIG_F4V_MUXER MOV_CLASS(f4v) AVOutputFormat ff_f4v_muxer = { .name = "f4v", .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"), .mime_type = "application/f4v", .extensions = "f4v", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH, .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &f4v_muxer_class, }; #endif
./CrossVul/dataset_final_sorted/CWE-129/c/bad_217_0
crossvul-cpp_data_good_4384_3
/** * Copyright (c) 2014-present, The osquery authors * * This source code is licensed as defined by the LICENSE file found in the * root directory of this source tree. * * SPDX-License-Identifier: (Apache-2.0 OR GPL-2.0-only) */ #include <boost/algorithm/string.hpp> #include <osquery/core/core.h> #include <osquery/filesystem/filesystem.h> #include <osquery/logger/logger.h> #include <osquery/sql/sql.h> #include <osquery/utils/info/platform_type.h> #include "osquery/sql/dynamic_table_row.h" #include "osquery/sql/sqlite_util.h" namespace fs = boost::filesystem; namespace osquery { const char* getSystemVFS(bool respect_locking) { if (respect_locking) { return nullptr; } if (isPlatform(PlatformType::TYPE_POSIX)) { return "unix-none"; } else if (isPlatform(PlatformType::TYPE_WINDOWS)) { return "win32-none"; } return nullptr; } Status genSqliteTableRow(sqlite3_stmt* stmt, TableRows& qd, const fs::path& sqlite_db) { auto r = make_table_row(); for (int i = 0; i < sqlite3_column_count(stmt); ++i) { auto column_name = std::string(sqlite3_column_name(stmt, i)); auto column_type = sqlite3_column_type(stmt, i); switch (column_type) { case SQLITE_BLOB: case SQLITE_TEXT: { auto text_value = sqlite3_column_text(stmt, i); if (text_value != nullptr) { r[column_name] = std::string(reinterpret_cast<const char*>(text_value)); } break; } case SQLITE_FLOAT: { auto float_value = sqlite3_column_double(stmt, i); r[column_name] = DOUBLE(float_value); break; } case SQLITE_INTEGER: { auto int_value = sqlite3_column_int64(stmt, i); r[column_name] = INTEGER(int_value); break; } } } if (r.count("path") > 0) { LOG(WARNING) << "ATC Table: Row contains a defined path key, omitting the " "implicit one"; } else { r["path"] = sqlite_db.string(); } qd.push_back(std::move(r)); return Status::success(); } Status genTableRowsForSqliteTable(const fs::path& sqlite_db, const std::string& sqlite_query, TableRows& results, bool respect_locking) { sqlite3* db = nullptr; if (!pathExists(sqlite_db).ok()) { return Status(1, "Database path does not exist"); } auto rc = sqlite3_open_v2( sqlite_db.string().c_str(), &db, (SQLITE_OPEN_READONLY | SQLITE_OPEN_PRIVATECACHE | SQLITE_OPEN_NOMUTEX), getSystemVFS(respect_locking)); if (rc != SQLITE_OK || db == nullptr) { VLOG(1) << "Cannot open specified database: " << getStringForSQLiteReturnCode(rc); if (db != nullptr) { sqlite3_close(db); } return Status(1, "Could not open database"); } rc = sqlite3_set_authorizer(db, &sqliteAuthorizer, nullptr); if (rc != SQLITE_OK) { sqlite3_close(db); auto errMsg = std::string("Failed to set sqlite authorizer: ") + sqlite3_errmsg(db); return Status(1, errMsg); } sqlite3_stmt* stmt = nullptr; rc = sqlite3_prepare_v2(db, sqlite_query.c_str(), -1, &stmt, nullptr); if (rc != SQLITE_OK) { sqlite3_close(db); VLOG(1) << "ATC table: Could not prepare database at path: " << sqlite_db; return Status(rc, "Could not prepare database"); } while ((sqlite3_step(stmt)) == SQLITE_ROW) { auto s = genSqliteTableRow(stmt, results, sqlite_db); if (!s.ok()) { break; } } // Close handles and free memory sqlite3_finalize(stmt); sqlite3_close(db); return Status{}; } Status getSqliteJournalMode(const fs::path& sqlite_db) { TableRows result; auto status = genTableRowsForSqliteTable( sqlite_db, "PRAGMA journal_mode;", result, true); if (!status.ok()) { return status; } if (result.empty()) { VLOG(1) << "PRAGMA query returned empty results"; return Status(1, "Could not retrieve journal mode"); } auto resultmap = static_cast<Row>(*result[0]); if (resultmap.find("journal_mode") == resultmap.end()) { VLOG(1) << "journal_mode not found PRAGMA query results"; return Status(1, "Could not retrieve journal mode"); } return Status(Status::kSuccessCode, boost::algorithm::to_lower_copy(resultmap["journal_mode"])); } } // namespace osquery
./CrossVul/dataset_final_sorted/CWE-77/cpp/good_4384_3
crossvul-cpp_data_good_4384_0
/** * Copyright (c) 2014-present, The osquery authors * * This source code is licensed as defined by the LICENSE file found in the * root directory of this source tree. * * SPDX-License-Identifier: (Apache-2.0 OR GPL-2.0-only) */ #include "osquery/sql/sqlite_util.h" #include "osquery/sql/virtual_table.h" #include <osquery/core/plugins/sql.h> #include <osquery/utils/conversions/castvariant.h> #include <osquery/core/core.h> #include <osquery/core/flags.h> #include <osquery/core/shutdown.h> #include <osquery/logger/logger.h> #include <osquery/registry/registry_factory.h> #include <osquery/sql/sql.h> #include <osquery/utils/conversions/split.h> #include <boost/lexical_cast.hpp> namespace osquery { FLAG(string, disable_tables, "", "Comma-delimited list of table names to be disabled"); FLAG(string, enable_tables, "", "Comma-delimited list of table names to be enabled"); FLAG(string, nullvalue, "", "Set string for NULL values, default ''"); using OpReg = QueryPlanner::Opcode::Register; using SQLiteDBInstanceRef = std::shared_ptr<SQLiteDBInstance>; /** * @brief A map of SQLite status codes to their corresponding message string * * Details of this map are defined at: http://www.sqlite.org/c3ref/c_abort.html */ // clang-format off const std::map<int, std::string> kSQLiteReturnCodes = { {0, "SQLITE_OK"}, {1, "SQLITE_ERROR"}, {2, "SQLITE_INTERNAL"}, {3, "SQLITE_PERM"}, {4, "SQLITE_ABORT"}, {5, "SQLITE_BUSY"}, {6, "SQLITE_LOCKED"}, {7, "SQLITE_NOMEM"}, {8, "SQLITE_READONLY"}, {9, "SQLITE_INTERRUPT"}, {10, "SQLITE_IOERR"}, {11, "SQLITE_CORRUPT"}, {12, "SQLITE_NOTFOUND"}, {13, "SQLITE_FULL"}, {14, "SQLITE_CANTOPEN"}, {15, "SQLITE_PROTOCOL"}, {16, "SQLITE_EMPTY"}, {17, "SQLITE_SCHEMA"}, {18, "SQLITE_TOOBIG"}, {19, "SQLITE_CONSTRAINT"}, {20, "SQLITE_MISMATCH"}, {21, "SQLITE_MISUSE"}, {22, "SQLITE_NOLFS"}, {23, "SQLITE_AUTH"}, {24, "SQLITE_FORMAT"}, {25, "SQLITE_RANGE"}, {26, "SQLITE_NOTADB"}, {27, "SQLITE_NOTICE"}, {28, "SQLITE_WARNING"}, {100, "SQLITE_ROW"}, {101, "SQLITE_DONE"}, }; const std::map<std::string, std::string> kMemoryDBSettings = { {"synchronous", "OFF"}, {"count_changes", "OFF"}, {"default_temp_store", "0"}, {"auto_vacuum", "FULL"}, {"journal_mode", "OFF"}, {"cache_size", "0"}, {"page_count", "0"}, }; // clang-format on #define OpComparator(x) \ { x, QueryPlanner::Opcode(OpReg::P2, INTEGER_TYPE) } #define Arithmetic(x) \ { x, QueryPlanner::Opcode(OpReg::P3, BIGINT_TYPE) } /** * @brief A map from opcode to pair of result register and resultant type. * * For most opcodes we can deduce a column type based on an interred input * to the opcode "function". These come in a few sets, arithmetic operators, * comparators, aggregates, and copies. */ const std::map<std::string, QueryPlanner::Opcode> kSQLOpcodes = { {"Concat", QueryPlanner::Opcode(OpReg::P3, TEXT_TYPE)}, {"AggStep", QueryPlanner::Opcode(OpReg::P3, BIGINT_TYPE)}, {"AggStep0", QueryPlanner::Opcode(OpReg::P3, BIGINT_TYPE)}, {"Integer", QueryPlanner::Opcode(OpReg::P2, INTEGER_TYPE)}, {"Int64", QueryPlanner::Opcode(OpReg::P2, BIGINT_TYPE)}, {"String", QueryPlanner::Opcode(OpReg::P2, TEXT_TYPE)}, {"String8", QueryPlanner::Opcode(OpReg::P2, TEXT_TYPE)}, {"Or", QueryPlanner::Opcode(OpReg::P3, INTEGER_TYPE)}, {"And", QueryPlanner::Opcode(OpReg::P3, INTEGER_TYPE)}, // Arithmetic yields a BIGINT for safety. Arithmetic("BitAnd"), Arithmetic("BitOr"), Arithmetic("ShiftLeft"), Arithmetic("ShiftRight"), Arithmetic("Add"), Arithmetic("Subtract"), Arithmetic("Multiply"), Arithmetic("Divide"), Arithmetic("Remainder"), // Comparators result in booleans and are treated as INTEGERs. OpComparator("Not"), OpComparator("IsNull"), OpComparator("NotNull"), OpComparator("Ne"), OpComparator("Eq"), OpComparator("Gt"), OpComparator("Le"), OpComparator("Lt"), OpComparator("Ge"), OpComparator("IfNeg"), OpComparator("IfNotZero"), }; RecursiveMutex SQLiteDBInstance::kPrimaryAttachMutex; /// The SQLiteSQLPlugin implements the "sql" registry for internal/core. class SQLiteSQLPlugin : public SQLPlugin { public: /// Execute SQL and store results. Status query(const std::string& query, QueryData& results, bool use_cache) const override; /// Introspect, explain, the suspected types selected in an SQL statement. Status getQueryColumns(const std::string& query, TableColumns& columns) const override; /// Similar to getQueryColumns but return the scanned tables. Status getQueryTables(const std::string& query, std::vector<std::string>& tables) const override; /// Create a SQLite module and attach (CREATE). Status attach(const std::string& name) override; /// Detach a virtual table (DROP). Status detach(const std::string& name) override; }; /// SQL provider for osquery internal/core. REGISTER_INTERNAL(SQLiteSQLPlugin, "sql", "sql"); std::string getStringForSQLiteReturnCode(int code) { if (kSQLiteReturnCodes.find(code) != kSQLiteReturnCodes.end()) { return kSQLiteReturnCodes.at(code); } else { std::ostringstream s; s << "Error: " << code << " is not a valid SQLite result code"; return s.str(); } } Status SQLiteSQLPlugin::query(const std::string& query, QueryData& results, bool use_cache) const { auto dbc = SQLiteDBManager::get(); dbc->useCache(use_cache); auto result = queryInternal(query, results, dbc); dbc->clearAffectedTables(); return result; } Status SQLiteSQLPlugin::getQueryColumns(const std::string& query, TableColumns& columns) const { auto dbc = SQLiteDBManager::get(); return getQueryColumnsInternal(query, columns, dbc); } Status SQLiteSQLPlugin::getQueryTables(const std::string& query, std::vector<std::string>& tables) const { auto dbc = SQLiteDBManager::get(); QueryPlanner planner(query, dbc); tables = planner.tables(); return Status(0); } SQLInternal::SQLInternal(const std::string& query, bool use_cache) { auto dbc = SQLiteDBManager::get(); dbc->useCache(use_cache); status_ = queryInternal(query, resultsTyped_, dbc); // One of the advantages of using SQLInternal (aside from the Registry-bypass) // is the ability to "deep-inspect" the table attributes and actions. event_based_ = (dbc->getAttributes() & TableAttributes::EVENT_BASED) != 0; dbc->clearAffectedTables(); } QueryDataTyped& SQLInternal::rowsTyped() { return resultsTyped_; } const Status& SQLInternal::getStatus() const { return status_; } bool SQLInternal::eventBased() const { return event_based_; } // Temporary: I'm going to move this from sql.cpp to here in change immediately // following since this is the only place we actually use it (breaking up to // make CRs smaller) extern void escapeNonPrintableBytesEx(std::string& str); class StringEscaperVisitor : public boost::static_visitor<> { public: void operator()(long long& i) const { // NO-OP } void operator()(double& d) const { // NO-OP } void operator()(std::string& str) const { escapeNonPrintableBytesEx(str); } }; void SQLInternal::escapeResults() { StringEscaperVisitor visitor; for (auto& rowTyped : resultsTyped_) { for (auto& column : rowTyped) { boost::apply_visitor(visitor, column.second); } } } Status SQLiteSQLPlugin::attach(const std::string& name) { PluginResponse response; auto status = Registry::call("table", name, {{"action", "columns"}}, response); if (!status.ok()) { return status; } bool is_extension = true; auto statement = columnDefinition(response, false, is_extension); // Attach requests occurring via the plugin/registry APIs must act on the // primary database. To allow this, getConnection can explicitly request the // primary instance and avoid the contention decisions. auto dbc = SQLiteDBManager::getConnection(true); // Attach as an extension, allowing read/write tables return attachTableInternal(name, statement, dbc, is_extension); } Status SQLiteSQLPlugin::detach(const std::string& name) { // Detach requests occurring via the plugin/registry APIs must act on the // primary database. To allow this, getConnection can explicitly request the // primary instance and avoid the contention decisions. auto dbc = SQLiteDBManager::getConnection(true); return detachTableInternal(name, dbc); } SQLiteDBInstance::SQLiteDBInstance(sqlite3*& db, Mutex& mtx) : db_(db), lock_(mtx, boost::try_to_lock) { if (lock_.owns_lock()) { primary_ = true; } else { db_ = nullptr; VLOG(1) << "DBManager contention: opening transient SQLite database"; init(); } } // This function is called by SQLite when a statement is prepared and we use // it to allowlist specific actions. int sqliteAuthorizer(void* userData, int code, const char* arg3, const char* arg4, const char* arg5, const char* arg6) { if (kAllowedSQLiteActionCodes.count(code) > 0) { return SQLITE_OK; } LOG(ERROR) << "Authorizer denied action " << code << " " << (arg3 ? arg3 : "null") << " " << (arg4 ? arg4 : "null") << " " << (arg5 ? arg5 : "null") << " " << (arg6 ? arg6 : "null"); return SQLITE_DENY; } static inline void openOptimized(sqlite3*& db) { sqlite3_open(":memory:", &db); std::string settings; for (const auto& setting : kMemoryDBSettings) { settings += "PRAGMA " + setting.first + "=" + setting.second + "; "; } sqlite3_exec(db, settings.c_str(), nullptr, nullptr, nullptr); // Register function extensions. registerMathExtensions(db); #if !defined(FREEBSD) registerStringExtensions(db); #endif #if !defined(SKIP_CARVER) registerOperationExtensions(db); #endif registerFilesystemExtensions(db); registerHashingExtensions(db); registerEncodingExtensions(db); auto rc = sqlite3_set_authorizer(db, &sqliteAuthorizer, nullptr); if (rc != SQLITE_OK) { LOG(ERROR) << "Failed to set sqlite authorizer: " << sqlite3_errmsg(db); requestShutdown(rc); } } void SQLiteDBInstance::init() { primary_ = false; openOptimized(db_); } void SQLiteDBInstance::useCache(bool use_cache) { use_cache_ = use_cache; } bool SQLiteDBInstance::useCache() const { return use_cache_; } RecursiveLock SQLiteDBInstance::attachLock() const { if (isPrimary()) { return RecursiveLock(kPrimaryAttachMutex); } return RecursiveLock(attach_mutex_); } void SQLiteDBInstance::addAffectedTable( std::shared_ptr<VirtualTableContent> table) { // An xFilter/scan was requested for this virtual table. affected_tables_.insert(std::make_pair(table->name, std::move(table))); } bool SQLiteDBInstance::tableCalled(VirtualTableContent const& table) { return (affected_tables_.count(table.name) > 0); } TableAttributes SQLiteDBInstance::getAttributes() const { const SQLiteDBInstance* rdbc = this; if (isPrimary() && !managed_) { // Similarly to clearAffectedTables, the connection may be forwarded. rdbc = SQLiteDBManager::getConnection(true).get(); } TableAttributes attributes = TableAttributes::NONE; for (const auto& table : rdbc->affected_tables_) { attributes = table.second->attributes | attributes; } return attributes; } void SQLiteDBInstance::clearAffectedTables() { if (isPrimary() && !managed_) { // A primary instance must forward clear requests to the DB manager's // 'connection' instance. This is a temporary primary instance. SQLiteDBManager::getConnection(true)->clearAffectedTables(); return; } for (const auto& table : affected_tables_) { table.second->constraints.clear(); table.second->cache.clear(); table.second->colsUsed.clear(); table.second->colsUsedBitsets.clear(); } // Since the affected tables are cleared, there are no more affected tables. // There is no concept of compounding tables between queries. affected_tables_.clear(); use_cache_ = false; } SQLiteDBInstance::~SQLiteDBInstance() { if (!isPrimary() && db_ != nullptr) { sqlite3_close(db_); } else { db_ = nullptr; } } SQLiteDBManager::SQLiteDBManager() : db_(nullptr) { sqlite3_soft_heap_limit64(1); setDisabledTables(Flag::getValue("disable_tables")); setEnabledTables(Flag::getValue("enable_tables")); } bool SQLiteDBManager::isDisabled(const std::string& table_name) { bool disabled_set = !Flag::isDefault("disable_tables"); bool enabled_set = !Flag::isDefault("enable_tables"); if (!disabled_set && !enabled_set) { // We have zero enabled tables and zero disabled tables. // As a result, no tables are disabled. return false; } const auto& element_disabled = instance().disabled_tables_.find(table_name); const auto& element_enabled = instance().enabled_tables_.find(table_name); bool table_disabled = (element_disabled != instance().disabled_tables_.end()); bool table_enabled = (element_enabled != instance().enabled_tables_.end()); if (table_disabled) { return true; } if (table_enabled && disabled_set && !table_disabled) { return false; } if (table_enabled && !disabled_set) { return false; } if (enabled_set && !table_enabled) { return true; } if (disabled_set && !table_disabled) { return false; } return true; } void SQLiteDBManager::resetPrimary() { auto& self = instance(); WriteLock connection_lock(self.mutex_); self.connection_.reset(); { WriteLock create_lock(self.create_mutex_); sqlite3_close(self.db_); self.db_ = nullptr; } } void SQLiteDBManager::setDisabledTables(const std::string& list) { const auto& tables = split(list, ","); disabled_tables_ = std::unordered_set<std::string>(tables.begin(), tables.end()); } void SQLiteDBManager::setEnabledTables(const std::string& list) { const auto& tables = split(list, ","); enabled_tables_ = std::unordered_set<std::string>(tables.begin(), tables.end()); } SQLiteDBInstanceRef SQLiteDBManager::getUnique() { auto instance = std::make_shared<SQLiteDBInstance>(); attachVirtualTables(instance); return instance; } SQLiteDBInstanceRef SQLiteDBManager::getConnection(bool primary) { auto& self = instance(); WriteLock lock(self.create_mutex_); if (self.db_ == nullptr) { // Create primary SQLite DB instance. openOptimized(self.db_); self.connection_ = SQLiteDBInstanceRef(new SQLiteDBInstance(self.db_)); attachVirtualTables(self.connection_); } // Internal usage may request the primary connection explicitly. if (primary) { return self.connection_; } // Create a 'database connection' for the managed database instance. auto instance = std::make_shared<SQLiteDBInstance>(self.db_, self.mutex_); if (!instance->isPrimary()) { attachVirtualTables(instance); } return instance; } SQLiteDBManager::~SQLiteDBManager() { connection_ = nullptr; if (db_ != nullptr) { sqlite3_close(db_); db_ = nullptr; } } QueryPlanner::QueryPlanner(const std::string& query, const SQLiteDBInstanceRef& instance) { QueryData plan; queryInternal("EXPLAIN QUERY PLAN " + query, plan, instance); queryInternal("EXPLAIN " + query, program_, instance); for (const auto& row : plan) { auto details = osquery::split(row.at("detail")); if (details.size() > 2 && details[0] == "SCAN") { tables_.push_back(details[2]); } } } Status QueryPlanner::applyTypes(TableColumns& columns) { std::map<size_t, ColumnType> column_types; for (const auto& row : program_) { if (row.at("opcode") == "ResultRow") { // The column parsing is finished. auto k = boost::lexical_cast<size_t>(row.at("p1")); for (const auto& type : column_types) { if (type.first - k < columns.size()) { std::get<1>(columns[type.first - k]) = type.second; } } } if (row.at("opcode") == "Copy") { // Copy P1 -> P1 + P3 into P2 -> P2 + P3. auto from = boost::lexical_cast<size_t>(row.at("p1")); auto to = boost::lexical_cast<size_t>(row.at("p2")); auto size = boost::lexical_cast<size_t>(row.at("p3")); for (size_t i = 0; i <= size; i++) { if (column_types.count(from + i)) { column_types[to + i] = std::move(column_types[from + i]); column_types.erase(from + i); } } } else if (row.at("opcode") == "Cast") { auto value = boost::lexical_cast<size_t>(row.at("p1")); auto to = boost::lexical_cast<size_t>(row.at("p2")); switch (to) { case 'A': // BLOB column_types[value] = BLOB_TYPE; break; case 'B': // TEXT column_types[value] = TEXT_TYPE; break; case 'C': // NUMERIC // We don't exactly have an equivalent to NUMERIC (which includes such // things as DATETIME and DECIMAL column_types[value] = UNKNOWN_TYPE; break; case 'D': // INTEGER column_types[value] = BIGINT_TYPE; break; case 'E': // REAL column_types[value] = DOUBLE_TYPE; break; default: column_types[value] = UNKNOWN_TYPE; break; } } if (kSQLOpcodes.count(row.at("opcode"))) { const auto& op = kSQLOpcodes.at(row.at("opcode")); auto k = boost::lexical_cast<size_t>(row.at(Opcode::regString(op.reg))); column_types[k] = op.type; } } return Status(0); } // Wrapper for legacy method until all uses can be replaced Status queryInternal(const std::string& query, QueryData& results, const SQLiteDBInstanceRef& instance) { QueryDataTyped typedResults; Status status = queryInternal(query, typedResults, instance); if (status.ok()) { results.reserve(typedResults.size()); for (const auto& row : typedResults) { Row r; for (const auto& col : row) { r[col.first] = castVariant(col.second); } results.push_back(std::move(r)); } } return status; } Status readRows(sqlite3_stmt* prepared_statement, QueryDataTyped& results, const SQLiteDBInstanceRef& instance) { // Do nothing with a null prepared_statement (eg, if the sql was just // whitespace) if (prepared_statement == nullptr) { return Status::success(); } int rc = sqlite3_step(prepared_statement); /* if we have a result set row... */ if (SQLITE_ROW == rc) { // First collect the column names int num_columns = sqlite3_column_count(prepared_statement); std::vector<std::string> colNames; colNames.reserve(num_columns); for (int i = 0; i < num_columns; i++) { colNames.push_back(sqlite3_column_name(prepared_statement, i)); } do { RowTyped row; for (int i = 0; i < num_columns; i++) { switch (sqlite3_column_type(prepared_statement, i)) { case SQLITE_INTEGER: row[colNames[i]] = static_cast<long long>( sqlite3_column_int64(prepared_statement, i)); break; case SQLITE_FLOAT: row[colNames[i]] = sqlite3_column_double(prepared_statement, i); break; case SQLITE_NULL: row[colNames[i]] = FLAGS_nullvalue; break; default: // Everything else (SQLITE_TEXT, SQLITE3_TEXT, SQLITE_BLOB) is // obtained/conveyed as text/string row[colNames[i]] = std::string(reinterpret_cast<const char*>( sqlite3_column_text(prepared_statement, i))); } } results.push_back(std::move(row)); rc = sqlite3_step(prepared_statement); } while (SQLITE_ROW == rc); } if (rc != SQLITE_DONE) { auto s = Status::failure(sqlite3_errmsg(instance->db())); sqlite3_finalize(prepared_statement); return s; } rc = sqlite3_finalize(prepared_statement); if (rc != SQLITE_OK) { return Status::failure(sqlite3_errmsg(instance->db())); } return Status::success(); } Status queryInternal(const std::string& query, QueryDataTyped& results, const SQLiteDBInstanceRef& instance) { sqlite3_stmt* prepared_statement{nullptr}; /* Statement to execute. */ int rc = SQLITE_OK; /* Return Code */ const char* leftover_sql = nullptr; /* Tail of unprocessed SQL */ const char* sql = query.c_str(); /* SQL to be processed */ /* The big while loop. One iteration per statement */ while ((sql[0] != '\0') && (SQLITE_OK == rc)) { const auto lock = instance->attachLock(); // Trim leading whitespace while (isspace(sql[0])) { sql++; } rc = sqlite3_prepare_v2( instance->db(), sql, -1, &prepared_statement, &leftover_sql); if (rc != SQLITE_OK) { Status s = Status::failure(sqlite3_errmsg(instance->db())); sqlite3_finalize(prepared_statement); return s; } Status s = readRows(prepared_statement, results, instance); if (!s.ok()) { return s; } sql = leftover_sql; } /* end while */ sqlite3_db_release_memory(instance->db()); return Status::success(); } Status getQueryColumnsInternal(const std::string& q, TableColumns& columns, const SQLiteDBInstanceRef& instance) { Status status = Status(); TableColumns results; { auto lock = instance->attachLock(); // Turn the query into a prepared statement sqlite3_stmt* stmt{nullptr}; auto rc = sqlite3_prepare_v2(instance->db(), q.c_str(), static_cast<int>(q.length() + 1), &stmt, nullptr); if (rc != SQLITE_OK || stmt == nullptr) { auto s = Status::failure(sqlite3_errmsg(instance->db())); if (stmt != nullptr) { sqlite3_finalize(stmt); } return s; } // Get column count auto num_columns = sqlite3_column_count(stmt); results.reserve(num_columns); // Get column names and types bool unknown_type = false; for (int i = 0; i < num_columns; ++i) { auto col_name = sqlite3_column_name(stmt, i); auto col_type = sqlite3_column_decltype(stmt, i); if (col_name == nullptr) { status = Status(1, "Could not get column type"); break; } if (col_type == nullptr) { // Types are only returned for table columns (not expressions). col_type = "UNKNOWN"; unknown_type = true; } results.push_back(std::make_tuple( col_name, columnTypeName(col_type), ColumnOptions::DEFAULT)); } // An unknown type means we have to parse the plan and SQLite opcodes. if (unknown_type) { QueryPlanner planner(q, instance); planner.applyTypes(results); } sqlite3_finalize(stmt); } if (status.ok()) { columns = std::move(results); } return status; } } // namespace osquery
./CrossVul/dataset_final_sorted/CWE-77/cpp/good_4384_0
crossvul-cpp_data_bad_4384_3
/** * Copyright (c) 2014-present, The osquery authors * * This source code is licensed as defined by the LICENSE file found in the * root directory of this source tree. * * SPDX-License-Identifier: (Apache-2.0 OR GPL-2.0-only) */ #include <boost/algorithm/string.hpp> #include <osquery/core/core.h> #include <osquery/filesystem/filesystem.h> #include <osquery/logger/logger.h> #include <osquery/sql/sql.h> #include <osquery/utils/info/platform_type.h> #include "osquery/sql/dynamic_table_row.h" #include "osquery/sql/sqlite_util.h" namespace fs = boost::filesystem; namespace osquery { const char* getSystemVFS(bool respect_locking) { if (respect_locking) { return nullptr; } if (isPlatform(PlatformType::TYPE_POSIX)) { return "unix-none"; } else if (isPlatform(PlatformType::TYPE_WINDOWS)) { return "win32-none"; } return nullptr; } Status genSqliteTableRow(sqlite3_stmt* stmt, TableRows& qd, const fs::path& sqlite_db) { auto r = make_table_row(); for (int i = 0; i < sqlite3_column_count(stmt); ++i) { auto column_name = std::string(sqlite3_column_name(stmt, i)); auto column_type = sqlite3_column_type(stmt, i); switch (column_type) { case SQLITE_BLOB: case SQLITE_TEXT: { auto text_value = sqlite3_column_text(stmt, i); if (text_value != nullptr) { r[column_name] = std::string(reinterpret_cast<const char*>(text_value)); } break; } case SQLITE_FLOAT: { auto float_value = sqlite3_column_double(stmt, i); r[column_name] = DOUBLE(float_value); break; } case SQLITE_INTEGER: { auto int_value = sqlite3_column_int64(stmt, i); r[column_name] = INTEGER(int_value); break; } } } if (r.count("path") > 0) { LOG(WARNING) << "ATC Table: Row contains a defined path key, omitting the " "implicit one"; } else { r["path"] = sqlite_db.string(); } qd.push_back(std::move(r)); return Status::success(); } Status genTableRowsForSqliteTable(const fs::path& sqlite_db, const std::string& sqlite_query, TableRows& results, bool respect_locking) { sqlite3* db = nullptr; if (!pathExists(sqlite_db).ok()) { return Status(1, "Database path does not exist"); } auto rc = sqlite3_open_v2( sqlite_db.string().c_str(), &db, (SQLITE_OPEN_READONLY | SQLITE_OPEN_PRIVATECACHE | SQLITE_OPEN_NOMUTEX), getSystemVFS(respect_locking)); if (rc != SQLITE_OK || db == nullptr) { VLOG(1) << "Cannot open specified database: " << getStringForSQLiteReturnCode(rc); if (db != nullptr) { sqlite3_close(db); } return Status(1, "Could not open database"); } sqlite3_stmt* stmt = nullptr; rc = sqlite3_prepare_v2(db, sqlite_query.c_str(), -1, &stmt, nullptr); if (rc != SQLITE_OK) { sqlite3_close(db); VLOG(1) << "ATC table: Could not prepare database at path: " << sqlite_db; return Status(rc, "Could not prepare database"); } while ((sqlite3_step(stmt)) == SQLITE_ROW) { auto s = genSqliteTableRow(stmt, results, sqlite_db); if (!s.ok()) { break; } } // Close handles and free memory sqlite3_finalize(stmt); sqlite3_close(db); return Status{}; } Status getSqliteJournalMode(const fs::path& sqlite_db) { TableRows result; auto status = genTableRowsForSqliteTable( sqlite_db, "PRAGMA journal_mode;", result, true); if (!status.ok()) { return status; } if (result.empty()) { VLOG(1) << "PRAGMA query returned empty results"; return Status(1, "Could not retrieve journal mode"); } auto resultmap = static_cast<Row>(*result[0]); if (resultmap.find("journal_mode") == resultmap.end()) { VLOG(1) << "journal_mode not found PRAGMA query results"; return Status(1, "Could not retrieve journal mode"); } return Status(Status::kSuccessCode, boost::algorithm::to_lower_copy(resultmap["journal_mode"])); } } // namespace osquery
./CrossVul/dataset_final_sorted/CWE-77/cpp/bad_4384_3
crossvul-cpp_data_bad_4384_0
/** * Copyright (c) 2014-present, The osquery authors * * This source code is licensed as defined by the LICENSE file found in the * root directory of this source tree. * * SPDX-License-Identifier: (Apache-2.0 OR GPL-2.0-only) */ #include "osquery/sql/sqlite_util.h" #include "osquery/sql/virtual_table.h" #include <osquery/core/plugins/sql.h> #include <osquery/utils/conversions/castvariant.h> #include <osquery/core/core.h> #include <osquery/core/flags.h> #include <osquery/logger/logger.h> #include <osquery/registry/registry_factory.h> #include <osquery/sql/sql.h> #include <osquery/utils/conversions/split.h> #include <boost/lexical_cast.hpp> namespace osquery { FLAG(string, disable_tables, "", "Comma-delimited list of table names to be disabled"); FLAG(string, enable_tables, "", "Comma-delimited list of table names to be enabled"); FLAG(string, nullvalue, "", "Set string for NULL values, default ''"); using OpReg = QueryPlanner::Opcode::Register; using SQLiteDBInstanceRef = std::shared_ptr<SQLiteDBInstance>; /** * @brief A map of SQLite status codes to their corresponding message string * * Details of this map are defined at: http://www.sqlite.org/c3ref/c_abort.html */ // clang-format off const std::map<int, std::string> kSQLiteReturnCodes = { {0, "SQLITE_OK"}, {1, "SQLITE_ERROR"}, {2, "SQLITE_INTERNAL"}, {3, "SQLITE_PERM"}, {4, "SQLITE_ABORT"}, {5, "SQLITE_BUSY"}, {6, "SQLITE_LOCKED"}, {7, "SQLITE_NOMEM"}, {8, "SQLITE_READONLY"}, {9, "SQLITE_INTERRUPT"}, {10, "SQLITE_IOERR"}, {11, "SQLITE_CORRUPT"}, {12, "SQLITE_NOTFOUND"}, {13, "SQLITE_FULL"}, {14, "SQLITE_CANTOPEN"}, {15, "SQLITE_PROTOCOL"}, {16, "SQLITE_EMPTY"}, {17, "SQLITE_SCHEMA"}, {18, "SQLITE_TOOBIG"}, {19, "SQLITE_CONSTRAINT"}, {20, "SQLITE_MISMATCH"}, {21, "SQLITE_MISUSE"}, {22, "SQLITE_NOLFS"}, {23, "SQLITE_AUTH"}, {24, "SQLITE_FORMAT"}, {25, "SQLITE_RANGE"}, {26, "SQLITE_NOTADB"}, {27, "SQLITE_NOTICE"}, {28, "SQLITE_WARNING"}, {100, "SQLITE_ROW"}, {101, "SQLITE_DONE"}, }; const std::map<std::string, std::string> kMemoryDBSettings = { {"synchronous", "OFF"}, {"count_changes", "OFF"}, {"default_temp_store", "0"}, {"auto_vacuum", "FULL"}, {"journal_mode", "OFF"}, {"cache_size", "0"}, {"page_count", "0"}, }; // clang-format on #define OpComparator(x) \ { x, QueryPlanner::Opcode(OpReg::P2, INTEGER_TYPE) } #define Arithmetic(x) \ { x, QueryPlanner::Opcode(OpReg::P3, BIGINT_TYPE) } /** * @brief A map from opcode to pair of result register and resultant type. * * For most opcodes we can deduce a column type based on an interred input * to the opcode "function". These come in a few sets, arithmetic operators, * comparators, aggregates, and copies. */ const std::map<std::string, QueryPlanner::Opcode> kSQLOpcodes = { {"Concat", QueryPlanner::Opcode(OpReg::P3, TEXT_TYPE)}, {"AggStep", QueryPlanner::Opcode(OpReg::P3, BIGINT_TYPE)}, {"AggStep0", QueryPlanner::Opcode(OpReg::P3, BIGINT_TYPE)}, {"Integer", QueryPlanner::Opcode(OpReg::P2, INTEGER_TYPE)}, {"Int64", QueryPlanner::Opcode(OpReg::P2, BIGINT_TYPE)}, {"String", QueryPlanner::Opcode(OpReg::P2, TEXT_TYPE)}, {"String8", QueryPlanner::Opcode(OpReg::P2, TEXT_TYPE)}, {"Or", QueryPlanner::Opcode(OpReg::P3, INTEGER_TYPE)}, {"And", QueryPlanner::Opcode(OpReg::P3, INTEGER_TYPE)}, // Arithmetic yields a BIGINT for safety. Arithmetic("BitAnd"), Arithmetic("BitOr"), Arithmetic("ShiftLeft"), Arithmetic("ShiftRight"), Arithmetic("Add"), Arithmetic("Subtract"), Arithmetic("Multiply"), Arithmetic("Divide"), Arithmetic("Remainder"), // Comparators result in booleans and are treated as INTEGERs. OpComparator("Not"), OpComparator("IsNull"), OpComparator("NotNull"), OpComparator("Ne"), OpComparator("Eq"), OpComparator("Gt"), OpComparator("Le"), OpComparator("Lt"), OpComparator("Ge"), OpComparator("IfNeg"), OpComparator("IfNotZero"), }; RecursiveMutex SQLiteDBInstance::kPrimaryAttachMutex; /// The SQLiteSQLPlugin implements the "sql" registry for internal/core. class SQLiteSQLPlugin : public SQLPlugin { public: /// Execute SQL and store results. Status query(const std::string& query, QueryData& results, bool use_cache) const override; /// Introspect, explain, the suspected types selected in an SQL statement. Status getQueryColumns(const std::string& query, TableColumns& columns) const override; /// Similar to getQueryColumns but return the scanned tables. Status getQueryTables(const std::string& query, std::vector<std::string>& tables) const override; /// Create a SQLite module and attach (CREATE). Status attach(const std::string& name) override; /// Detach a virtual table (DROP). Status detach(const std::string& name) override; }; /// SQL provider for osquery internal/core. REGISTER_INTERNAL(SQLiteSQLPlugin, "sql", "sql"); std::string getStringForSQLiteReturnCode(int code) { if (kSQLiteReturnCodes.find(code) != kSQLiteReturnCodes.end()) { return kSQLiteReturnCodes.at(code); } else { std::ostringstream s; s << "Error: " << code << " is not a valid SQLite result code"; return s.str(); } } Status SQLiteSQLPlugin::query(const std::string& query, QueryData& results, bool use_cache) const { auto dbc = SQLiteDBManager::get(); dbc->useCache(use_cache); auto result = queryInternal(query, results, dbc); dbc->clearAffectedTables(); return result; } Status SQLiteSQLPlugin::getQueryColumns(const std::string& query, TableColumns& columns) const { auto dbc = SQLiteDBManager::get(); return getQueryColumnsInternal(query, columns, dbc); } Status SQLiteSQLPlugin::getQueryTables(const std::string& query, std::vector<std::string>& tables) const { auto dbc = SQLiteDBManager::get(); QueryPlanner planner(query, dbc); tables = planner.tables(); return Status(0); } SQLInternal::SQLInternal(const std::string& query, bool use_cache) { auto dbc = SQLiteDBManager::get(); dbc->useCache(use_cache); status_ = queryInternal(query, resultsTyped_, dbc); // One of the advantages of using SQLInternal (aside from the Registry-bypass) // is the ability to "deep-inspect" the table attributes and actions. event_based_ = (dbc->getAttributes() & TableAttributes::EVENT_BASED) != 0; dbc->clearAffectedTables(); } QueryDataTyped& SQLInternal::rowsTyped() { return resultsTyped_; } const Status& SQLInternal::getStatus() const { return status_; } bool SQLInternal::eventBased() const { return event_based_; } // Temporary: I'm going to move this from sql.cpp to here in change immediately // following since this is the only place we actually use it (breaking up to // make CRs smaller) extern void escapeNonPrintableBytesEx(std::string& str); class StringEscaperVisitor : public boost::static_visitor<> { public: void operator()(long long& i) const { // NO-OP } void operator()(double& d) const { // NO-OP } void operator()(std::string& str) const { escapeNonPrintableBytesEx(str); } }; void SQLInternal::escapeResults() { StringEscaperVisitor visitor; for (auto& rowTyped : resultsTyped_) { for (auto& column : rowTyped) { boost::apply_visitor(visitor, column.second); } } } Status SQLiteSQLPlugin::attach(const std::string& name) { PluginResponse response; auto status = Registry::call("table", name, {{"action", "columns"}}, response); if (!status.ok()) { return status; } bool is_extension = true; auto statement = columnDefinition(response, false, is_extension); // Attach requests occurring via the plugin/registry APIs must act on the // primary database. To allow this, getConnection can explicitly request the // primary instance and avoid the contention decisions. auto dbc = SQLiteDBManager::getConnection(true); // Attach as an extension, allowing read/write tables return attachTableInternal(name, statement, dbc, is_extension); } Status SQLiteSQLPlugin::detach(const std::string& name) { // Detach requests occurring via the plugin/registry APIs must act on the // primary database. To allow this, getConnection can explicitly request the // primary instance and avoid the contention decisions. auto dbc = SQLiteDBManager::getConnection(true); return detachTableInternal(name, dbc); } SQLiteDBInstance::SQLiteDBInstance(sqlite3*& db, Mutex& mtx) : db_(db), lock_(mtx, boost::try_to_lock) { if (lock_.owns_lock()) { primary_ = true; } else { db_ = nullptr; VLOG(1) << "DBManager contention: opening transient SQLite database"; init(); } } static inline void openOptimized(sqlite3*& db) { sqlite3_open(":memory:", &db); std::string settings; for (const auto& setting : kMemoryDBSettings) { settings += "PRAGMA " + setting.first + "=" + setting.second + "; "; } sqlite3_exec(db, settings.c_str(), nullptr, nullptr, nullptr); // Register function extensions. registerMathExtensions(db); #if !defined(FREEBSD) registerStringExtensions(db); #endif #if !defined(SKIP_CARVER) registerOperationExtensions(db); #endif registerFilesystemExtensions(db); registerHashingExtensions(db); registerEncodingExtensions(db); } void SQLiteDBInstance::init() { primary_ = false; openOptimized(db_); } void SQLiteDBInstance::useCache(bool use_cache) { use_cache_ = use_cache; } bool SQLiteDBInstance::useCache() const { return use_cache_; } RecursiveLock SQLiteDBInstance::attachLock() const { if (isPrimary()) { return RecursiveLock(kPrimaryAttachMutex); } return RecursiveLock(attach_mutex_); } void SQLiteDBInstance::addAffectedTable( std::shared_ptr<VirtualTableContent> table) { // An xFilter/scan was requested for this virtual table. affected_tables_.insert(std::make_pair(table->name, std::move(table))); } bool SQLiteDBInstance::tableCalled(VirtualTableContent const& table) { return (affected_tables_.count(table.name) > 0); } TableAttributes SQLiteDBInstance::getAttributes() const { const SQLiteDBInstance* rdbc = this; if (isPrimary() && !managed_) { // Similarly to clearAffectedTables, the connection may be forwarded. rdbc = SQLiteDBManager::getConnection(true).get(); } TableAttributes attributes = TableAttributes::NONE; for (const auto& table : rdbc->affected_tables_) { attributes = table.second->attributes | attributes; } return attributes; } void SQLiteDBInstance::clearAffectedTables() { if (isPrimary() && !managed_) { // A primary instance must forward clear requests to the DB manager's // 'connection' instance. This is a temporary primary instance. SQLiteDBManager::getConnection(true)->clearAffectedTables(); return; } for (const auto& table : affected_tables_) { table.second->constraints.clear(); table.second->cache.clear(); table.second->colsUsed.clear(); table.second->colsUsedBitsets.clear(); } // Since the affected tables are cleared, there are no more affected tables. // There is no concept of compounding tables between queries. affected_tables_.clear(); use_cache_ = false; } SQLiteDBInstance::~SQLiteDBInstance() { if (!isPrimary() && db_ != nullptr) { sqlite3_close(db_); } else { db_ = nullptr; } } SQLiteDBManager::SQLiteDBManager() : db_(nullptr) { sqlite3_soft_heap_limit64(1); setDisabledTables(Flag::getValue("disable_tables")); setEnabledTables(Flag::getValue("enable_tables")); } bool SQLiteDBManager::isDisabled(const std::string& table_name) { bool disabled_set = !Flag::isDefault("disable_tables"); bool enabled_set = !Flag::isDefault("enable_tables"); if (!disabled_set && !enabled_set) { // We have zero enabled tables and zero disabled tables. // As a result, no tables are disabled. return false; } const auto& element_disabled = instance().disabled_tables_.find(table_name); const auto& element_enabled = instance().enabled_tables_.find(table_name); bool table_disabled = (element_disabled != instance().disabled_tables_.end()); bool table_enabled = (element_enabled != instance().enabled_tables_.end()); if (table_disabled) { return true; } if (table_enabled && disabled_set && !table_disabled) { return false; } if (table_enabled && !disabled_set) { return false; } if (enabled_set && !table_enabled) { return true; } if (disabled_set && !table_disabled) { return false; } return true; } void SQLiteDBManager::resetPrimary() { auto& self = instance(); WriteLock connection_lock(self.mutex_); self.connection_.reset(); { WriteLock create_lock(self.create_mutex_); sqlite3_close(self.db_); self.db_ = nullptr; } } void SQLiteDBManager::setDisabledTables(const std::string& list) { const auto& tables = split(list, ","); disabled_tables_ = std::unordered_set<std::string>(tables.begin(), tables.end()); } void SQLiteDBManager::setEnabledTables(const std::string& list) { const auto& tables = split(list, ","); enabled_tables_ = std::unordered_set<std::string>(tables.begin(), tables.end()); } SQLiteDBInstanceRef SQLiteDBManager::getUnique() { auto instance = std::make_shared<SQLiteDBInstance>(); attachVirtualTables(instance); return instance; } SQLiteDBInstanceRef SQLiteDBManager::getConnection(bool primary) { auto& self = instance(); WriteLock lock(self.create_mutex_); if (self.db_ == nullptr) { // Create primary SQLite DB instance. openOptimized(self.db_); self.connection_ = SQLiteDBInstanceRef(new SQLiteDBInstance(self.db_)); attachVirtualTables(self.connection_); } // Internal usage may request the primary connection explicitly. if (primary) { return self.connection_; } // Create a 'database connection' for the managed database instance. auto instance = std::make_shared<SQLiteDBInstance>(self.db_, self.mutex_); if (!instance->isPrimary()) { attachVirtualTables(instance); } return instance; } SQLiteDBManager::~SQLiteDBManager() { connection_ = nullptr; if (db_ != nullptr) { sqlite3_close(db_); db_ = nullptr; } } QueryPlanner::QueryPlanner(const std::string& query, const SQLiteDBInstanceRef& instance) { QueryData plan; queryInternal("EXPLAIN QUERY PLAN " + query, plan, instance); queryInternal("EXPLAIN " + query, program_, instance); for (const auto& row : plan) { auto details = osquery::split(row.at("detail")); if (details.size() > 2 && details[0] == "SCAN") { tables_.push_back(details[2]); } } } Status QueryPlanner::applyTypes(TableColumns& columns) { std::map<size_t, ColumnType> column_types; for (const auto& row : program_) { if (row.at("opcode") == "ResultRow") { // The column parsing is finished. auto k = boost::lexical_cast<size_t>(row.at("p1")); for (const auto& type : column_types) { if (type.first - k < columns.size()) { std::get<1>(columns[type.first - k]) = type.second; } } } if (row.at("opcode") == "Copy") { // Copy P1 -> P1 + P3 into P2 -> P2 + P3. auto from = boost::lexical_cast<size_t>(row.at("p1")); auto to = boost::lexical_cast<size_t>(row.at("p2")); auto size = boost::lexical_cast<size_t>(row.at("p3")); for (size_t i = 0; i <= size; i++) { if (column_types.count(from + i)) { column_types[to + i] = std::move(column_types[from + i]); column_types.erase(from + i); } } } else if (row.at("opcode") == "Cast") { auto value = boost::lexical_cast<size_t>(row.at("p1")); auto to = boost::lexical_cast<size_t>(row.at("p2")); switch (to) { case 'A': // BLOB column_types[value] = BLOB_TYPE; break; case 'B': // TEXT column_types[value] = TEXT_TYPE; break; case 'C': // NUMERIC // We don't exactly have an equivalent to NUMERIC (which includes such // things as DATETIME and DECIMAL column_types[value] = UNKNOWN_TYPE; break; case 'D': // INTEGER column_types[value] = BIGINT_TYPE; break; case 'E': // REAL column_types[value] = DOUBLE_TYPE; break; default: column_types[value] = UNKNOWN_TYPE; break; } } if (kSQLOpcodes.count(row.at("opcode"))) { const auto& op = kSQLOpcodes.at(row.at("opcode")); auto k = boost::lexical_cast<size_t>(row.at(Opcode::regString(op.reg))); column_types[k] = op.type; } } return Status(0); } // Wrapper for legacy method until all uses can be replaced Status queryInternal(const std::string& query, QueryData& results, const SQLiteDBInstanceRef& instance) { QueryDataTyped typedResults; Status status = queryInternal(query, typedResults, instance); if (status.ok()) { results.reserve(typedResults.size()); for (const auto& row : typedResults) { Row r; for (const auto& col : row) { r[col.first] = castVariant(col.second); } results.push_back(std::move(r)); } } return status; } Status readRows(sqlite3_stmt* prepared_statement, QueryDataTyped& results, const SQLiteDBInstanceRef& instance) { // Do nothing with a null prepared_statement (eg, if the sql was just // whitespace) if (prepared_statement == nullptr) { return Status::success(); } int rc = sqlite3_step(prepared_statement); /* if we have a result set row... */ if (SQLITE_ROW == rc) { // First collect the column names int num_columns = sqlite3_column_count(prepared_statement); std::vector<std::string> colNames; colNames.reserve(num_columns); for (int i = 0; i < num_columns; i++) { colNames.push_back(sqlite3_column_name(prepared_statement, i)); } do { RowTyped row; for (int i = 0; i < num_columns; i++) { switch (sqlite3_column_type(prepared_statement, i)) { case SQLITE_INTEGER: row[colNames[i]] = static_cast<long long>( sqlite3_column_int64(prepared_statement, i)); break; case SQLITE_FLOAT: row[colNames[i]] = sqlite3_column_double(prepared_statement, i); break; case SQLITE_NULL: row[colNames[i]] = FLAGS_nullvalue; break; default: // Everything else (SQLITE_TEXT, SQLITE3_TEXT, SQLITE_BLOB) is // obtained/conveyed as text/string row[colNames[i]] = std::string(reinterpret_cast<const char*>( sqlite3_column_text(prepared_statement, i))); } } results.push_back(std::move(row)); rc = sqlite3_step(prepared_statement); } while (SQLITE_ROW == rc); } if (rc != SQLITE_DONE) { auto s = Status::failure(sqlite3_errmsg(instance->db())); sqlite3_finalize(prepared_statement); return s; } rc = sqlite3_finalize(prepared_statement); if (rc != SQLITE_OK) { return Status::failure(sqlite3_errmsg(instance->db())); } return Status::success(); } Status queryInternal(const std::string& query, QueryDataTyped& results, const SQLiteDBInstanceRef& instance) { sqlite3_stmt* prepared_statement{nullptr}; /* Statement to execute. */ int rc = SQLITE_OK; /* Return Code */ const char* leftover_sql = nullptr; /* Tail of unprocessed SQL */ const char* sql = query.c_str(); /* SQL to be processed */ /* The big while loop. One iteration per statement */ while ((sql[0] != '\0') && (SQLITE_OK == rc)) { const auto lock = instance->attachLock(); // Trim leading whitespace while (isspace(sql[0])) { sql++; } rc = sqlite3_prepare_v2( instance->db(), sql, -1, &prepared_statement, &leftover_sql); if (rc != SQLITE_OK) { Status s = Status::failure(sqlite3_errmsg(instance->db())); sqlite3_finalize(prepared_statement); return s; } Status s = readRows(prepared_statement, results, instance); if (!s.ok()) { return s; } sql = leftover_sql; } /* end while */ sqlite3_db_release_memory(instance->db()); return Status::success(); } Status getQueryColumnsInternal(const std::string& q, TableColumns& columns, const SQLiteDBInstanceRef& instance) { Status status = Status(); TableColumns results; { auto lock = instance->attachLock(); // Turn the query into a prepared statement sqlite3_stmt* stmt{nullptr}; auto rc = sqlite3_prepare_v2(instance->db(), q.c_str(), static_cast<int>(q.length() + 1), &stmt, nullptr); if (rc != SQLITE_OK || stmt == nullptr) { auto s = Status::failure(sqlite3_errmsg(instance->db())); if (stmt != nullptr) { sqlite3_finalize(stmt); } return s; } // Get column count auto num_columns = sqlite3_column_count(stmt); results.reserve(num_columns); // Get column names and types bool unknown_type = false; for (int i = 0; i < num_columns; ++i) { auto col_name = sqlite3_column_name(stmt, i); auto col_type = sqlite3_column_decltype(stmt, i); if (col_name == nullptr) { status = Status(1, "Could not get column type"); break; } if (col_type == nullptr) { // Types are only returned for table columns (not expressions). col_type = "UNKNOWN"; unknown_type = true; } results.push_back(std::make_tuple( col_name, columnTypeName(col_type), ColumnOptions::DEFAULT)); } // An unknown type means we have to parse the plan and SQLite opcodes. if (unknown_type) { QueryPlanner planner(q, instance); planner.applyTypes(results); } sqlite3_finalize(stmt); } if (status.ok()) { columns = std::move(results); } return status; } } // namespace osquery
./CrossVul/dataset_final_sorted/CWE-77/cpp/bad_4384_0
crossvul-cpp_data_good_2351_0
/* * read.c - read the blkid cache from disk, to avoid scanning all devices * * Copyright (C) 2001, 2003 Theodore Y. Ts'o * Copyright (C) 2001 Andreas Dilger * * %Begin-Header% * This file may be redistributed under the terms of the * GNU Lesser General Public License. * %End-Header% */ #include <stdio.h> #include <ctype.h> #include <string.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #ifdef HAVE_ERRNO_H #include <errno.h> #endif #include "blkidP.h" #ifdef HAVE_STDLIB_H # ifndef _XOPEN_SOURCE # define _XOPEN_SOURCE 600 /* for inclusion of strtoull */ # endif # include <stdlib.h> #endif #ifdef HAVE_STRTOULL #define STRTOULL strtoull /* defined in stdlib.h if you try hard enough */ #else /* FIXME: need to support real strtoull here */ #define STRTOULL strtoul #endif #ifdef TEST_PROGRAM #define blkid_debug_dump_dev(dev) (debug_dump_dev(dev)) static void debug_dump_dev(blkid_dev dev); #endif /* * File format: * * <device [<NAME="value"> ...]>device_name</device> * * The following tags are required for each entry: * <ID="id"> unique (within this file) ID number of this device * <TIME="sec.usec"> (time_t and suseconds_t) time this entry was last * read from disk * <TYPE="type"> (detected) type of filesystem/data for this partition * * The following tags may be present, depending on the device contents * <LABEL="label"> (user supplied) label (volume name, etc) * <UUID="uuid"> (generated) universally unique identifier (serial no) */ static char *skip_over_blank(char *cp) { while (*cp && isspace(*cp)) cp++; return cp; } static char *skip_over_word(char *cp) { char ch; while ((ch = *cp)) { /* If we see a backslash, skip the next character */ if (ch == '\\') { cp++; if (*cp == '\0') break; cp++; continue; } if (isspace(ch) || ch == '<' || ch == '>') break; cp++; } return cp; } static char *strip_line(char *line) { char *p; line = skip_over_blank(line); p = line + strlen(line) - 1; while (*line) { if (isspace(*p)) *p-- = '\0'; else break; } return line; } #if 0 static char *parse_word(char **buf) { char *word, *next; word = *buf; if (*word == '\0') return NULL; word = skip_over_blank(word); next = skip_over_word(word); if (*next) { char *end = next - 1; if (*end == '"' || *end == '\'') *end = '\0'; *next++ = '\0'; } *buf = next; if (*word == '"' || *word == '\'') word++; return word; } #endif /* * Start parsing a new line from the cache. * * line starts with "<device" return 1 -> continue parsing line * line starts with "<foo", empty, or # return 0 -> skip line * line starts with other, return -BLKID_ERR_CACHE -> error */ static int parse_start(char **cp) { char *p; p = strip_line(*cp); /* Skip comment or blank lines. We can't just NUL the first '#' char, * in case it is inside quotes, or escaped. */ if (*p == '\0' || *p == '#') return 0; if (!strncmp(p, "<device", 7)) { DBG(READ, ul_debug("found device header: %8s", p)); p += 7; *cp = p; return 1; } if (*p == '<') return 0; return -BLKID_ERR_CACHE; } /* Consume the remaining XML on the line (cosmetic only) */ static int parse_end(char **cp) { *cp = skip_over_blank(*cp); if (!strncmp(*cp, "</device>", 9)) { DBG(READ, ul_debug("found device trailer %9s", *cp)); *cp += 9; return 0; } return -BLKID_ERR_CACHE; } /* * Allocate a new device struct with device name filled in. Will handle * finding the device on lines of the form: * <device foo=bar>devname</device> * <device>devname<foo>bar</foo></device> */ static int parse_dev(blkid_cache cache, blkid_dev *dev, char **cp) { char *start, *tmp, *end, *name; int ret; if ((ret = parse_start(cp)) <= 0) return ret; start = tmp = strchr(*cp, '>'); if (!start) { DBG(READ, ul_debug("blkid: short line parsing dev: %s", *cp)); return -BLKID_ERR_CACHE; } start = skip_over_blank(start + 1); end = skip_over_word(start); DBG(READ, ul_debug("device should be %*s", (int)(end - start), start)); if (**cp == '>') *cp = end; else (*cp)++; *tmp = '\0'; if (!(tmp = strrchr(end, '<')) || parse_end(&tmp) < 0) { DBG(READ, ul_debug("blkid: missing </device> ending: %s", end)); } else if (tmp) *tmp = '\0'; if (end - start <= 1) { DBG(READ, ul_debug("blkid: empty device name: %s", *cp)); return -BLKID_ERR_CACHE; } name = strndup(start, end - start); if (name == NULL) return -BLKID_ERR_MEM; DBG(READ, ul_debug("found dev %s", name)); if (!(*dev = blkid_get_dev(cache, name, BLKID_DEV_CREATE))) { free(name); return -BLKID_ERR_MEM; } free(name); return 1; } /* * Extract a tag of the form NAME="value" from the line. */ static int parse_token(char **name, char **value, char **cp) { char *end; if (!name || !value || !cp) return -BLKID_ERR_PARAM; if (!(*value = strchr(*cp, '='))) return 0; **value = '\0'; *name = strip_line(*cp); *value = skip_over_blank(*value + 1); if (**value == '"') { char *p = end = *value + 1; /* convert 'foo\"bar' to 'foo"bar' */ while (*p) { if (*p == '\\') { p++; *end = *p; } else { *end = *p; if (*p == '"') break; } p++; end++; } if (*end != '"') { DBG(READ, ul_debug("unbalanced quotes at: %s", *value)); *cp = *value; return -BLKID_ERR_CACHE; } (*value)++; *end = '\0'; end = ++p; } else { end = skip_over_word(*value); if (*end) { *end = '\0'; end++; } } *cp = end; return 1; } /* * Extract a tag of the form <NAME>value</NAME> from the line. */ /* static int parse_xml(char **name, char **value, char **cp) { char *end; if (!name || !value || !cp) return -BLKID_ERR_PARAM; *name = strip_line(*cp); if ((*name)[0] != '<' || (*name)[1] == '/') return 0; FIXME: finish this. } */ /* * Extract a tag from the line. * * Return 1 if a valid tag was found. * Return 0 if no tag found. * Return -ve error code. */ static int parse_tag(blkid_cache cache, blkid_dev dev, char **cp) { char *name = NULL; char *value = NULL; int ret; if (!cache || !dev) return -BLKID_ERR_PARAM; if ((ret = parse_token(&name, &value, cp)) <= 0 /* && (ret = parse_xml(&name, &value, cp)) <= 0 */) return ret; /* Some tags are stored directly in the device struct */ if (!strcmp(name, "DEVNO")) dev->bid_devno = STRTOULL(value, 0, 0); else if (!strcmp(name, "PRI")) dev->bid_pri = strtol(value, 0, 0); else if (!strcmp(name, "TIME")) { char *end = NULL; dev->bid_time = STRTOULL(value, &end, 0); if (end && *end == '.') dev->bid_utime = STRTOULL(end + 1, 0, 0); } else ret = blkid_set_tag(dev, name, value, strlen(value)); DBG(READ, ul_debug(" tag: %s=\"%s\"", name, value)); return ret < 0 ? ret : 1; } /* * Parse a single line of data, and return a newly allocated dev struct. * Add the new device to the cache struct, if one was read. * * Lines are of the form <device [TAG="value" ...]>/dev/foo</device> * * Returns -ve value on error. * Returns 0 otherwise. * If a valid device was read, *dev_p is non-NULL, otherwise it is NULL * (e.g. comment lines, unknown XML content, etc). */ static int blkid_parse_line(blkid_cache cache, blkid_dev *dev_p, char *cp) { blkid_dev dev; int ret; if (!cache || !dev_p) return -BLKID_ERR_PARAM; *dev_p = NULL; DBG(READ, ul_debug("line: %s", cp)); if ((ret = parse_dev(cache, dev_p, &cp)) <= 0) return ret; dev = *dev_p; while ((ret = parse_tag(cache, dev, &cp)) > 0) { ; } if (dev->bid_type == NULL) { DBG(READ, ul_debug("blkid: device %s has no TYPE",dev->bid_name)); blkid_free_dev(dev); goto done; } DBG(READ, blkid_debug_dump_dev(dev)); done: return ret; } /* * Parse the specified filename, and return the data in the supplied or * a newly allocated cache struct. If the file doesn't exist, return a * new empty cache struct. */ void blkid_read_cache(blkid_cache cache) { FILE *file; char buf[4096]; int fd, lineno = 0; struct stat st; if (!cache) return; /* * If the file doesn't exist, then we just return an empty * struct so that the cache can be populated. */ if ((fd = open(cache->bic_filename, O_RDONLY|O_CLOEXEC)) < 0) return; if (fstat(fd, &st) < 0) goto errout; if ((st.st_mtime == cache->bic_ftime) || (cache->bic_flags & BLKID_BIC_FL_CHANGED)) { DBG(CACHE, ul_debug("skipping re-read of %s", cache->bic_filename)); goto errout; } DBG(CACHE, ul_debug("reading cache file %s", cache->bic_filename)); file = fdopen(fd, "r" UL_CLOEXECSTR); if (!file) goto errout; while (fgets(buf, sizeof(buf), file)) { blkid_dev dev; unsigned int end; lineno++; if (buf[0] == 0) continue; end = strlen(buf) - 1; /* Continue reading next line if it ends with a backslash */ while (end < (sizeof(buf) - 2) && buf[end] == '\\' && fgets(buf + end, sizeof(buf) - end, file)) { end = strlen(buf) - 1; lineno++; } if (blkid_parse_line(cache, &dev, buf) < 0) { DBG(READ, ul_debug("blkid: bad format on line %d", lineno)); continue; } } fclose(file); /* * Initially we do not need to write out the cache file. */ cache->bic_flags &= ~BLKID_BIC_FL_CHANGED; cache->bic_ftime = st.st_mtime; return; errout: close(fd); return; } #ifdef TEST_PROGRAM static void debug_dump_dev(blkid_dev dev) { struct list_head *p; if (!dev) { printf(" dev: NULL\n"); return; } printf(" dev: name = %s\n", dev->bid_name); printf(" dev: DEVNO=\"0x%0llx\"\n", (long long)dev->bid_devno); printf(" dev: TIME=\"%ld.%ld\"\n", (long)dev->bid_time, (long)dev->bid_utime); printf(" dev: PRI=\"%d\"\n", dev->bid_pri); printf(" dev: flags = 0x%08X\n", dev->bid_flags); list_for_each(p, &dev->bid_tags) { blkid_tag tag = list_entry(p, struct blkid_struct_tag, bit_tags); if (tag) printf(" tag: %s=\"%s\"\n", tag->bit_name, tag->bit_val); else printf(" tag: NULL\n"); } printf("\n"); } int main(int argc, char**argv) { blkid_cache cache = NULL; int ret; blkid_init_debug(BLKID_DEBUG_ALL); if (argc > 2) { fprintf(stderr, "Usage: %s [filename]\n" "Test parsing of the cache (filename)\n", argv[0]); exit(1); } if ((ret = blkid_get_cache(&cache, argv[1])) < 0) fprintf(stderr, "error %d reading cache file %s\n", ret, argv[1] ? argv[1] : blkid_get_cache_filename(NULL)); blkid_put_cache(cache); return ret; } #endif
./CrossVul/dataset_final_sorted/CWE-77/c/good_2351_0
crossvul-cpp_data_good_251_4
/** * @file * IMAP helper functions * * @authors * Copyright (C) 1996-1998,2010,2012-2013 Michael R. Elkins <me@mutt.org> * Copyright (C) 1996-1999 Brandon Long <blong@fiction.net> * Copyright (C) 1999-2009,2012 Brendan Cully <brendan@kublai.com> * * @copyright * 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, see <http://www.gnu.org/licenses/>. */ /** * @page imap_util IMAP helper functions * * IMAP helper functions */ #include "config.h" #include <ctype.h> #include <errno.h> #include <netdb.h> #include <netinet/in.h> #include <signal.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include "imap_private.h" #include "mutt/mutt.h" #include "conn/conn.h" #include "bcache.h" #include "context.h" #include "globals.h" #include "header.h" #include "imap/imap.h" #include "mailbox.h" #include "message.h" #include "mutt_account.h" #include "mutt_socket.h" #include "mx.h" #include "options.h" #include "protos.h" #include "url.h" #ifdef USE_HCACHE #include "hcache/hcache.h" #endif /** * imap_expand_path - Canonicalise an IMAP path * @param path Buffer containing path * @param len Buffer length * @retval 0 Success * @retval -1 Error * * IMAP implementation of mutt_expand_path. Rewrite an IMAP path in canonical * and absolute form. The buffer is rewritten in place with the canonical IMAP * path. * * Function can fail if imap_parse_path() or url_tostring() fail, * of if the buffer isn't large enough. */ int imap_expand_path(char *path, size_t len) { struct ImapMbox mx; struct ImapData *idata = NULL; struct Url url; char fixedpath[LONG_STRING]; int rc; if (imap_parse_path(path, &mx) < 0) return -1; idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW); mutt_account_tourl(&mx.account, &url); imap_fix_path(idata, mx.mbox, fixedpath, sizeof(fixedpath)); url.path = fixedpath; rc = url_tostring(&url, path, len, U_DECODE_PASSWD); FREE(&mx.mbox); return rc; } /** * imap_get_parent - Get an IMAP folder's parent * @param output Buffer for the result * @param mbox Mailbox whose parent is to be determined * @param olen Length of the buffer * @param delim Path delimiter */ void imap_get_parent(char *output, const char *mbox, size_t olen, char delim) { int n; /* Make a copy of the mailbox name, but only if the pointers are different */ if (mbox != output) mutt_str_strfcpy(output, mbox, olen); n = mutt_str_strlen(output); /* Let's go backwards until the next delimiter * * If output[n] is a '/', the first n-- will allow us * to ignore it. If it isn't, then output looks like * "/aaaaa/bbbb". There is at least one "b", so we can't skip * the "/" after the 'a's. * * If output == '/', then n-- => n == 0, so the loop ends * immediately */ for (n--; n >= 0 && output[n] != delim; n--) ; /* We stopped before the beginning. There is a trailing * slash. */ if (n > 0) { /* Strip the trailing delimiter. */ output[n] = '\0'; } else { output[0] = (n == 0) ? delim : '\0'; } } /** * imap_get_parent_path - Get the path of the parent folder * @param output Buffer for the result * @param path Mailbox whose parent is to be determined * @param olen Length of the buffer * * Provided an imap path, returns in output the parent directory if * existent. Else returns the same path. */ void imap_get_parent_path(char *output, const char *path, size_t olen) { struct ImapMbox mx; struct ImapData *idata = NULL; char mbox[LONG_STRING] = ""; if (imap_parse_path(path, &mx) < 0) { mutt_str_strfcpy(output, path, olen); return; } idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW); if (!idata) { mutt_str_strfcpy(output, path, olen); return; } /* Stores a fixed path in mbox */ imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox)); /* Gets the parent mbox in mbox */ imap_get_parent(mbox, mbox, sizeof(mbox), idata->delim); /* Returns a fully qualified IMAP url */ imap_qualify_path(output, olen, &mx, mbox); FREE(&mx.mbox); } /** * imap_clean_path - Cleans an IMAP path using imap_fix_path * @param path Path to be cleaned * @param plen Length of the buffer * * Does it in place. */ void imap_clean_path(char *path, size_t plen) { struct ImapMbox mx; struct ImapData *idata = NULL; char mbox[LONG_STRING] = ""; if (imap_parse_path(path, &mx) < 0) return; idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW); if (!idata) return; /* Stores a fixed path in mbox */ imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox)); /* Returns a fully qualified IMAP url */ imap_qualify_path(path, plen, &mx, mbox); } #ifdef USE_HCACHE /** * imap_hcache_namer - Generate a filename for the header cache * @param path Path for the header cache file * @param dest Buffer for result * @param dlen Length of buffer * @retval num Chars written to dest */ static int imap_hcache_namer(const char *path, char *dest, size_t dlen) { return snprintf(dest, dlen, "%s.hcache", path); } /** * imap_hcache_open - Open a header cache * @param idata Server data * @param path Path to the header cache * @retval ptr HeaderCache * @retval NULL Failure */ header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path) { struct ImapMbox mx; struct Url url; char cachepath[PATH_MAX]; char mbox[PATH_MAX]; if (path) imap_cachepath(idata, path, mbox, sizeof(mbox)); else { if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0) return NULL; imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox)); FREE(&mx.mbox); } mutt_account_tourl(&idata->conn->account, &url); url.path = mbox; url_tostring(&url, cachepath, sizeof(cachepath), U_PATH); return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer); } /** * imap_hcache_close - Close the header cache * @param idata Server data */ void imap_hcache_close(struct ImapData *idata) { if (!idata->hcache) return; mutt_hcache_close(idata->hcache); idata->hcache = NULL; } /** * imap_hcache_get - Get a header cache entry by its UID * @param idata Server data * @param uid UID to find * @retval ptr Email Header * @retval NULL Failure */ struct Header *imap_hcache_get(struct ImapData *idata, unsigned int uid) { char key[16]; void *uv = NULL; struct Header *h = NULL; if (!idata->hcache) return NULL; sprintf(key, "/%u", uid); uv = mutt_hcache_fetch(idata->hcache, key, imap_hcache_keylen(key)); if (uv) { if (*(unsigned int *) uv == idata->uid_validity) h = mutt_hcache_restore(uv); else mutt_debug(3, "hcache uidvalidity mismatch: %u\n", *(unsigned int *) uv); mutt_hcache_free(idata->hcache, &uv); } return h; } /** * imap_hcache_put - Add an entry to the header cache * @param idata Server data * @param h Email Header * @retval 0 Success * @retval -1 Failure */ int imap_hcache_put(struct ImapData *idata, struct Header *h) { char key[16]; if (!idata->hcache) return -1; sprintf(key, "/%u", HEADER_DATA(h)->uid); return mutt_hcache_store(idata->hcache, key, imap_hcache_keylen(key), h, idata->uid_validity); } /** * imap_hcache_del - Delete an item from the header cache * @param idata Server data * @param uid UID of entry to delete * @retval 0 Success * @retval -1 Failure */ int imap_hcache_del(struct ImapData *idata, unsigned int uid) { char key[16]; if (!idata->hcache) return -1; sprintf(key, "/%u", uid); return mutt_hcache_delete(idata->hcache, key, imap_hcache_keylen(key)); } #endif /** * imap_parse_path - Parse an IMAP mailbox name into name,host,port * @param path Mailbox path to parse * @param mx An IMAP mailbox * @retval 0 Success * @retval -1 Failure * * Given an IMAP mailbox name, return host, port and a path IMAP servers will * recognize. mx.mbox is malloc'd, caller must free it */ int imap_parse_path(const char *path, struct ImapMbox *mx) { static unsigned short ImapPort = 0; static unsigned short ImapsPort = 0; struct servent *service = NULL; struct Url url; char *c = NULL; if (!ImapPort) { service = getservbyname("imap", "tcp"); if (service) ImapPort = ntohs(service->s_port); else ImapPort = IMAP_PORT; mutt_debug(3, "Using default IMAP port %d\n", ImapPort); } if (!ImapsPort) { service = getservbyname("imaps", "tcp"); if (service) ImapsPort = ntohs(service->s_port); else ImapsPort = IMAP_SSL_PORT; mutt_debug(3, "Using default IMAPS port %d\n", ImapsPort); } /* Defaults */ memset(&mx->account, 0, sizeof(mx->account)); mx->account.port = ImapPort; mx->account.type = MUTT_ACCT_TYPE_IMAP; c = mutt_str_strdup(path); url_parse(&url, c); if (url.scheme == U_IMAP || url.scheme == U_IMAPS) { if (mutt_account_fromurl(&mx->account, &url) < 0 || !*mx->account.host) { url_free(&url); FREE(&c); return -1; } mx->mbox = mutt_str_strdup(url.path); if (url.scheme == U_IMAPS) mx->account.flags |= MUTT_ACCT_SSL; url_free(&url); FREE(&c); } /* old PINE-compatibility code */ else { url_free(&url); FREE(&c); char tmp[128]; if (sscanf(path, "{%127[^}]}", tmp) != 1) return -1; c = strchr(path, '}'); if (!c) return -1; else { /* walk past closing '}' */ mx->mbox = mutt_str_strdup(c + 1); } c = strrchr(tmp, '@'); if (c) { *c = '\0'; mutt_str_strfcpy(mx->account.user, tmp, sizeof(mx->account.user)); mutt_str_strfcpy(tmp, c + 1, sizeof(tmp)); mx->account.flags |= MUTT_ACCT_USER; } const int n = sscanf(tmp, "%127[^:/]%127s", mx->account.host, tmp); if (n < 1) { mutt_debug(1, "NULL host in %s\n", path); FREE(&mx->mbox); return -1; } if (n > 1) { if (sscanf(tmp, ":%hu%127s", &(mx->account.port), tmp) >= 1) mx->account.flags |= MUTT_ACCT_PORT; if (sscanf(tmp, "/%s", tmp) == 1) { if (mutt_str_strncmp(tmp, "ssl", 3) == 0) mx->account.flags |= MUTT_ACCT_SSL; else { mutt_debug(1, "Unknown connection type in %s\n", path); FREE(&mx->mbox); return -1; } } } } if ((mx->account.flags & MUTT_ACCT_SSL) && !(mx->account.flags & MUTT_ACCT_PORT)) mx->account.port = ImapsPort; return 0; } /** * imap_mxcmp - Compare mailbox names, giving priority to INBOX * @param mx1 First mailbox name * @param mx2 Second mailbox name * @retval <0 First mailbox precedes Second mailbox * @retval 0 Mailboxes are the same * @retval >0 Second mailbox precedes First mailbox * * Like a normal sort function except that "INBOX" will be sorted to the * beginning of the list. */ int imap_mxcmp(const char *mx1, const char *mx2) { char *b1 = NULL; char *b2 = NULL; int rc; if (!mx1 || !*mx1) mx1 = "INBOX"; if (!mx2 || !*mx2) mx2 = "INBOX"; if ((mutt_str_strcasecmp(mx1, "INBOX") == 0) && (mutt_str_strcasecmp(mx2, "INBOX") == 0)) { return 0; } b1 = mutt_mem_malloc(strlen(mx1) + 1); b2 = mutt_mem_malloc(strlen(mx2) + 1); imap_fix_path(NULL, mx1, b1, strlen(mx1) + 1); imap_fix_path(NULL, mx2, b2, strlen(mx2) + 1); rc = mutt_str_strcmp(b1, b2); FREE(&b1); FREE(&b2); return rc; } /** * imap_pretty_mailbox - Prettify an IMAP mailbox name * @param path Mailbox name to be tidied * * Called by mutt_pretty_mailbox() to make IMAP paths look nice. */ void imap_pretty_mailbox(char *path) { struct ImapMbox home, target; struct Url url; char *delim = NULL; int tlen; int hlen = 0; bool home_match = false; if (imap_parse_path(path, &target) < 0) return; tlen = mutt_str_strlen(target.mbox); /* check whether we can do '=' substitution */ if (mx_is_imap(Folder) && !imap_parse_path(Folder, &home)) { hlen = mutt_str_strlen(home.mbox); if (tlen && mutt_account_match(&home.account, &target.account) && (mutt_str_strncmp(home.mbox, target.mbox, hlen) == 0)) { if (hlen == 0) home_match = true; else if (ImapDelimChars) { for (delim = ImapDelimChars; *delim != '\0'; delim++) if (target.mbox[hlen] == *delim) home_match = true; } } FREE(&home.mbox); } /* do the '=' substitution */ if (home_match) { *path++ = '='; /* copy remaining path, skipping delimiter */ if (hlen == 0) hlen = -1; memcpy(path, target.mbox + hlen + 1, tlen - hlen - 1); path[tlen - hlen - 1] = '\0'; } else { mutt_account_tourl(&target.account, &url); url.path = target.mbox; /* FIXME: That hard-coded constant is bogus. But we need the actual * size of the buffer from mutt_pretty_mailbox. And these pretty * operations usually shrink the result. Still... */ url_tostring(&url, path, 1024, 0); } FREE(&target.mbox); } /** * imap_continue - display a message and ask the user if they want to go on * @param msg Location of the error * @param resp Message for user * @retval num Result: #MUTT_YES, #MUTT_NO, #MUTT_ABORT */ int imap_continue(const char *msg, const char *resp) { imap_error(msg, resp); return mutt_yesorno(_("Continue?"), 0); } /** * imap_error - show an error and abort * @param where Location of the error * @param msg Message for user */ void imap_error(const char *where, const char *msg) { mutt_error("%s [%s]\n", where, msg); } /** * imap_new_idata - Allocate and initialise a new ImapData structure * @retval NULL Failure (no mem) * @retval ptr New ImapData */ struct ImapData *imap_new_idata(void) { struct ImapData *idata = mutt_mem_calloc(1, sizeof(struct ImapData)); idata->cmdbuf = mutt_buffer_new(); idata->cmdslots = ImapPipelineDepth + 2; idata->cmds = mutt_mem_calloc(idata->cmdslots, sizeof(*idata->cmds)); STAILQ_INIT(&idata->flags); STAILQ_INIT(&idata->mboxcache); return idata; } /** * imap_free_idata - Release and clear storage in an ImapData structure * @param idata Server data */ void imap_free_idata(struct ImapData **idata) { if (!idata) return; FREE(&(*idata)->capstr); mutt_list_free(&(*idata)->flags); imap_mboxcache_free(*idata); mutt_buffer_free(&(*idata)->cmdbuf); FREE(&(*idata)->buf); mutt_bcache_close(&(*idata)->bcache); FREE(&(*idata)->cmds); FREE(idata); } /** * imap_fix_path - Fix up the imap path * @param idata Server data * @param mailbox Mailbox path * @param path Buffer for the result * @param plen Length of buffer * @retval ptr Fixed-up path * * This is necessary because the rest of neomutt assumes a hierarchy delimiter of * '/', which is not necessarily true in IMAP. Additionally, the filesystem * converts multiple hierarchy delimiters into a single one, ie "///" is equal * to "/". IMAP servers are not required to do this. * Moreover, IMAP servers may dislike the path ending with the delimiter. */ char *imap_fix_path(struct ImapData *idata, const char *mailbox, char *path, size_t plen) { int i = 0; char delim = '\0'; if (idata) delim = idata->delim; while (mailbox && *mailbox && i < plen - 1) { if ((ImapDelimChars && strchr(ImapDelimChars, *mailbox)) || (delim && *mailbox == delim)) { /* use connection delimiter if known. Otherwise use user delimiter */ if (!idata) delim = *mailbox; while (*mailbox && ((ImapDelimChars && strchr(ImapDelimChars, *mailbox)) || (delim && *mailbox == delim))) { mailbox++; } path[i] = delim; } else { path[i] = *mailbox; mailbox++; } i++; } if (i && path[--i] != delim) i++; path[i] = '\0'; return path; } /** * imap_cachepath - Generate a cache path for a mailbox * @param idata Server data * @param mailbox Mailbox name * @param dest Buffer to store cache path * @param dlen Length of buffer */ void imap_cachepath(struct ImapData *idata, const char *mailbox, char *dest, size_t dlen) { char *s = NULL; const char *p = mailbox; for (s = dest; p && *p && dlen; dlen--) { if (*p == idata->delim) { *s = '/'; /* simple way to avoid collisions with UIDs */ if (*(p + 1) >= '0' && *(p + 1) <= '9') { if (--dlen) *++s = '_'; } } else *s = *p; p++; s++; } *s = '\0'; } /** * imap_get_literal_count - write number of bytes in an IMAP literal into bytes * @param[in] buf Number as a string * @param[out] bytes Resulting number * @retval 0 Success * @retval -1 Failure */ int imap_get_literal_count(const char *buf, unsigned int *bytes) { char *pc = NULL; char *pn = NULL; if (!buf || !(pc = strchr(buf, '{'))) return -1; pc++; pn = pc; while (isdigit((unsigned char) *pc)) pc++; *pc = '\0'; if (mutt_str_atoui(pn, bytes) < 0) return -1; return 0; } /** * imap_get_qualifier - Get the qualifier from a tagged response * @param buf Command string to process * @retval ptr Start of the qualifier * * In a tagged response, skip tag and status for the qualifier message. * Used by imap_copy_message for TRYCREATE */ char *imap_get_qualifier(char *buf) { char *s = buf; /* skip tag */ s = imap_next_word(s); /* skip OK/NO/BAD response */ s = imap_next_word(s); return s; } /** * imap_next_word - Find where the next IMAP word begins * @param s Command string to process * @retval ptr Next IMAP word */ char *imap_next_word(char *s) { int quoted = 0; while (*s) { if (*s == '\\') { s++; if (*s) s++; continue; } if (*s == '\"') quoted = quoted ? 0 : 1; if (!quoted && ISSPACE(*s)) break; s++; } SKIPWS(s); return s; } /** * imap_qualify_path - Make an absolute IMAP folder target * @param dest Buffer for the result * @param len Length of buffer * @param mx Imap mailbox * @param path Path relative to the mailbox * * given ImapMbox and relative path. */ void imap_qualify_path(char *dest, size_t len, struct ImapMbox *mx, char *path) { struct Url url; mutt_account_tourl(&mx->account, &url); url.path = path; url_tostring(&url, dest, len, 0); } /** * imap_quote_string - quote string according to IMAP rules * @param dest Buffer for the result * @param dlen Length of the buffer * @param src String to be quoted * * Surround string with quotes, escape " and \ with backslash */ void imap_quote_string(char *dest, size_t dlen, const char *src, bool quote_backtick) { const char *quote = "`\"\\"; if (!quote_backtick) quote++; char *pt = dest; const char *s = src; *pt++ = '"'; /* save room for trailing quote-char */ dlen -= 2; for (; *s && dlen; s++) { if (strchr(quote, *s)) { dlen -= 2; if (dlen == 0) break; *pt++ = '\\'; *pt++ = *s; } else { *pt++ = *s; dlen--; } } *pt++ = '"'; *pt = '\0'; } /** * imap_unquote_string - equally stupid unquoting routine * @param s String to be unquoted */ void imap_unquote_string(char *s) { char *d = s; if (*s == '\"') s++; else return; while (*s) { if (*s == '\"') { *d = '\0'; return; } if (*s == '\\') { s++; } if (*s) { *d = *s; d++; s++; } } *d = '\0'; } /** * imap_munge_mbox_name - Quote awkward characters in a mailbox name * @param idata Server data * @param dest Buffer to store safe mailbox name * @param dlen Length of buffer * @param src Mailbox name */ void imap_munge_mbox_name(struct ImapData *idata, char *dest, size_t dlen, const char *src) { char *buf = mutt_str_strdup(src); imap_utf_encode(idata, &buf); imap_quote_string(dest, dlen, buf, false); FREE(&buf); } /** * imap_unmunge_mbox_name - Remove quoting from a mailbox name * @param idata Server data * @param s Mailbox name * * The string will be altered in-place. */ void imap_unmunge_mbox_name(struct ImapData *idata, char *s) { imap_unquote_string(s); char *buf = mutt_str_strdup(s); if (buf) { imap_utf_decode(idata, &buf); strncpy(s, buf, strlen(s)); } FREE(&buf); } /** * imap_keepalive - poll the current folder to keep the connection alive */ void imap_keepalive(void) { struct Connection *conn = NULL; struct ImapData *idata = NULL; time_t now = time(NULL); TAILQ_FOREACH(conn, mutt_socket_head(), entries) { if (conn->account.type == MUTT_ACCT_TYPE_IMAP) { idata = conn->data; if (idata->state >= IMAP_AUTHENTICATED && now >= idata->lastread + ImapKeepalive) { imap_check(idata, 1); } } } } /** * imap_wait_keepalive - Wait for a process to change state * @param pid Process ID to listen to * @retval num 'wstatus' from waitpid() */ int imap_wait_keepalive(pid_t pid) { struct sigaction oldalrm; struct sigaction act; sigset_t oldmask; int rc; bool imap_passive = ImapPassive; ImapPassive = true; OptKeepQuiet = true; sigprocmask(SIG_SETMASK, NULL, &oldmask); sigemptyset(&act.sa_mask); act.sa_handler = mutt_sig_empty_handler; #ifdef SA_INTERRUPT act.sa_flags = SA_INTERRUPT; #else act.sa_flags = 0; #endif sigaction(SIGALRM, &act, &oldalrm); alarm(ImapKeepalive); while (waitpid(pid, &rc, 0) < 0 && errno == EINTR) { alarm(0); /* cancel a possibly pending alarm */ imap_keepalive(); alarm(ImapKeepalive); } alarm(0); /* cancel a possibly pending alarm */ sigaction(SIGALRM, &oldalrm, NULL); sigprocmask(SIG_SETMASK, &oldmask, NULL); OptKeepQuiet = false; if (!imap_passive) ImapPassive = false; return rc; } /** * imap_allow_reopen - Allow re-opening a folder upon expunge * @param ctx Context */ void imap_allow_reopen(struct Context *ctx) { struct ImapData *idata = NULL; if (!ctx || !ctx->data || ctx->magic != MUTT_IMAP) return; idata = ctx->data; if (idata->ctx == ctx) idata->reopen |= IMAP_REOPEN_ALLOW; } /** * imap_disallow_reopen - Disallow re-opening a folder upon expunge * @param ctx Context */ void imap_disallow_reopen(struct Context *ctx) { struct ImapData *idata = NULL; if (!ctx || !ctx->data || ctx->magic != MUTT_IMAP) return; idata = ctx->data; if (idata->ctx == ctx) idata->reopen &= ~IMAP_REOPEN_ALLOW; } /** * imap_account_match - Compare two Accounts * @param a1 First Account * @param a2 Second Account * @retval true Accounts match */ int imap_account_match(const struct Account *a1, const struct Account *a2) { struct ImapData *a1_idata = imap_conn_find(a1, MUTT_IMAP_CONN_NONEW); struct ImapData *a2_idata = imap_conn_find(a2, MUTT_IMAP_CONN_NONEW); const struct Account *a1_canon = a1_idata == NULL ? a1 : &a1_idata->conn->account; const struct Account *a2_canon = a2_idata == NULL ? a2 : &a2_idata->conn->account; return mutt_account_match(a1_canon, a2_canon); }
./CrossVul/dataset_final_sorted/CWE-77/c/good_251_4
crossvul-cpp_data_bad_838_0
/* HIDP implementation for Linux Bluetooth stack (BlueZ). Copyright (C) 2003-2004 Marcel Holtmann <marcel@holtmann.org> 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/export.h> #include <linux/file.h> #include "hidp.h" static struct bt_sock_list hidp_sk_list = { .lock = __RW_LOCK_UNLOCKED(hidp_sk_list.lock) }; static int hidp_sock_release(struct socket *sock) { struct sock *sk = sock->sk; BT_DBG("sock %p sk %p", sock, sk); if (!sk) return 0; bt_sock_unlink(&hidp_sk_list, sk); sock_orphan(sk); sock_put(sk); return 0; } static int do_hidp_sock_ioctl(struct socket *sock, unsigned int cmd, void __user *argp) { struct hidp_connadd_req ca; struct hidp_conndel_req cd; struct hidp_connlist_req cl; struct hidp_conninfo ci; struct socket *csock; struct socket *isock; int err; BT_DBG("cmd %x arg %p", cmd, argp); switch (cmd) { case HIDPCONNADD: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&ca, argp, sizeof(ca))) return -EFAULT; csock = sockfd_lookup(ca.ctrl_sock, &err); if (!csock) return err; isock = sockfd_lookup(ca.intr_sock, &err); if (!isock) { sockfd_put(csock); return err; } err = hidp_connection_add(&ca, csock, isock); if (!err && copy_to_user(argp, &ca, sizeof(ca))) err = -EFAULT; sockfd_put(csock); sockfd_put(isock); return err; case HIDPCONNDEL: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&cd, argp, sizeof(cd))) return -EFAULT; return hidp_connection_del(&cd); case HIDPGETCONNLIST: if (copy_from_user(&cl, argp, sizeof(cl))) return -EFAULT; if (cl.cnum <= 0) return -EINVAL; err = hidp_get_connlist(&cl); if (!err && copy_to_user(argp, &cl, sizeof(cl))) return -EFAULT; return err; case HIDPGETCONNINFO: if (copy_from_user(&ci, argp, sizeof(ci))) return -EFAULT; err = hidp_get_conninfo(&ci); if (!err && copy_to_user(argp, &ci, sizeof(ci))) return -EFAULT; return err; } return -EINVAL; } static int hidp_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { return do_hidp_sock_ioctl(sock, cmd, (void __user *)arg); } #ifdef CONFIG_COMPAT struct compat_hidp_connadd_req { int ctrl_sock; /* Connected control socket */ int intr_sock; /* Connected interrupt socket */ __u16 parser; __u16 rd_size; compat_uptr_t rd_data; __u8 country; __u8 subclass; __u16 vendor; __u16 product; __u16 version; __u32 flags; __u32 idle_to; char name[128]; }; static int hidp_sock_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { void __user *argp = compat_ptr(arg); int err; if (cmd == HIDPGETCONNLIST) { struct hidp_connlist_req cl; u32 __user *p = argp; u32 uci; if (get_user(cl.cnum, p) || get_user(uci, p + 1)) return -EFAULT; cl.ci = compat_ptr(uci); if (cl.cnum <= 0) return -EINVAL; err = hidp_get_connlist(&cl); if (!err && put_user(cl.cnum, p)) err = -EFAULT; return err; } else if (cmd == HIDPCONNADD) { struct compat_hidp_connadd_req ca32; struct hidp_connadd_req ca; struct socket *csock; struct socket *isock; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&ca32, (void __user *) arg, sizeof(ca32))) return -EFAULT; ca.ctrl_sock = ca32.ctrl_sock; ca.intr_sock = ca32.intr_sock; ca.parser = ca32.parser; ca.rd_size = ca32.rd_size; ca.rd_data = compat_ptr(ca32.rd_data); ca.country = ca32.country; ca.subclass = ca32.subclass; ca.vendor = ca32.vendor; ca.product = ca32.product; ca.version = ca32.version; ca.flags = ca32.flags; ca.idle_to = ca32.idle_to; memcpy(ca.name, ca32.name, 128); csock = sockfd_lookup(ca.ctrl_sock, &err); if (!csock) return err; isock = sockfd_lookup(ca.intr_sock, &err); if (!isock) { sockfd_put(csock); return err; } err = hidp_connection_add(&ca, csock, isock); if (!err && copy_to_user(argp, &ca32, sizeof(ca32))) err = -EFAULT; sockfd_put(csock); sockfd_put(isock); return err; } return hidp_sock_ioctl(sock, cmd, arg); } #endif static const struct proto_ops hidp_sock_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .release = hidp_sock_release, .ioctl = hidp_sock_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = hidp_sock_compat_ioctl, #endif .bind = sock_no_bind, .getname = sock_no_getname, .sendmsg = sock_no_sendmsg, .recvmsg = sock_no_recvmsg, .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 hidp_proto = { .name = "HIDP", .owner = THIS_MODULE, .obj_size = sizeof(struct bt_sock) }; static int hidp_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, &hidp_proto, kern); if (!sk) return -ENOMEM; sock_init_data(sock, sk); sock->ops = &hidp_sock_ops; sock->state = SS_UNCONNECTED; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = protocol; sk->sk_state = BT_OPEN; bt_sock_link(&hidp_sk_list, sk); return 0; } static const struct net_proto_family hidp_sock_family_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .create = hidp_sock_create }; int __init hidp_init_sockets(void) { int err; err = proto_register(&hidp_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_HIDP, &hidp_sock_family_ops); if (err < 0) { BT_ERR("Can't register HIDP socket"); goto error; } err = bt_procfs_init(&init_net, "hidp", &hidp_sk_list, NULL); if (err < 0) { BT_ERR("Failed to create HIDP proc file"); bt_sock_unregister(BTPROTO_HIDP); goto error; } BT_INFO("HIDP socket layer initialized"); return 0; error: proto_unregister(&hidp_proto); return err; } void __exit hidp_cleanup_sockets(void) { bt_procfs_cleanup(&init_net, "hidp"); bt_sock_unregister(BTPROTO_HIDP); proto_unregister(&hidp_proto); }
./CrossVul/dataset_final_sorted/CWE-77/c/bad_838_0
crossvul-cpp_data_bad_251_0
/** * @file * IMAP login authentication method * * @authors * Copyright (C) 1999-2001,2005,2009 Brendan Cully <brendan@kublai.com> * * @copyright * 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, see <http://www.gnu.org/licenses/>. */ /** * @page imap_auth_login IMAP login authentication method * * IMAP login authentication method */ #include "config.h" #include <stdio.h> #include "imap_private.h" #include "mutt/mutt.h" #include "conn/conn.h" #include "mutt.h" #include "auth.h" #include "globals.h" #include "mutt_account.h" #include "mutt_logging.h" #include "mutt_socket.h" #include "options.h" #include "protos.h" /** * imap_auth_login - Plain LOGIN support * @param idata Server data * @param method Name of this authentication method * @retval enum Result, e.g. #IMAP_AUTH_SUCCESS */ enum ImapAuthRes imap_auth_login(struct ImapData *idata, const char *method) { char q_user[SHORT_STRING], q_pass[SHORT_STRING]; char buf[STRING]; int rc; if (mutt_bit_isset(idata->capabilities, LOGINDISABLED)) { mutt_message(_("LOGIN disabled on this server.")); return IMAP_AUTH_UNAVAIL; } if (mutt_account_getuser(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; if (mutt_account_getpass(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; mutt_message(_("Logging in...")); imap_quote_string(q_user, sizeof(q_user), idata->conn->account.user); imap_quote_string(q_pass, sizeof(q_pass), idata->conn->account.pass); /* don't print the password unless we're at the ungodly debugging level * of 5 or higher */ if (DebugLevel < IMAP_LOG_PASS) mutt_debug(2, "Sending LOGIN command for %s...\n", idata->conn->account.user); snprintf(buf, sizeof(buf), "LOGIN %s %s", q_user, q_pass); rc = imap_exec(idata, buf, IMAP_CMD_FAIL_OK | IMAP_CMD_PASS); if (!rc) { mutt_clear_error(); /* clear "Logging in...". fixes #3524 */ return IMAP_AUTH_SUCCESS; } mutt_error(_("Login failed.")); return IMAP_AUTH_FAILURE; }
./CrossVul/dataset_final_sorted/CWE-77/c/bad_251_0
crossvul-cpp_data_bad_1866_1
/* vi: set sw=4 ts=4: * * picocom.c * * simple dumb-terminal program. Helps you manually configure and test * stuff like modems, devices w. serial ports etc. * * by Nick Patavalis (npat@efault.net) * * 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 <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <assert.h> #include <stdarg.h> #include <signal.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <limits.h> #ifdef USE_FLOCK #include <sys/file.h> #endif #ifdef LINENOISE #include <dirent.h> #include <libgen.h> #endif #define _GNU_SOURCE #include <getopt.h> #include "term.h" #ifdef LINENOISE #include "linenoise-1.0/linenoise.h" #endif /**********************************************************************/ /* parity modes names */ const char *parity_str[] = { [P_NONE] = "none", [P_EVEN] = "even", [P_ODD] = "odd", [P_MARK] = "mark", [P_SPACE] = "space", }; /* flow control modes names */ const char *flow_str[] = { [FC_NONE] = "none", [FC_RTSCTS] = "RTS/CTS", [FC_XONXOFF] = "xon/xoff", [FC_OTHER] = "other", }; /**********************************************************************/ #define KEY_EXIT '\x18' /* C-x: exit picocom */ #define KEY_QUIT '\x11' /* C-q: exit picocom without reseting port */ #define KEY_PULSE '\x10' /* C-p: pulse DTR */ #define KEY_TOGGLE '\x14' /* C-t: toggle DTR */ #define KEY_BAUD_UP '\x15' /* C-u: increase baudrate (up) */ #define KEY_BAUD_DN '\x04' /* C-d: decrase baudrate (down) */ #define KEY_FLOW '\x06' /* C-f: change flowcntrl mode */ #define KEY_PARITY '\x19' /* C-y: change parity mode */ #define KEY_BITS '\x02' /* C-b: change number of databits */ #define KEY_LECHO '\x03' /* C-c: toggle local echo */ #define KEY_STATUS '\x16' /* C-v: show program option */ #define KEY_SEND '\x13' /* C-s: send file */ #define KEY_RECEIVE '\x12' /* C-r: receive file */ #define KEY_BREAK '\x1c' /* C-\: break */ /**********************************************************************/ /* implemented caracter mappings */ #define M_CRLF (1 << 0) /* map CR --> LF */ #define M_CRCRLF (1 << 1) /* map CR --> CR + LF */ #define M_IGNCR (1 << 2) /* map CR --> <nothing> */ #define M_LFCR (1 << 3) /* map LF --> CR */ #define M_LFCRLF (1 << 4) /* map LF --> CR + LF */ #define M_IGNLF (1 << 5) /* map LF --> <nothing> */ #define M_DELBS (1 << 6) /* map DEL --> BS */ #define M_BSDEL (1 << 7) /* map BS --> DEL */ #define M_NFLAGS 8 /* default character mappings */ #define M_I_DFL 0 #define M_O_DFL 0 #define M_E_DFL (M_DELBS | M_CRCRLF) /* character mapping names */ struct map_names_s { char *name; int flag; } map_names[] = { { "crlf", M_CRLF }, { "crcrlf", M_CRCRLF }, { "igncr", M_IGNCR }, { "lfcr", M_LFCR }, { "lfcrlf", M_LFCRLF }, { "ignlf", M_IGNLF }, { "delbs", M_DELBS }, { "bsdel", M_BSDEL }, /* Sentinel */ { NULL, 0 } }; int parse_map (char *s) { char *m, *t; int f, flags, i; flags = 0; while ( (t = strtok(s, ", \t")) ) { for (i=0; (m = map_names[i].name); i++) { if ( ! strcmp(t, m) ) { f = map_names[i].flag; break; } } if ( m ) flags |= f; else { flags = -1; break; } s = NULL; } return flags; } void print_map (int flags) { int i; for (i = 0; i < M_NFLAGS; i++) if ( flags & (1 << i) ) printf("%s,", map_names[i].name); printf("\n"); } /**********************************************************************/ struct { char port[128]; int baud; enum flowcntrl_e flow; enum parity_e parity; int databits; int lecho; int noinit; int noreset; #if defined (UUCP_LOCK_DIR) || defined (USE_FLOCK) int nolock; #endif unsigned char escape; char send_cmd[128]; char receive_cmd[128]; int imap; int omap; int emap; } opts = { .port = "", .baud = 9600, .flow = FC_NONE, .parity = P_NONE, .databits = 8, .lecho = 0, .noinit = 0, .noreset = 0, #if defined (UUCP_LOCK_DIR) || defined (USE_FLOCK) .nolock = 0, #endif .escape = '\x01', .send_cmd = "sz -vv", .receive_cmd = "rz -vv", .imap = M_I_DFL, .omap = M_O_DFL, .emap = M_E_DFL }; int sig_exit = 0; #define STO STDOUT_FILENO #define STI STDIN_FILENO int tty_fd; #ifndef TTY_Q_SZ #define TTY_Q_SZ 256 #endif struct tty_q { int len; unsigned char buff[TTY_Q_SZ]; } tty_q; int tty_write_sz; #define TTY_WRITE_SZ_DIV 10 #define TTY_WRITE_SZ_MIN 8 #define set_tty_write_sz(baud) \ do { \ tty_write_sz = (baud) / TTY_WRITE_SZ_DIV; \ if ( tty_write_sz < TTY_WRITE_SZ_MIN ) \ tty_write_sz = TTY_WRITE_SZ_MIN; \ } while (0) /**********************************************************************/ #ifdef UUCP_LOCK_DIR /* use HDB UUCP locks .. see * <http://www.faqs.org/faqs/uucp-internals> for details */ char lockname[_POSIX_PATH_MAX] = ""; int uucp_lockname(const char *dir, const char *file) { char *p, *cp; struct stat sb; if ( ! dir || *dir == '\0' || stat(dir, &sb) != 0 ) return -1; /* cut-off initial "/dev/" from file-name */ p = strchr(file + 1, '/'); p = p ? p + 1 : (char *)file; /* replace '/'s with '_'s in what remains (after making a copy) */ p = cp = strdup(p); do { if ( *p == '/' ) *p = '_'; } while(*p++); /* build lockname */ snprintf(lockname, sizeof(lockname), "%s/LCK..%s", dir, cp); /* destroy the copy */ free(cp); return 0; } int uucp_lock(void) { int r, fd, pid; char buf[16]; mode_t m; if ( lockname[0] == '\0' ) return 0; fd = open(lockname, O_RDONLY); if ( fd >= 0 ) { r = read(fd, buf, sizeof(buf)); close(fd); /* if r == 4, lock file is binary (old-style) */ pid = (r == 4) ? *(int *)buf : strtol(buf, NULL, 10); if ( pid > 0 && kill((pid_t)pid, 0) < 0 && errno == ESRCH ) { /* stale lock file */ printf("Removing stale lock: %s\n", lockname); sleep(1); unlink(lockname); } else { lockname[0] = '\0'; errno = EEXIST; return -1; } } /* lock it */ m = umask(022); fd = open(lockname, O_WRONLY|O_CREAT|O_EXCL, 0666); if ( fd < 0 ) { lockname[0] = '\0'; return -1; } umask(m); snprintf(buf, sizeof(buf), "%04d\n", getpid()); write(fd, buf, strlen(buf)); close(fd); return 0; } int uucp_unlock(void) { if ( lockname[0] ) unlink(lockname); return 0; } #endif /* of UUCP_LOCK_DIR */ /**********************************************************************/ ssize_t writen_ni(int fd, const void *buff, size_t n) { size_t nl; ssize_t nw; const char *p; p = buff; nl = n; while (nl > 0) { do { nw = write(fd, p, nl); } while ( nw < 0 && errno == EINTR ); if ( nw <= 0 ) break; nl -= nw; p += nw; } return n - nl; } int fd_printf (int fd, const char *format, ...) { char buf[256]; va_list args; int len; va_start(args, format); len = vsnprintf(buf, sizeof(buf), format, args); buf[sizeof(buf) - 1] = '\0'; va_end(args); return writen_ni(fd, buf, len); } void fatal (const char *format, ...) { char *s, buf[256]; va_list args; int len; term_reset(STO); term_reset(STI); va_start(args, format); len = vsnprintf(buf, sizeof(buf), format, args); buf[sizeof(buf) - 1] = '\0'; va_end(args); s = "\r\nFATAL: "; writen_ni(STO, s, strlen(s)); writen_ni(STO, buf, len); s = "\r\n"; writen_ni(STO, s, strlen(s)); /* wait a bit for output to drain */ sleep(1); #ifdef UUCP_LOCK_DIR uucp_unlock(); #endif exit(EXIT_FAILURE); } /**********************************************************************/ #ifndef LINENOISE int cput(int fd, char c) { return write(fd, &c, 1); } int fd_readline (int fdi, int fdo, char *b, int bsz) { int r; unsigned char c; unsigned char *bp, *bpe; bp = (unsigned char *)b; bpe = (unsigned char *)b + bsz - 1; while (1) { r = read(fdi, &c, 1); if ( r <= 0 ) { r = -1; goto out; } switch (c) { case '\b': case '\x7f': if ( bp > (unsigned char *)b ) { bp--; cput(fdo, '\b'); cput(fdo, ' '); cput(fdo, '\b'); } else { cput(fdo, '\x07'); } break; case '\x03': /* CTRL-c */ r = -1; errno = EINTR; goto out; case '\r': *bp = '\0'; r = bp - (unsigned char *)b; goto out; default: if ( bp < bpe ) { *bp++ = c; cput(fdo, c); } else { cput(fdo, '\x07'); } break; } } out: return r; } char * read_filename (void) { char fname[_POSIX_PATH_MAX]; int r; fd_printf(STO, "\r\n*** file: "); r = fd_readline(STI, STO, fname, sizeof(fname)); fd_printf(STO, "\r\n"); if ( r < 0 ) return NULL; else return strdup(fname); } #else /* LINENOISE defined */ void file_completion_cb (const char *buf, linenoiseCompletions *lc) { DIR *dirp; struct dirent *dp; char *basec, *basen, *dirc, *dirn; int baselen, dirlen; char *fullpath; struct stat filestat; basec = strdup(buf); dirc = strdup(buf); dirn = dirname(dirc); dirlen = strlen(dirn); basen = basename(basec); baselen = strlen(basen); dirp = opendir(dirn); if (dirp) { while ((dp = readdir(dirp)) != NULL) { if (strncmp(basen, dp->d_name, baselen) == 0) { /* add 2 extra bytes for possible / in middle & at end */ fullpath = (char *) malloc(strlen(dp->d_name) + dirlen + 3); strcpy(fullpath, dirn); if (fullpath[dirlen-1] != '/') strcat(fullpath, "/"); strcat(fullpath, dp->d_name); if (stat(fullpath, &filestat) == 0) { if (S_ISDIR(filestat.st_mode)) { strcat(fullpath, "/"); } linenoiseAddCompletion(lc,fullpath); } free(fullpath); } } closedir(dirp); } free(basec); free(dirc); } static char *send_receive_history_file_path = NULL; void init_send_receive_history (void) { char *home_directory; home_directory = getenv("HOME"); if (home_directory) { send_receive_history_file_path = malloc(strlen(home_directory) + 2 + strlen(SEND_RECEIVE_HISTFILE)); strcpy(send_receive_history_file_path, home_directory); if (home_directory[strlen(home_directory)-1] != '/') { strcat(send_receive_history_file_path, "/"); } strcat(send_receive_history_file_path, SEND_RECEIVE_HISTFILE); linenoiseHistoryLoad(send_receive_history_file_path); } } void cleanup_send_receive_history (void) { if (send_receive_history_file_path) free(send_receive_history_file_path); } void add_send_receive_history (char *fname) { linenoiseHistoryAdd(fname); if (send_receive_history_file_path) linenoiseHistorySave(send_receive_history_file_path); } char * read_filename (void) { char *fname; linenoiseSetCompletionCallback(file_completion_cb); printf("\r\n"); fname = linenoise("*** file: "); printf("\r\n"); linenoiseSetCompletionCallback(NULL); if (fname != NULL) add_send_receive_history(fname); return fname; } #endif /* of ifndef LINENOISE */ /**********************************************************************/ /* maximum number of chars that can replace a single characted due to mapping */ #define M_MAXMAP 4 int do_map (char *b, int map, char c) { int n; switch (c) { case '\x7f': /* DEL mapings */ if ( map & M_DELBS ) { b[0] = '\x08'; n = 1; } else { b[0] = c; n = 1; } break; case '\x08': /* BS mapings */ if ( map & M_BSDEL ) { b[0] = '\x7f'; n = 1; } else { b[0] = c; n = 1; } break; case '\x0d': /* CR mappings */ if ( map & M_CRLF ) { b[0] = '\x0a'; n = 1; } else if ( map & M_CRCRLF ) { b[0] = '\x0d'; b[1] = '\x0a'; n = 2; } else if ( map & M_IGNCR ) { n = 0; } else { b[0] = c; n = 1; } break; case '\x0a': /* LF mappings */ if ( map & M_LFCR ) { b[0] = '\x0d'; n = 1; } else if ( map & M_LFCRLF ) { b[0] = '\x0d'; b[1] = '\x0a'; n = 2; } else if ( map & M_IGNLF ) { n = 0; } else { b[0] = c; n = 1; } break; default: b[0] = c; n = 1; break; } return n; } void map_and_write (int fd, int map, char c) { char b[M_MAXMAP]; int n; n = do_map(b, map, c); if ( n ) if ( writen_ni(fd, b, n) < n ) fatal("write to stdout failed: %s", strerror(errno)); } /**********************************************************************/ int baud_up (int baud) { return term_baud_up(baud); } int baud_down (int baud) { int nb; nb = term_baud_down(baud); if (nb == 0) nb = baud; return nb; } int flow_next (int flow) { switch(flow) { case FC_NONE: flow = FC_RTSCTS; break; case FC_RTSCTS: flow = FC_XONXOFF; break; case FC_XONXOFF: flow = FC_NONE; break; default: flow = FC_NONE; break; } return flow; } int parity_next (int parity) { switch(parity) { case P_NONE: parity = P_EVEN; break; case P_EVEN: parity = P_ODD; break; case P_ODD: parity = P_NONE; break; default: parity = P_NONE; break; } return parity; } int bits_next (int bits) { bits++; if (bits > 8) bits = 5; return bits; } void show_status (int dtr_up) { int baud, bits; enum flowcntrl_e flow; enum parity_e parity; term_refresh(tty_fd); baud = term_get_baudrate(tty_fd, NULL); flow = term_get_flowcntrl(tty_fd); parity = term_get_parity(tty_fd); bits = term_get_databits(tty_fd); fd_printf(STO, "\r\n"); if ( baud != opts.baud ) { fd_printf(STO, "*** baud: %d (%d)\r\n", opts.baud, baud); } else { fd_printf(STO, "*** baud: %d\r\n", opts.baud); } if ( flow != opts.flow ) { fd_printf(STO, "*** flow: %s (%s)\r\n", flow_str[opts.flow], flow_str[flow]); } else { fd_printf(STO, "*** flow: %s\r\n", flow_str[opts.flow]); } if ( parity != opts.parity ) { fd_printf(STO, "*** parity: %s (%s)\r\n", parity_str[opts.parity], parity_str[parity]); } else { fd_printf(STO, "*** parity: %s\r\n", parity_str[opts.parity]); } if ( bits != opts.databits ) { fd_printf(STO, "*** databits: %d (%d)\r\n", opts.databits, bits); } else { fd_printf(STO, "*** databits: %d\r\n", opts.databits); } fd_printf(STO, "*** dtr: %s\r\n", dtr_up ? "up" : "down"); } /**********************************************************************/ void establish_child_signal_handlers (void) { struct sigaction dfl_action; /* Set up the structure to specify the default action. */ dfl_action.sa_handler = SIG_DFL; sigemptyset (&dfl_action.sa_mask); dfl_action.sa_flags = 0; sigaction (SIGINT, &dfl_action, NULL); sigaction (SIGTERM, &dfl_action, NULL); } #define EXEC "exec " int run_cmd(int fd, ...) { pid_t pid; sigset_t sigm, sigm_old; /* block signals, let child establish its own handlers */ sigemptyset(&sigm); sigaddset(&sigm, SIGTERM); sigprocmask(SIG_BLOCK, &sigm, &sigm_old); pid = fork(); if ( pid < 0 ) { sigprocmask(SIG_SETMASK, &sigm_old, NULL); fd_printf(STO, "*** cannot fork: %s ***\r\n", strerror(errno)); return -1; } else if ( pid ) { /* father: picocom */ int status, r; /* reset the mask */ sigprocmask(SIG_SETMASK, &sigm_old, NULL); /* wait for child to finish */ do { r = waitpid(pid, &status, 0); } while ( r < 0 && errno == EINTR ); /* reset terminal (back to raw mode) */ term_apply(STI); /* check and report child return status */ if ( WIFEXITED(status) ) { fd_printf(STO, "\r\n*** exit status: %d ***\r\n", WEXITSTATUS(status)); return WEXITSTATUS(status); } else if ( WIFSIGNALED(status) ) { fd_printf(STO, "\r\n*** killed by signal: %d ***\r\n", WTERMSIG(status)); return -1; } else { fd_printf(STO, "\r\n*** abnormal termination: 0x%x ***\r\n", r); return -1; } } else { /* child: external program */ long fl; char cmd[512]; /* unmanage terminal, and reset it to canonical mode */ term_remove(STI); /* unmanage serial port fd, without reset */ term_erase(fd); /* set serial port fd to blocking mode */ fl = fcntl(fd, F_GETFL); fl &= ~O_NONBLOCK; fcntl(fd, F_SETFL, fl); /* connect stdin and stdout to serial port */ close(STI); close(STO); dup2(fd, STI); dup2(fd, STO); { /* build command-line */ char *c, *ce; const char *s; int n; va_list vls; strcpy(cmd, EXEC); c = &cmd[sizeof(EXEC)- 1]; ce = cmd + sizeof(cmd) - 1; va_start(vls, fd); while ( (s = va_arg(vls, const char *)) ) { n = strlen(s); if ( c + n + 1 >= ce ) break; memcpy(c, s, n); c += n; *c++ = ' '; } va_end(vls); *c = '\0'; } /* run extenral command */ fd_printf(STDERR_FILENO, "%s\n", &cmd[sizeof(EXEC) - 1]); establish_child_signal_handlers(); sigprocmask(SIG_SETMASK, &sigm_old, NULL); execl("/bin/sh", "sh", "-c", cmd, NULL); exit(42); } } #undef EXEC /**********************************************************************/ /* Process command key. Returns non-zero if command results in picocom exit, zero otherwise. */ int do_command (unsigned char c) { static int dtr_up = 0; int newbaud, newflow, newparity, newbits; const char *xfr_cmd; char *fname; int r; switch (c) { case KEY_EXIT: return 1; case KEY_QUIT: term_set_hupcl(tty_fd, 0); term_flush(tty_fd); term_apply(tty_fd); term_erase(tty_fd); return 1; case KEY_STATUS: show_status(dtr_up); break; case KEY_PULSE: fd_printf(STO, "\r\n*** pulse DTR ***\r\n"); if ( term_pulse_dtr(tty_fd) < 0 ) fd_printf(STO, "*** FAILED\r\n"); break; case KEY_TOGGLE: if ( dtr_up ) r = term_lower_dtr(tty_fd); else r = term_raise_dtr(tty_fd); if ( r >= 0 ) dtr_up = ! dtr_up; fd_printf(STO, "\r\n*** DTR: %s ***\r\n", dtr_up ? "up" : "down"); break; case KEY_BAUD_UP: case KEY_BAUD_DN: if (c == KEY_BAUD_UP) opts.baud = baud_up(opts.baud); else opts.baud = baud_down(opts.baud); term_set_baudrate(tty_fd, opts.baud); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newbaud = term_get_baudrate(tty_fd, NULL); if ( opts.baud != newbaud ) { fd_printf(STO, "\r\n*** baud: %d (%d) ***\r\n", opts.baud, newbaud); } else { fd_printf(STO, "\r\n*** baud: %d ***\r\n", opts.baud); } set_tty_write_sz(newbaud); break; case KEY_FLOW: opts.flow = flow_next(opts.flow); term_set_flowcntrl(tty_fd, opts.flow); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newflow = term_get_flowcntrl(tty_fd); if ( opts.flow != newflow ) { fd_printf(STO, "\r\n*** flow: %s (%s) ***\r\n", flow_str[opts.flow], flow_str[newflow]); } else { fd_printf(STO, "\r\n*** flow: %s ***\r\n", flow_str[opts.flow]); } break; case KEY_PARITY: opts.parity = parity_next(opts.parity); term_set_parity(tty_fd, opts.parity); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newparity = term_get_parity(tty_fd); if (opts.parity != newparity ) { fd_printf(STO, "\r\n*** parity: %s (%s) ***\r\n", parity_str[opts.parity], parity_str[newparity]); } else { fd_printf(STO, "\r\n*** parity: %s ***\r\n", parity_str[opts.parity]); } break; case KEY_BITS: opts.databits = bits_next(opts.databits); term_set_databits(tty_fd, opts.databits); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newbits = term_get_databits(tty_fd); if (opts.databits != newbits ) { fd_printf(STO, "\r\n*** databits: %d (%d) ***\r\n", opts.databits, newbits); } else { fd_printf(STO, "\r\n*** databits: %d ***\r\n", opts.databits); } break; case KEY_LECHO: opts.lecho = ! opts.lecho; fd_printf(STO, "\r\n*** local echo: %s ***\r\n", opts.lecho ? "yes" : "no"); break; case KEY_SEND: case KEY_RECEIVE: xfr_cmd = (c == KEY_SEND) ? opts.send_cmd : opts.receive_cmd; if ( xfr_cmd[0] == '\0' ) { fd_printf(STO, "\r\n*** command disabled ***\r\n"); break; } fname = read_filename(); if (fname == NULL) { fd_printf(STO, "*** cannot read filename ***\r\n"); break; } run_cmd(tty_fd, xfr_cmd, fname, NULL); free(fname); break; case KEY_BREAK: term_break(tty_fd); fd_printf(STO, "\r\n*** break sent ***\r\n"); break; default: break; } return 0; } /**********************************************************************/ void loop(void) { enum { ST_COMMAND, ST_TRANSPARENT } state; fd_set rdset, wrset; int r, n; unsigned char c; tty_q.len = 0; state = ST_TRANSPARENT; while ( ! sig_exit ) { FD_ZERO(&rdset); FD_ZERO(&wrset); FD_SET(STI, &rdset); FD_SET(tty_fd, &rdset); if ( tty_q.len ) FD_SET(tty_fd, &wrset); r = select(tty_fd + 1, &rdset, &wrset, NULL, NULL); if ( r < 0 ) { if ( errno == EINTR ) continue; else fatal("select failed: %d : %s", errno, strerror(errno)); } if ( FD_ISSET(STI, &rdset) ) { /* read from terminal */ do { n = read(STI, &c, 1); } while (n < 0 && errno == EINTR); if (n == 0) { fatal("stdin closed"); } else if (n < 0) { /* is this really necessary? better safe than sory! */ if ( errno != EAGAIN && errno != EWOULDBLOCK ) fatal("read from stdin failed: %s", strerror(errno)); else goto skip_proc_STI; } switch (state) { case ST_COMMAND: if ( c == opts.escape ) { /* pass the escape character down */ if (tty_q.len + M_MAXMAP <= TTY_Q_SZ) { n = do_map((char *)tty_q.buff + tty_q.len, opts.omap, c); tty_q.len += n; if ( opts.lecho ) map_and_write(STO, opts.emap, c); } else { fd_printf(STO, "\x07"); } } else { /* process command key */ if ( do_command(c) ) /* picocom exit */ return; } state = ST_TRANSPARENT; break; case ST_TRANSPARENT: if ( c == opts.escape ) { state = ST_COMMAND; } else { if (tty_q.len + M_MAXMAP <= TTY_Q_SZ) { n = do_map((char *)tty_q.buff + tty_q.len, opts.omap, c); tty_q.len += n; if ( opts.lecho ) map_and_write(STO, opts.emap, c); } else fd_printf(STO, "\x07"); } break; default: assert(0); break; } } skip_proc_STI: if ( FD_ISSET(tty_fd, &rdset) ) { /* read from port */ do { n = read(tty_fd, &c, 1); } while (n < 0 && errno == EINTR); if (n == 0) { fatal("term closed"); } else if ( n < 0 ) { if ( errno != EAGAIN && errno != EWOULDBLOCK ) fatal("read from term failed: %s", strerror(errno)); } else { map_and_write(STO, opts.imap, c); } } if ( FD_ISSET(tty_fd, &wrset) ) { /* write to port */ int sz; sz = (tty_q.len < tty_write_sz) ? tty_q.len : tty_write_sz; do { n = write(tty_fd, tty_q.buff, sz); } while ( n < 0 && errno == EINTR ); if ( n <= 0 ) fatal("write to term failed: %s", strerror(errno)); memmove(tty_q.buff, tty_q.buff + n, tty_q.len - n); tty_q.len -= n; } } } /**********************************************************************/ void deadly_handler(int signum) { if ( ! sig_exit ) { sig_exit = 1; kill(0, SIGTERM); } } void establish_signal_handlers (void) { struct sigaction exit_action, ign_action; /* Set up the structure to specify the exit action. */ exit_action.sa_handler = deadly_handler; sigemptyset (&exit_action.sa_mask); exit_action.sa_flags = 0; /* Set up the structure to specify the ignore action. */ ign_action.sa_handler = SIG_IGN; sigemptyset (&ign_action.sa_mask); ign_action.sa_flags = 0; sigaction (SIGTERM, &exit_action, NULL); sigaction (SIGINT, &ign_action, NULL); sigaction (SIGHUP, &ign_action, NULL); sigaction (SIGQUIT, &ign_action, NULL); sigaction (SIGALRM, &ign_action, NULL); sigaction (SIGUSR1, &ign_action, NULL); sigaction (SIGUSR2, &ign_action, NULL); sigaction (SIGPIPE, &ign_action, NULL); } /**********************************************************************/ void show_usage(char *name) { char *s; s = strrchr(name, '/'); s = s ? s+1 : name; printf("picocom v%s\n", VERSION_STR); printf("\nCompiled-in options:\n"); printf(" TTY_Q_SZ is %d\n", TTY_Q_SZ); #ifdef USE_HIGH_BAUD printf(" HIGH_BAUD is enabled\n"); #endif #ifdef USE_FLOCK printf(" USE_FLOCK is enabled\n"); #endif #ifdef UUCP_LOCK_DIR printf(" UUCP_LOCK_DIR is: %s\n", UUCP_LOCK_DIR); #endif #ifdef LINENOISE printf(" LINENOISE is enabled\n"); printf(" SEND_RECEIVE_HISTFILE is: %s\n", SEND_RECEIVE_HISTFILE); #endif printf("\nUsage is: %s [options] <tty device>\n", s); printf("Options are:\n"); printf(" --<b>aud <baudrate>\n"); printf(" --<f>low s (=soft) | h (=hard) | n (=none)\n"); printf(" --<p>arity o (=odd) | e (=even) | n (=none)\n"); printf(" --<d>atabits 5 | 6 | 7 | 8\n"); printf(" --<e>scape <char>\n"); printf(" --e<c>ho\n"); printf(" --no<i>nit\n"); printf(" --no<r>eset\n"); printf(" --no<l>ock\n"); printf(" --<s>end-cmd <command>\n"); printf(" --recei<v>e-cmd <command>\n"); printf(" --imap <map> (input mappings)\n"); printf(" --omap <map> (output mappings)\n"); printf(" --emap <map> (local-echo mappings)\n"); printf(" --<h>elp\n"); printf("<map> is a comma-separated list of one or more of:\n"); printf(" crlf : map CR --> LF\n"); printf(" crcrlf : map CR --> CR + LF\n"); printf(" igncr : ignore CR\n"); printf(" lfcr : map LF --> CR\n"); printf(" lfcrlf : map LF --> CR + LF\n"); printf(" ignlf : ignore LF\n"); printf(" bsdel : map BS --> DEL\n"); printf(" delbs : map DEL --> BS\n"); printf("<?> indicates the equivalent short option.\n"); printf("Short options are prefixed by \"-\" instead of by \"--\".\n"); } /**********************************************************************/ void parse_args(int argc, char *argv[]) { int r; static struct option longOptions[] = { {"receive-cmd", required_argument, 0, 'v'}, {"send-cmd", required_argument, 0, 's'}, {"imap", required_argument, 0, 'I' }, {"omap", required_argument, 0, 'O' }, {"emap", required_argument, 0, 'E' }, {"escape", required_argument, 0, 'e'}, {"echo", no_argument, 0, 'c'}, {"noinit", no_argument, 0, 'i'}, {"noreset", no_argument, 0, 'r'}, {"nolock", no_argument, 0, 'l'}, {"flow", required_argument, 0, 'f'}, {"baud", required_argument, 0, 'b'}, {"parity", required_argument, 0, 'p'}, {"databits", required_argument, 0, 'd'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; r = 0; while (1) { int optionIndex = 0; int c; int map; /* no default error messages printed. */ opterr = 0; c = getopt_long(argc, argv, "hirlcv:s:r:e:f:b:p:d:", longOptions, &optionIndex); if (c < 0) break; switch (c) { case 's': strncpy(opts.send_cmd, optarg, sizeof(opts.send_cmd)); opts.send_cmd[sizeof(opts.send_cmd) - 1] = '\0'; break; case 'v': strncpy(opts.receive_cmd, optarg, sizeof(opts.receive_cmd)); opts.receive_cmd[sizeof(opts.receive_cmd) - 1] = '\0'; break; case 'I': map = parse_map(optarg); if (map >= 0) opts.imap = map; else { fprintf(stderr, "Invalid --imap\n"); r = -1; } break; case 'O': map = parse_map(optarg); if (map >= 0) opts.omap = map; else { fprintf(stderr, "Invalid --omap\n"); r = -1; } break; case 'E': map = parse_map(optarg); if (map >= 0) opts.emap = map; else { fprintf(stderr, "Invalid --emap\n"); r = -1; } break; case 'c': opts.lecho = 1; break; case 'i': opts.noinit = 1; break; case 'r': opts.noreset = 1; break; case 'l': #if defined (UUCP_LOCK_DIR) || defined (USE_FLOCK) opts.nolock = 1; #endif break; case 'e': opts.escape = optarg[0] & 0x1f; break; case 'f': switch (optarg[0]) { case 'X': case 'x': opts.flow = FC_XONXOFF; break; case 'H': case 'h': opts.flow = FC_RTSCTS; break; case 'N': case 'n': opts.flow = FC_NONE; break; default: fprintf(stderr, "Invalid --flow: %c\n", optarg[0]); r = -1; break; } break; case 'b': opts.baud = atoi(optarg); break; case 'p': switch (optarg[0]) { case 'e': opts.parity = P_EVEN; break; case 'o': opts.parity = P_ODD; break; case 'n': opts.parity = P_NONE; break; default: fprintf(stderr, "Invalid --parity: %c\n", optarg[0]); r = -1; break; } break; case 'd': switch (optarg[0]) { case '5': opts.databits = 5; break; case '6': opts.databits = 6; break; case '7': opts.databits = 7; break; case '8': opts.databits = 8; break; default: fprintf(stderr, "Invalid --databits: %c\n", optarg[0]); r = -1; break; } break; case 'h': show_usage(argv[0]); exit(EXIT_SUCCESS); case '?': default: fprintf(stderr, "Unrecognized option(s)\n"); r = -1; break; } if ( r < 0 ) { fprintf(stderr, "Run with '--help'.\n"); exit(EXIT_FAILURE); } } /* while */ if ( (argc - optind) < 1) { fprintf(stderr, "No port given\n"); fprintf(stderr, "Run with '--help'.\n"); exit(EXIT_FAILURE); } strncpy(opts.port, argv[optind], sizeof(opts.port) - 1); opts.port[sizeof(opts.port) - 1] = '\0'; printf("picocom v%s\n", VERSION_STR); printf("\n"); printf("port is : %s\n", opts.port); printf("flowcontrol : %s\n", flow_str[opts.flow]); printf("baudrate is : %d\n", opts.baud); printf("parity is : %s\n", parity_str[opts.parity]); printf("databits are : %d\n", opts.databits); printf("escape is : C-%c\n", 'a' + opts.escape - 1); printf("local echo is : %s\n", opts.lecho ? "yes" : "no"); printf("noinit is : %s\n", opts.noinit ? "yes" : "no"); printf("noreset is : %s\n", opts.noreset ? "yes" : "no"); #if defined (UUCP_LOCK_DIR) || defined (USE_FLOCK) printf("nolock is : %s\n", opts.nolock ? "yes" : "no"); #endif printf("send_cmd is : %s\n", (opts.send_cmd[0] == '\0') ? "disabled" : opts.send_cmd); printf("receive_cmd is : %s\n", (opts.receive_cmd[0] == '\0') ? "disabled" : opts.receive_cmd); printf("imap is : "); print_map(opts.imap); printf("omap is : "); print_map(opts.omap); printf("emap is : "); print_map(opts.emap); printf("\n"); } /**********************************************************************/ int main(int argc, char *argv[]) { int r; parse_args(argc, argv); establish_signal_handlers(); r = term_lib_init(); if ( r < 0 ) fatal("term_init failed: %s", term_strerror(term_errno, errno)); #ifdef UUCP_LOCK_DIR if ( ! opts.nolock ) uucp_lockname(UUCP_LOCK_DIR, opts.port); if ( uucp_lock() < 0 ) fatal("cannot lock %s: %s", opts.port, strerror(errno)); #endif tty_fd = open(opts.port, O_RDWR | O_NONBLOCK | O_NOCTTY); if (tty_fd < 0) fatal("cannot open %s: %s", opts.port, strerror(errno)); #ifdef USE_FLOCK if ( ! opts.nolock ) { r = flock(tty_fd, LOCK_EX | LOCK_NB); if ( r < 0 ) fatal("cannot lock %s: %s", opts.port, strerror(errno)); } #endif if ( opts.noinit ) { r = term_add(tty_fd); } else { r = term_set(tty_fd, 1, /* raw mode. */ opts.baud, /* baud rate. */ opts.parity, /* parity. */ opts.databits, /* data bits. */ opts.flow, /* flow control. */ 1, /* local or modem */ !opts.noreset); /* hup-on-close. */ } if ( r < 0 ) fatal("failed to add device %s: %s", opts.port, term_strerror(term_errno, errno)); r = term_apply(tty_fd); if ( r < 0 ) fatal("failed to config device %s: %s", opts.port, term_strerror(term_errno, errno)); set_tty_write_sz(term_get_baudrate(tty_fd, NULL)); r = term_add(STI); if ( r < 0 ) fatal("failed to add I/O device: %s", term_strerror(term_errno, errno)); term_set_raw(STI); r = term_apply(STI); if ( r < 0 ) fatal("failed to set I/O device to raw mode: %s", term_strerror(term_errno, errno)); #ifdef LINENOISE init_send_receive_history(); #endif fd_printf(STO, "Terminal ready\r\n"); loop(); #ifdef LINENOISE cleanup_send_receive_history(); #endif fd_printf(STO, "\r\n"); if ( opts.noreset ) { fd_printf(STO, "Skipping tty reset...\r\n"); term_erase(tty_fd); } if ( sig_exit ) fd_printf(STO, "Picocom was killed\r\n"); else fd_printf(STO, "Thanks for using picocom\r\n"); /* wait a bit for output to drain */ sleep(1); #ifdef UUCP_LOCK_DIR uucp_unlock(); #endif return EXIT_SUCCESS; } /**********************************************************************/ /* * Local Variables: * mode:c * tab-width: 4 * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-77/c/bad_1866_1
crossvul-cpp_data_good_2351_1
/* * save.c - write the cache struct to disk * * Copyright (C) 2001 by Andreas Dilger * Copyright (C) 2003 Theodore Ts'o * * %Begin-Header% * This file may be redistributed under the terms of the * GNU Lesser General Public License. * %End-Header% */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #ifdef HAVE_ERRNO_H #include <errno.h> #endif #include "closestream.h" #include "blkidP.h" static void save_quoted(const char *data, FILE *file) { const char *p; fputc('"', file); for (p = data; p && *p; p++) { if ((unsigned char) *p == 0x22 || /* " */ (unsigned char) *p == 0x5c) /* \ */ fputc('\\', file); fputc(*p, file); } fputc('"', file); } static int save_dev(blkid_dev dev, FILE *file) { struct list_head *p; if (!dev || dev->bid_name[0] != '/') return 0; DBG(SAVE, ul_debug("device %s, type %s", dev->bid_name, dev->bid_type ? dev->bid_type : "(null)")); fprintf(file, "<device DEVNO=\"0x%04lx\" TIME=\"%ld.%ld\"", (unsigned long) dev->bid_devno, (long) dev->bid_time, (long) dev->bid_utime); if (dev->bid_pri) fprintf(file, " PRI=\"%d\"", dev->bid_pri); list_for_each(p, &dev->bid_tags) { blkid_tag tag = list_entry(p, struct blkid_struct_tag, bit_tags); fputc(' ', file); /* space between tags */ fputs(tag->bit_name, file); /* tag NAME */ fputc('=', file); /* separator between NAME and VALUE */ save_quoted(tag->bit_val, file); /* tag "VALUE" */ } fprintf(file, ">%s</device>\n", dev->bid_name); return 0; } /* * Write out the cache struct to the cache file on disk. */ int blkid_flush_cache(blkid_cache cache) { struct list_head *p; char *tmp = NULL; char *opened = NULL; char *filename; FILE *file = NULL; int fd, ret = 0; struct stat st; if (!cache) return -BLKID_ERR_PARAM; if (list_empty(&cache->bic_devs) || !(cache->bic_flags & BLKID_BIC_FL_CHANGED)) { DBG(SAVE, ul_debug("skipping cache file write")); return 0; } filename = cache->bic_filename ? cache->bic_filename : blkid_get_cache_filename(NULL); if (!filename) return -BLKID_ERR_PARAM; if (strncmp(filename, BLKID_RUNTIME_DIR "/", sizeof(BLKID_RUNTIME_DIR)) == 0) { /* default destination, create the directory if necessary */ if (stat(BLKID_RUNTIME_DIR, &st) && errno == ENOENT && mkdir(BLKID_RUNTIME_DIR, S_IWUSR| S_IRUSR|S_IRGRP|S_IROTH| S_IXUSR|S_IXGRP|S_IXOTH) != 0 && errno != EEXIST) { DBG(SAVE, ul_debug("can't create %s directory for cache file", BLKID_RUNTIME_DIR)); return 0; } } /* If we can't write to the cache file, then don't even try */ if (((ret = stat(filename, &st)) < 0 && errno != ENOENT) || (ret == 0 && access(filename, W_OK) < 0)) { DBG(SAVE, ul_debug("can't write to cache file %s", filename)); return 0; } /* * Try and create a temporary file in the same directory so * that in case of error we don't overwrite the cache file. * If the cache file doesn't yet exist, it isn't a regular * file (e.g. /dev/null or a socket), or we couldn't create * a temporary file then we open it directly. */ if (ret == 0 && S_ISREG(st.st_mode)) { tmp = malloc(strlen(filename) + 8); if (tmp) { sprintf(tmp, "%s-XXXXXX", filename); fd = mkostemp(tmp, O_RDWR|O_CREAT|O_EXCL|O_CLOEXEC); if (fd >= 0) { if (fchmod(fd, 0644) != 0) DBG(SAVE, ul_debug("%s: fchmod failed", filename)); else if ((file = fdopen(fd, "w" UL_CLOEXECSTR))) opened = tmp; if (!file) close(fd); } } } if (!file) { file = fopen(filename, "w" UL_CLOEXECSTR); opened = filename; } DBG(SAVE, ul_debug("writing cache file %s (really %s)", filename, opened)); if (!file) { ret = errno; goto errout; } list_for_each(p, &cache->bic_devs) { blkid_dev dev = list_entry(p, struct blkid_struct_dev, bid_devs); if (!dev->bid_type || (dev->bid_flags & BLKID_BID_FL_REMOVABLE)) continue; if ((ret = save_dev(dev, file)) < 0) break; } if (ret >= 0) { cache->bic_flags &= ~BLKID_BIC_FL_CHANGED; ret = 1; } if (close_stream(file) != 0) DBG(SAVE, ul_debug("write failed: %s", filename)); if (opened != filename) { if (ret < 0) { unlink(opened); DBG(SAVE, ul_debug("unlinked temp cache %s", opened)); } else { char *backup; backup = malloc(strlen(filename) + 5); if (backup) { sprintf(backup, "%s.old", filename); unlink(backup); if (link(filename, backup)) { DBG(SAVE, ul_debug("can't link %s to %s", filename, backup)); } free(backup); } if (rename(opened, filename)) { ret = errno; DBG(SAVE, ul_debug("can't rename %s to %s", opened, filename)); } else { DBG(SAVE, ul_debug("moved temp cache %s", opened)); } } } errout: free(tmp); if (filename != cache->bic_filename) free(filename); return ret; } #ifdef TEST_PROGRAM int main(int argc, char **argv) { blkid_cache cache = NULL; int ret; blkid_init_debug(BLKID_DEBUG_ALL); if (argc > 2) { fprintf(stderr, "Usage: %s [filename]\n" "Test loading/saving a cache (filename)\n", argv[0]); exit(1); } if ((ret = blkid_get_cache(&cache, "/dev/null")) != 0) { fprintf(stderr, "%s: error creating cache (%d)\n", argv[0], ret); exit(1); } if ((ret = blkid_probe_all(cache)) < 0) { fprintf(stderr, "error (%d) probing devices\n", ret); exit(1); } cache->bic_filename = strdup(argv[1]); if ((ret = blkid_flush_cache(cache)) < 0) { fprintf(stderr, "error (%d) saving cache\n", ret); exit(1); } blkid_put_cache(cache); return ret; } #endif
./CrossVul/dataset_final_sorted/CWE-77/c/good_2351_1
crossvul-cpp_data_good_248_0
/** * @file * IMAP network mailbox * * @authors * Copyright (C) 1996-1998,2012 Michael R. Elkins <me@mutt.org> * Copyright (C) 1996-1999 Brandon Long <blong@fiction.net> * Copyright (C) 1999-2009,2012,2017 Brendan Cully <brendan@kublai.com> * * @copyright * 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, see <http://www.gnu.org/licenses/>. */ /** * @page imap_imap IMAP network mailbox * * Support for IMAP4rev1, with the occasional nod to IMAP 4. */ #include "config.h" #include <ctype.h> #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include "imap_private.h" #include "mutt/mutt.h" #include "conn/conn.h" #include "mutt.h" #include "imap.h" #include "auth.h" #include "bcache.h" #include "body.h" #include "buffy.h" #include "context.h" #include "envelope.h" #include "globals.h" #include "header.h" #include "mailbox.h" #include "message.h" #include "mutt_account.h" #include "mutt_curses.h" #include "mutt_logging.h" #include "mutt_socket.h" #include "mx.h" #include "options.h" #include "pattern.h" #include "progress.h" #include "protos.h" #include "sort.h" #include "tags.h" #include "url.h" #ifdef USE_HCACHE #include "hcache/hcache.h" #endif /** * check_capabilities - Make sure we can log in to this server * @param idata Server data * @retval 0 Success * @retval -1 Failure */ static int check_capabilities(struct ImapData *idata) { if (imap_exec(idata, "CAPABILITY", 0) != 0) { imap_error("check_capabilities", idata->buf); return -1; } if (!(mutt_bit_isset(idata->capabilities, IMAP4) || mutt_bit_isset(idata->capabilities, IMAP4REV1))) { mutt_error( _("This IMAP server is ancient. NeoMutt does not work with it.")); return -1; } return 0; } /** * get_flags - Make a simple list out of a FLAGS response * @param hflags List to store flags * @param s String containing flags * @retval ptr End of the flags * @retval ptr NULL Failure * * return stream following FLAGS response */ static char *get_flags(struct ListHead *hflags, char *s) { /* sanity-check string */ if (mutt_str_strncasecmp("FLAGS", s, 5) != 0) { mutt_debug(1, "not a FLAGS response: %s\n", s); return NULL; } s += 5; SKIPWS(s); if (*s != '(') { mutt_debug(1, "bogus FLAGS response: %s\n", s); return NULL; } /* update caller's flags handle */ while (*s && *s != ')') { s++; SKIPWS(s); const char *flag_word = s; while (*s && (*s != ')') && !ISSPACE(*s)) s++; const char ctmp = *s; *s = '\0'; if (*flag_word) mutt_list_insert_tail(hflags, mutt_str_strdup(flag_word)); *s = ctmp; } /* note bad flags response */ if (*s != ')') { mutt_debug(1, "Unterminated FLAGS response: %s\n", s); mutt_list_free(hflags); return NULL; } s++; return s; } /** * set_flag - append str to flags if we currently have permission according to aclbit * @param[in] idata Server data * @param[in] aclbit Permissions, e.g. #MUTT_ACL_WRITE * @param[in] flag Does the email have the flag set? * @param[in] str Server flag name * @param[out] flags Buffer for server command * @param[in] flsize Length of buffer */ static void set_flag(struct ImapData *idata, int aclbit, int flag, const char *str, char *flags, size_t flsize) { if (mutt_bit_isset(idata->ctx->rights, aclbit)) if (flag && imap_has_flag(&idata->flags, str)) mutt_str_strcat(flags, flsize, str); } /** * make_msg_set - Make a message set * @param[in] idata Server data * @param[in] buf Buffer to store message set * @param[in] flag Flags to match, e.g. #MUTT_DELETED * @param[in] changed Matched messages that have been altered * @param[in] invert Flag matches should be inverted * @param[out] pos Cursor used for multiple calls to this function * @retval num Messages in the set * * @note Headers must be in SORT_ORDER. See imap_exec_msgset() for args. * Pos is an opaque pointer a la strtok(). It should be 0 at first call. */ static int make_msg_set(struct ImapData *idata, struct Buffer *buf, int flag, bool changed, bool invert, int *pos) { int count = 0; /* number of messages in message set */ unsigned int setstart = 0; /* start of current message range */ int n; bool started = false; struct Header **hdrs = idata->ctx->hdrs; for (n = *pos; n < idata->ctx->msgcount && buf->dptr - buf->data < IMAP_MAX_CMDLEN; n++) { bool match = false; /* whether current message matches flag condition */ /* don't include pending expunged messages */ if (hdrs[n]->active) { switch (flag) { case MUTT_DELETED: if (hdrs[n]->deleted != HEADER_DATA(hdrs[n])->deleted) match = invert ^ hdrs[n]->deleted; break; case MUTT_FLAG: if (hdrs[n]->flagged != HEADER_DATA(hdrs[n])->flagged) match = invert ^ hdrs[n]->flagged; break; case MUTT_OLD: if (hdrs[n]->old != HEADER_DATA(hdrs[n])->old) match = invert ^ hdrs[n]->old; break; case MUTT_READ: if (hdrs[n]->read != HEADER_DATA(hdrs[n])->read) match = invert ^ hdrs[n]->read; break; case MUTT_REPLIED: if (hdrs[n]->replied != HEADER_DATA(hdrs[n])->replied) match = invert ^ hdrs[n]->replied; break; case MUTT_TAG: if (hdrs[n]->tagged) match = true; break; case MUTT_TRASH: if (hdrs[n]->deleted && !hdrs[n]->purge) match = true; break; } } if (match && (!changed || hdrs[n]->changed)) { count++; if (setstart == 0) { setstart = HEADER_DATA(hdrs[n])->uid; if (!started) { mutt_buffer_printf(buf, "%u", HEADER_DATA(hdrs[n])->uid); started = true; } else mutt_buffer_printf(buf, ",%u", HEADER_DATA(hdrs[n])->uid); } /* tie up if the last message also matches */ else if (n == idata->ctx->msgcount - 1) mutt_buffer_printf(buf, ":%u", HEADER_DATA(hdrs[n])->uid); } /* End current set if message doesn't match or we've reached the end * of the mailbox via inactive messages following the last match. */ else if (setstart && (hdrs[n]->active || n == idata->ctx->msgcount - 1)) { if (HEADER_DATA(hdrs[n - 1])->uid > setstart) mutt_buffer_printf(buf, ":%u", HEADER_DATA(hdrs[n - 1])->uid); setstart = 0; } } *pos = n; return count; } /** * compare_flags_for_copy - Compare local flags against the server * @param h Header of email * @retval true Flags have changed * @retval false Flags match cached server flags * * The comparison of flags EXCLUDES the deleted flag. */ static bool compare_flags_for_copy(struct Header *h) { struct ImapHeaderData *hd = (struct ImapHeaderData *) h->data; if (h->read != hd->read) return true; if (h->old != hd->old) return true; if (h->flagged != hd->flagged) return true; if (h->replied != hd->replied) return true; return false; } /** * sync_helper - Sync flag changes to the server * @param idata Server data * @param right ACL, e.g. #MUTT_ACL_DELETE * @param flag Mutt flag, e.g. MUTT_DELETED * @param name Name of server flag * @retval >=0 Success, number of messages * @retval -1 Failure */ static int sync_helper(struct ImapData *idata, int right, int flag, const char *name) { int count = 0; int rc; char buf[LONG_STRING]; if (!idata->ctx) return -1; if (!mutt_bit_isset(idata->ctx->rights, right)) return 0; if (right == MUTT_ACL_WRITE && !imap_has_flag(&idata->flags, name)) return 0; snprintf(buf, sizeof(buf), "+FLAGS.SILENT (%s)", name); rc = imap_exec_msgset(idata, "UID STORE", buf, flag, 1, 0); if (rc < 0) return rc; count += rc; buf[0] = '-'; rc = imap_exec_msgset(idata, "UID STORE", buf, flag, 1, 1); if (rc < 0) return rc; count += rc; return count; } /** * get_mailbox - Split mailbox URI * @param path Mailbox URI * @param hidata Server data * @param buf Buffer to store mailbox name * @param blen Length of buffer * @retval 0 Success * @retval -1 Failure * * Split up a mailbox URI. The connection info is stored in the ImapData and * the mailbox name is stored in buf. */ static int get_mailbox(const char *path, struct ImapData **hidata, char *buf, size_t blen) { struct ImapMbox mx; if (imap_parse_path(path, &mx)) { mutt_debug(1, "Error parsing %s\n", path); return -1; } if (!(*hidata = imap_conn_find(&(mx.account), ImapPassive ? MUTT_IMAP_CONN_NONEW : 0)) || (*hidata)->state < IMAP_AUTHENTICATED) { FREE(&mx.mbox); return -1; } imap_fix_path(*hidata, mx.mbox, buf, blen); if (!*buf) mutt_str_strfcpy(buf, "INBOX", blen); FREE(&mx.mbox); return 0; } /** * do_search - Perform a search of messages * @param search List of pattern to match * @param allpats Must all patterns match? * @retval num Number of patterns search that should be done server-side * * Count the number of patterns that can be done by the server (are full-text). */ static int do_search(const struct Pattern *search, int allpats) { int rc = 0; const struct Pattern *pat = NULL; for (pat = search; pat; pat = pat->next) { switch (pat->op) { case MUTT_BODY: case MUTT_HEADER: case MUTT_WHOLE_MSG: if (pat->stringmatch) rc++; break; case MUTT_SERVERSEARCH: rc++; break; default: if (pat->child && do_search(pat->child, 1)) rc++; } if (!allpats) break; } return rc; } /** * compile_search - Convert NeoMutt pattern to IMAP search * @param ctx Context * @param pat Pattern to convert * @param buf Buffer for result * @retval 0 Success * @retval -1 Failure * * Convert neomutt Pattern to IMAP SEARCH command containing only elements * that require full-text search (neomutt already has what it needs for most * match types, and does a better job (eg server doesn't support regexes). */ static int compile_search(struct Context *ctx, const struct Pattern *pat, struct Buffer *buf) { if (do_search(pat, 0) == 0) return 0; if (pat->not) mutt_buffer_addstr(buf, "NOT "); if (pat->child) { int clauses; clauses = do_search(pat->child, 1); if (clauses > 0) { const struct Pattern *clause = pat->child; mutt_buffer_addch(buf, '('); while (clauses) { if (do_search(clause, 0)) { if (pat->op == MUTT_OR && clauses > 1) mutt_buffer_addstr(buf, "OR "); clauses--; if (compile_search(ctx, clause, buf) < 0) return -1; if (clauses) mutt_buffer_addch(buf, ' '); } clause = clause->next; } mutt_buffer_addch(buf, ')'); } } else { char term[STRING]; char *delim = NULL; switch (pat->op) { case MUTT_HEADER: mutt_buffer_addstr(buf, "HEADER "); /* extract header name */ delim = strchr(pat->p.str, ':'); if (!delim) { mutt_error(_("Header search without header name: %s"), pat->p.str); return -1; } *delim = '\0'; imap_quote_string(term, sizeof(term), pat->p.str, false); mutt_buffer_addstr(buf, term); mutt_buffer_addch(buf, ' '); /* and field */ *delim = ':'; delim++; SKIPWS(delim); imap_quote_string(term, sizeof(term), delim, false); mutt_buffer_addstr(buf, term); break; case MUTT_BODY: mutt_buffer_addstr(buf, "BODY "); imap_quote_string(term, sizeof(term), pat->p.str, false); mutt_buffer_addstr(buf, term); break; case MUTT_WHOLE_MSG: mutt_buffer_addstr(buf, "TEXT "); imap_quote_string(term, sizeof(term), pat->p.str, false); mutt_buffer_addstr(buf, term); break; case MUTT_SERVERSEARCH: { struct ImapData *idata = ctx->data; if (!mutt_bit_isset(idata->capabilities, X_GM_EXT1)) { mutt_error(_("Server-side custom search not supported: %s"), pat->p.str); return -1; } } mutt_buffer_addstr(buf, "X-GM-RAW "); imap_quote_string(term, sizeof(term), pat->p.str, false); mutt_buffer_addstr(buf, term); break; } } return 0; } /** * longest_common_prefix - Find longest prefix common to two strings * @param dest Destination buffer * @param src Source buffer * @param start Starting offset into string * @param dlen Destination buffer length * @retval num Length of the common string * * Trim dest to the length of the longest prefix it shares with src. */ static size_t longest_common_prefix(char *dest, const char *src, size_t start, size_t dlen) { size_t pos = start; while (pos < dlen && dest[pos] && dest[pos] == src[pos]) pos++; dest[pos] = '\0'; return pos; } /** * complete_hosts - Look for completion matches for mailboxes * @param buf Partial mailbox name to complete * @param buflen Length of buffer * @retval 0 Success * @retval -1 Failure * * look for IMAP URLs to complete from defined mailboxes. Could be extended to * complete over open connections and account/folder hooks too. */ static int complete_hosts(char *buf, size_t buflen) { struct Buffy *mailbox = NULL; struct Connection *conn = NULL; int rc = -1; size_t matchlen; matchlen = mutt_str_strlen(buf); for (mailbox = Incoming; mailbox; mailbox = mailbox->next) { if (mutt_str_strncmp(buf, mailbox->path, matchlen) == 0) { if (rc) { mutt_str_strfcpy(buf, mailbox->path, buflen); rc = 0; } else longest_common_prefix(buf, mailbox->path, matchlen, buflen); } } TAILQ_FOREACH(conn, mutt_socket_head(), entries) { struct Url url; char urlstr[LONG_STRING]; if (conn->account.type != MUTT_ACCT_TYPE_IMAP) continue; mutt_account_tourl(&conn->account, &url); /* FIXME: how to handle multiple users on the same host? */ url.user = NULL; url.path = NULL; url_tostring(&url, urlstr, sizeof(urlstr), 0); if (mutt_str_strncmp(buf, urlstr, matchlen) == 0) { if (rc) { mutt_str_strfcpy(buf, urlstr, buflen); rc = 0; } else longest_common_prefix(buf, urlstr, matchlen, buflen); } } return rc; } /** * imap_access - Check permissions on an IMAP mailbox * @param path Mailbox path * @retval 0 Success * @retval <0 Failure * * TODO: ACL checks. Right now we assume if it exists we can mess with it. */ int imap_access(const char *path) { struct ImapData *idata = NULL; struct ImapMbox mx; char buf[LONG_STRING]; char mailbox[LONG_STRING]; char mbox[LONG_STRING]; int rc; if (imap_parse_path(path, &mx)) return -1; idata = imap_conn_find(&mx.account, ImapPassive ? MUTT_IMAP_CONN_NONEW : 0); if (!idata) { FREE(&mx.mbox); return -1; } imap_fix_path(idata, mx.mbox, mailbox, sizeof(mailbox)); if (!*mailbox) mutt_str_strfcpy(mailbox, "INBOX", sizeof(mailbox)); /* we may already be in the folder we're checking */ if (mutt_str_strcmp(idata->mailbox, mx.mbox) == 0) { FREE(&mx.mbox); return 0; } FREE(&mx.mbox); if (imap_mboxcache_get(idata, mailbox, 0)) { mutt_debug(3, "found %s in cache\n", mailbox); return 0; } imap_munge_mbox_name(idata, mbox, sizeof(mbox), mailbox); if (mutt_bit_isset(idata->capabilities, IMAP4REV1)) snprintf(buf, sizeof(buf), "STATUS %s (UIDVALIDITY)", mbox); else if (mutt_bit_isset(idata->capabilities, STATUS)) snprintf(buf, sizeof(buf), "STATUS %s (UID-VALIDITY)", mbox); else { mutt_debug(2, "STATUS not supported?\n"); return -1; } rc = imap_exec(idata, buf, IMAP_CMD_FAIL_OK); if (rc < 0) { mutt_debug(1, "Can't check STATUS of %s\n", mbox); return rc; } return 0; } /** * imap_create_mailbox - Create a new mailbox * @param idata Server data * @param mailbox Mailbox to create * @retval 0 Success * @retval -1 Failure */ int imap_create_mailbox(struct ImapData *idata, char *mailbox) { char buf[LONG_STRING], mbox[LONG_STRING]; imap_munge_mbox_name(idata, mbox, sizeof(mbox), mailbox); snprintf(buf, sizeof(buf), "CREATE %s", mbox); if (imap_exec(idata, buf, 0) != 0) { mutt_error(_("CREATE failed: %s"), imap_cmd_trailer(idata)); return -1; } return 0; } /** * imap_rename_mailbox - Rename a mailbox * @param idata Server data * @param mx Existing mailbox * @param newname New name for mailbox * @retval 0 Success * @retval -1 Failure */ int imap_rename_mailbox(struct ImapData *idata, struct ImapMbox *mx, const char *newname) { char oldmbox[LONG_STRING]; char newmbox[LONG_STRING]; char buf[LONG_STRING]; imap_munge_mbox_name(idata, oldmbox, sizeof(oldmbox), mx->mbox); imap_munge_mbox_name(idata, newmbox, sizeof(newmbox), newname); snprintf(buf, sizeof(buf), "RENAME %s %s", oldmbox, newmbox); if (imap_exec(idata, buf, 0) != 0) return -1; return 0; } /** * imap_delete_mailbox - Delete a mailbox * @param ctx Context * @param mx Mailbox to delete * @retval 0 Success * @retval -1 Failure */ int imap_delete_mailbox(struct Context *ctx, struct ImapMbox *mx) { char buf[PATH_MAX], mbox[PATH_MAX]; struct ImapData *idata = NULL; if (!ctx || !ctx->data) { idata = imap_conn_find(&mx->account, ImapPassive ? MUTT_IMAP_CONN_NONEW : 0); if (!idata) { FREE(&mx->mbox); return -1; } } else { idata = ctx->data; } imap_munge_mbox_name(idata, mbox, sizeof(mbox), mx->mbox); snprintf(buf, sizeof(buf), "DELETE %s", mbox); if (imap_exec(idata, buf, 0) != 0) return -1; return 0; } /** * imap_logout_all - close all open connections * * Quick and dirty until we can make sure we've got all the context we need. */ void imap_logout_all(void) { struct ConnectionList *head = mutt_socket_head(); struct Connection *np, *tmp; TAILQ_FOREACH_SAFE(np, head, entries, tmp) { if (np->account.type == MUTT_ACCT_TYPE_IMAP && np->fd >= 0) { TAILQ_REMOVE(head, np, entries); mutt_message(_("Closing connection to %s..."), np->account.host); imap_logout((struct ImapData **) (void *) &np->data); mutt_clear_error(); mutt_socket_free(np); } } } /** * imap_read_literal - Read bytes bytes from server into file * @param fp File handle for email file * @param idata Server data * @param bytes Number of bytes to read * @param pbar Progress bar * @retval 0 Success * @retval -1 Failure * * Not explicitly buffered, relies on FILE buffering. * * @note Strips `\r` from `\r\n`. * Apparently even literals use `\r\n`-terminated strings ?! */ int imap_read_literal(FILE *fp, struct ImapData *idata, unsigned long bytes, struct Progress *pbar) { char c; bool r = false; struct Buffer *buf = NULL; if (DebugLevel >= IMAP_LOG_LTRL) buf = mutt_buffer_alloc(bytes + 10); mutt_debug(2, "reading %ld bytes\n", bytes); for (unsigned long pos = 0; pos < bytes; pos++) { if (mutt_socket_readchar(idata->conn, &c) != 1) { mutt_debug(1, "error during read, %ld bytes read\n", pos); idata->status = IMAP_FATAL; mutt_buffer_free(&buf); return -1; } if (r && c != '\n') fputc('\r', fp); if (c == '\r') { r = true; continue; } else r = false; fputc(c, fp); if (pbar && !(pos % 1024)) mutt_progress_update(pbar, pos, -1); if (DebugLevel >= IMAP_LOG_LTRL) mutt_buffer_addch(buf, c); } if (DebugLevel >= IMAP_LOG_LTRL) { mutt_debug(IMAP_LOG_LTRL, "\n%s", buf->data); mutt_buffer_free(&buf); } return 0; } /** * imap_expunge_mailbox - Purge messages from the server * @param idata Server data * * Purge IMAP portion of expunged messages from the context. Must not be done * while something has a handle on any headers (eg inside pager or editor). * That is, check IMAP_REOPEN_ALLOW. */ void imap_expunge_mailbox(struct ImapData *idata) { struct Header *h = NULL; int cacheno; short old_sort; #ifdef USE_HCACHE idata->hcache = imap_hcache_open(idata, NULL); #endif old_sort = Sort; Sort = SORT_ORDER; mutt_sort_headers(idata->ctx, 0); for (int i = 0; i < idata->ctx->msgcount; i++) { h = idata->ctx->hdrs[i]; if (h->index == INT_MAX) { mutt_debug(2, "Expunging message UID %u.\n", HEADER_DATA(h)->uid); h->active = false; idata->ctx->size -= h->content->length; imap_cache_del(idata, h); #ifdef USE_HCACHE imap_hcache_del(idata, HEADER_DATA(h)->uid); #endif /* free cached body from disk, if necessary */ cacheno = HEADER_DATA(h)->uid % IMAP_CACHE_LEN; if (idata->cache[cacheno].uid == HEADER_DATA(h)->uid && idata->cache[cacheno].path) { unlink(idata->cache[cacheno].path); FREE(&idata->cache[cacheno].path); } mutt_hash_int_delete(idata->uid_hash, HEADER_DATA(h)->uid, h); imap_free_header_data((struct ImapHeaderData **) &h->data); } else { h->index = i; /* NeoMutt has several places where it turns off h->active as a * hack. For example to avoid FLAG updates, or to exclude from * imap_exec_msgset. * * Unfortunately, when a reopen is allowed and the IMAP_EXPUNGE_PENDING * flag becomes set (e.g. a flag update to a modified header), * this function will be called by imap_cmd_finish(). * * The mx_update_tables() will free and remove these "inactive" headers, * despite that an EXPUNGE was not received for them. * This would result in memory leaks and segfaults due to dangling * pointers in the msn_index and uid_hash. * * So this is another hack to work around the hacks. We don't want to * remove the messages, so make sure active is on. */ h->active = true; } } #ifdef USE_HCACHE imap_hcache_close(idata); #endif /* We may be called on to expunge at any time. We can't rely on the caller * to always know to rethread */ mx_update_tables(idata->ctx, false); Sort = old_sort; mutt_sort_headers(idata->ctx, 1); } /** * imap_conn_find - Find an open IMAP connection * @param account Account to search * @param flags Flags, e.g. #MUTT_IMAP_CONN_NONEW * @retval ptr Matching connection * @retval NULL Failure * * Find an open IMAP connection matching account, or open a new one if none can * be found. */ struct ImapData *imap_conn_find(const struct Account *account, int flags) { struct Connection *conn = NULL; struct Account *creds = NULL; struct ImapData *idata = NULL; bool new = false; while ((conn = mutt_conn_find(conn, account))) { if (!creds) creds = &conn->account; else memcpy(&conn->account, creds, sizeof(struct Account)); idata = conn->data; if (flags & MUTT_IMAP_CONN_NONEW) { if (!idata) { /* This should only happen if we've come to the end of the list */ mutt_socket_free(conn); return NULL; } else if (idata->state < IMAP_AUTHENTICATED) continue; } if (flags & MUTT_IMAP_CONN_NOSELECT && idata && idata->state >= IMAP_SELECTED) continue; if (idata && idata->status == IMAP_FATAL) continue; break; } if (!conn) return NULL; /* this happens when the initial connection fails */ if (!idata) { /* The current connection is a new connection */ idata = imap_new_idata(); if (!idata) { mutt_socket_free(conn); return NULL; } conn->data = idata; idata->conn = conn; new = true; } if (idata->state == IMAP_DISCONNECTED) imap_open_connection(idata); if (idata->state == IMAP_CONNECTED) { if (imap_authenticate(idata) == IMAP_AUTH_SUCCESS) { idata->state = IMAP_AUTHENTICATED; FREE(&idata->capstr); new = true; if (idata->conn->ssf) mutt_debug(2, "Communication encrypted at %d bits\n", idata->conn->ssf); } else mutt_account_unsetpass(&idata->conn->account); } if (new && idata->state == IMAP_AUTHENTICATED) { /* capabilities may have changed */ imap_exec(idata, "CAPABILITY", IMAP_CMD_QUEUE); /* enable RFC6855, if the server supports that */ if (mutt_bit_isset(idata->capabilities, ENABLE)) imap_exec(idata, "ENABLE UTF8=ACCEPT", IMAP_CMD_QUEUE); /* get root delimiter, '/' as default */ idata->delim = '/'; imap_exec(idata, "LIST \"\" \"\"", IMAP_CMD_QUEUE); /* we may need the root delimiter before we open a mailbox */ imap_exec(idata, NULL, IMAP_CMD_FAIL_OK); } return idata; } /** * imap_open_connection - Open an IMAP connection * @param idata Server data * @retval 0 Success * @retval -1 Failure */ int imap_open_connection(struct ImapData *idata) { char buf[LONG_STRING]; if (mutt_socket_open(idata->conn) < 0) return -1; idata->state = IMAP_CONNECTED; if (imap_cmd_step(idata) != IMAP_CMD_OK) { imap_close_connection(idata); return -1; } if (mutt_str_strncasecmp("* OK", idata->buf, 4) == 0) { if ((mutt_str_strncasecmp("* OK [CAPABILITY", idata->buf, 16) != 0) && check_capabilities(idata)) { goto bail; } #ifdef USE_SSL /* Attempt STARTTLS if available and desired. */ if (!idata->conn->ssf && (SslForceTls || mutt_bit_isset(idata->capabilities, STARTTLS))) { int rc; if (SslForceTls) rc = MUTT_YES; else if ((rc = query_quadoption(SslStarttls, _("Secure connection with TLS?"))) == MUTT_ABORT) { goto err_close_conn; } if (rc == MUTT_YES) { rc = imap_exec(idata, "STARTTLS", IMAP_CMD_FAIL_OK); if (rc == -1) goto bail; if (rc != -2) { if (mutt_ssl_starttls(idata->conn)) { mutt_error(_("Could not negotiate TLS connection")); goto err_close_conn; } else { /* RFC2595 demands we recheck CAPABILITY after TLS completes. */ if (imap_exec(idata, "CAPABILITY", 0)) goto bail; } } } } if (SslForceTls && !idata->conn->ssf) { mutt_error(_("Encrypted connection unavailable")); goto err_close_conn; } #endif } else if (mutt_str_strncasecmp("* PREAUTH", idata->buf, 9) == 0) { idata->state = IMAP_AUTHENTICATED; if (check_capabilities(idata) != 0) goto bail; FREE(&idata->capstr); } else { imap_error("imap_open_connection()", buf); goto bail; } return 0; #ifdef USE_SSL err_close_conn: imap_close_connection(idata); #endif bail: FREE(&idata->capstr); return -1; } /** * imap_close_connection - Close an IMAP connection * @param idata Server data */ void imap_close_connection(struct ImapData *idata) { if (idata->state != IMAP_DISCONNECTED) { mutt_socket_close(idata->conn); idata->state = IMAP_DISCONNECTED; } idata->seqno = idata->nextcmd = idata->lastcmd = idata->status = false; memset(idata->cmds, 0, sizeof(struct ImapCommand) * idata->cmdslots); } /** * imap_logout - Gracefully log out of server * @param idata Server data */ void imap_logout(struct ImapData **idata) { /* we set status here to let imap_handle_untagged know we _expect_ to * receive a bye response (so it doesn't freak out and close the conn) */ (*idata)->status = IMAP_BYE; imap_cmd_start(*idata, "LOGOUT"); if (ImapPollTimeout <= 0 || mutt_socket_poll((*idata)->conn, ImapPollTimeout) != 0) { while (imap_cmd_step(*idata) == IMAP_CMD_CONTINUE) ; } mutt_socket_close((*idata)->conn); imap_free_idata(idata); } /** * imap_has_flag - Does the flag exist in the list * @param flag_list List of server flags * @param flag Flag to find * @retval true Flag exists * * Do a caseless comparison of the flag against a flag list, return true if * found or flag list has '\*'. */ bool imap_has_flag(struct ListHead *flag_list, const char *flag) { if (STAILQ_EMPTY(flag_list)) return false; struct ListNode *np; STAILQ_FOREACH(np, flag_list, entries) { if (mutt_str_strncasecmp(np->data, flag, strlen(np->data)) == 0) return true; if (mutt_str_strncmp(np->data, "\\*", strlen(np->data)) == 0) return true; } return false; } /** * imap_exec_msgset - Prepare commands for all messages matching conditions * @param idata ImapData containing context containing header set * @param pre prefix commands * @param post postfix commands * @param flag flag type on which to filter, e.g. MUTT_REPLIED * @param changed include only changed messages in message set * @param invert invert sense of flag, eg MUTT_READ matches unread messages * @retval num Matched messages * @retval -1 Failure * * pre/post: commands are of the form "%s %s %s %s", tag, pre, message set, post * Prepares commands for all messages matching conditions * (must be flushed with imap_exec) */ int imap_exec_msgset(struct ImapData *idata, const char *pre, const char *post, int flag, int changed, int invert) { struct Header **hdrs = NULL; short oldsort; int pos; int rc; int count = 0; struct Buffer *cmd = mutt_buffer_new(); /* We make a copy of the headers just in case resorting doesn't give exactly the original order (duplicate messages?), because other parts of the ctx are tied to the header order. This may be overkill. */ oldsort = Sort; if (Sort != SORT_ORDER) { hdrs = idata->ctx->hdrs; idata->ctx->hdrs = mutt_mem_malloc(idata->ctx->msgcount * sizeof(struct Header *)); memcpy(idata->ctx->hdrs, hdrs, idata->ctx->msgcount * sizeof(struct Header *)); Sort = SORT_ORDER; qsort(idata->ctx->hdrs, idata->ctx->msgcount, sizeof(struct Header *), mutt_get_sort_func(SORT_ORDER)); } pos = 0; do { cmd->dptr = cmd->data; mutt_buffer_printf(cmd, "%s ", pre); rc = make_msg_set(idata, cmd, flag, changed, invert, &pos); if (rc > 0) { mutt_buffer_printf(cmd, " %s", post); if (imap_exec(idata, cmd->data, IMAP_CMD_QUEUE)) { rc = -1; goto out; } count += rc; } } while (rc > 0); rc = count; out: mutt_buffer_free(&cmd); if (oldsort != Sort) { Sort = oldsort; FREE(&idata->ctx->hdrs); idata->ctx->hdrs = hdrs; } return rc; } /** * imap_sync_message_for_copy - Update server to reflect the flags of a single message * @param[in] idata Server data * @param[in] hdr Header of the email * @param[in] cmd Buffer for the command string * @param[out] err_continue Did the user force a continue? * @retval 0 Success * @retval -1 Failure * * Update the IMAP server to reflect the flags for a single message before * performing a "UID COPY". * * @note This does not sync the "deleted" flag state, because it is not * desirable to propagate that flag into the copy. */ int imap_sync_message_for_copy(struct ImapData *idata, struct Header *hdr, struct Buffer *cmd, int *err_continue) { char flags[LONG_STRING]; char *tags; char uid[11]; if (!compare_flags_for_copy(hdr)) { if (hdr->deleted == HEADER_DATA(hdr)->deleted) hdr->changed = false; return 0; } snprintf(uid, sizeof(uid), "%u", HEADER_DATA(hdr)->uid); cmd->dptr = cmd->data; mutt_buffer_addstr(cmd, "UID STORE "); mutt_buffer_addstr(cmd, uid); flags[0] = '\0'; set_flag(idata, MUTT_ACL_SEEN, hdr->read, "\\Seen ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, hdr->old, "Old ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, hdr->flagged, "\\Flagged ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, hdr->replied, "\\Answered ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_DELETE, HEADER_DATA(hdr)->deleted, "\\Deleted ", flags, sizeof(flags)); if (mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE)) { /* restore system flags */ if (HEADER_DATA(hdr)->flags_system) mutt_str_strcat(flags, sizeof(flags), HEADER_DATA(hdr)->flags_system); /* set custom flags */ tags = driver_tags_get_with_hidden(&hdr->tags); if (tags) { mutt_str_strcat(flags, sizeof(flags), tags); FREE(&tags); } } mutt_str_remove_trailing_ws(flags); /* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to * explicitly revoke all system flags (if we have permission) */ if (!*flags) { set_flag(idata, MUTT_ACL_SEEN, 1, "\\Seen ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, 1, "Old ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, 1, "\\Flagged ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, 1, "\\Answered ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_DELETE, !HEADER_DATA(hdr)->deleted, "\\Deleted ", flags, sizeof(flags)); /* erase custom flags */ if (mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE) && HEADER_DATA(hdr)->flags_remote) mutt_str_strcat(flags, sizeof(flags), HEADER_DATA(hdr)->flags_remote); mutt_str_remove_trailing_ws(flags); mutt_buffer_addstr(cmd, " -FLAGS.SILENT ("); } else mutt_buffer_addstr(cmd, " FLAGS.SILENT ("); mutt_buffer_addstr(cmd, flags); mutt_buffer_addstr(cmd, ")"); /* dumb hack for bad UW-IMAP 4.7 servers spurious FLAGS updates */ hdr->active = false; /* after all this it's still possible to have no flags, if you * have no ACL rights */ if (*flags && (imap_exec(idata, cmd->data, 0) != 0) && err_continue && (*err_continue != MUTT_YES)) { *err_continue = imap_continue("imap_sync_message: STORE failed", idata->buf); if (*err_continue != MUTT_YES) { hdr->active = true; return -1; } } /* server have now the updated flags */ FREE(&HEADER_DATA(hdr)->flags_remote); HEADER_DATA(hdr)->flags_remote = driver_tags_get_with_hidden(&hdr->tags); hdr->active = true; if (hdr->deleted == HEADER_DATA(hdr)->deleted) hdr->changed = false; return 0; } /** * imap_check_mailbox - use the NOOP or IDLE command to poll for new mail * @param ctx Context * @param force Don't wait * @retval #MUTT_REOPENED mailbox has been externally modified * @retval #MUTT_NEW_MAIL new mail has arrived * @retval 0 no change * @retval -1 error */ int imap_check_mailbox(struct Context *ctx, int force) { return imap_check(ctx->data, force); } /** * imap_check - Check for new mail * @param idata Server data * @param force Force a refresh * @retval >0 Success, e.g. #MUTT_REOPENED * @retval -1 Failure */ int imap_check(struct ImapData *idata, int force) { /* overload keyboard timeout to avoid many mailbox checks in a row. * Most users don't like having to wait exactly when they press a key. */ int result = 0; /* try IDLE first, unless force is set */ if (!force && ImapIdle && mutt_bit_isset(idata->capabilities, IDLE) && (idata->state != IMAP_IDLE || time(NULL) >= idata->lastread + ImapKeepalive)) { if (imap_cmd_idle(idata) < 0) return -1; } if (idata->state == IMAP_IDLE) { while ((result = mutt_socket_poll(idata->conn, 0)) > 0) { if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE) { mutt_debug(1, "Error reading IDLE response\n"); return -1; } } if (result < 0) { mutt_debug(1, "Poll failed, disabling IDLE\n"); mutt_bit_unset(idata->capabilities, IDLE); } } if ((force || (idata->state != IMAP_IDLE && time(NULL) >= idata->lastread + Timeout)) && imap_exec(idata, "NOOP", IMAP_CMD_POLL) != 0) { return -1; } /* We call this even when we haven't run NOOP in case we have pending * changes to process, since we can reopen here. */ imap_cmd_finish(idata); if (idata->check_status & IMAP_EXPUNGE_PENDING) result = MUTT_REOPENED; else if (idata->check_status & IMAP_NEWMAIL_PENDING) result = MUTT_NEW_MAIL; else if (idata->check_status & IMAP_FLAGS_PENDING) result = MUTT_FLAGS; idata->check_status = 0; return result; } /** * imap_buffy_check - Check for new mail in subscribed folders * @param check_stats Check for message stats too * @retval num Number of mailboxes with new mail * @retval 0 Failure * * Given a list of mailboxes rather than called once for each so that it can * batch the commands and save on round trips. */ int imap_buffy_check(int check_stats) { struct ImapData *idata = NULL; struct ImapData *lastdata = NULL; struct Buffy *mailbox = NULL; char name[LONG_STRING]; char command[LONG_STRING]; char munged[LONG_STRING]; int buffies = 0; for (mailbox = Incoming; mailbox; mailbox = mailbox->next) { /* Init newly-added mailboxes */ if (!mailbox->magic) { if (mx_is_imap(mailbox->path)) mailbox->magic = MUTT_IMAP; } if (mailbox->magic != MUTT_IMAP) continue; if (get_mailbox(mailbox->path, &idata, name, sizeof(name)) < 0) { mailbox->new = false; continue; } /* Don't issue STATUS on the selected mailbox, it will be NOOPed or * IDLEd elsewhere. * idata->mailbox may be NULL for connections other than the current * mailbox's, and shouldn't expand to INBOX in that case. #3216. */ if (idata->mailbox && (imap_mxcmp(name, idata->mailbox) == 0)) { mailbox->new = false; continue; } if (!mutt_bit_isset(idata->capabilities, IMAP4REV1) && !mutt_bit_isset(idata->capabilities, STATUS)) { mutt_debug(2, "Server doesn't support STATUS\n"); continue; } if (lastdata && idata != lastdata) { /* Send commands to previous server. Sorting the buffy list * may prevent some infelicitous interleavings */ if (imap_exec(lastdata, NULL, IMAP_CMD_FAIL_OK | IMAP_CMD_POLL) == -1) mutt_debug(1, "#1 Error polling mailboxes\n"); lastdata = NULL; } if (!lastdata) lastdata = idata; imap_munge_mbox_name(idata, munged, sizeof(munged), name); if (check_stats) { snprintf(command, sizeof(command), "STATUS %s (UIDNEXT UIDVALIDITY UNSEEN RECENT MESSAGES)", munged); } else { snprintf(command, sizeof(command), "STATUS %s (UIDNEXT UIDVALIDITY UNSEEN RECENT)", munged); } if (imap_exec(idata, command, IMAP_CMD_QUEUE | IMAP_CMD_POLL) < 0) { mutt_debug(1, "Error queueing command\n"); return 0; } } if (lastdata && (imap_exec(lastdata, NULL, IMAP_CMD_FAIL_OK | IMAP_CMD_POLL) == -1)) { mutt_debug(1, "#2 Error polling mailboxes\n"); return 0; } /* collect results */ for (mailbox = Incoming; mailbox; mailbox = mailbox->next) { if (mailbox->magic == MUTT_IMAP && mailbox->new) buffies++; } return buffies; } /** * imap_status - Get the status of a mailbox * @param path Path of mailbox * @param queue true if the command should be queued for the next call * @retval -1 Error * @retval >=0 Count of messages in mailbox * * If queue is true, the command will be sent now and be expected to have been * run on the next call (for pipelining the postponed count). */ int imap_status(char *path, int queue) { static int queued = 0; struct ImapData *idata = NULL; char buf[LONG_STRING]; char mbox[LONG_STRING]; struct ImapStatus *status = NULL; if (get_mailbox(path, &idata, buf, sizeof(buf)) < 0) return -1; /* We are in the folder we're polling - just return the mailbox count. * * Note that imap_mxcmp() converts NULL to "INBOX", so we need to * make sure the idata really is open to a folder. */ if (idata->ctx && !imap_mxcmp(buf, idata->mailbox)) return idata->ctx->msgcount; else if (mutt_bit_isset(idata->capabilities, IMAP4REV1) || mutt_bit_isset(idata->capabilities, STATUS)) { imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf); snprintf(buf, sizeof(buf), "STATUS %s (%s)", mbox, "MESSAGES"); imap_unmunge_mbox_name(idata, mbox); } else { /* Server does not support STATUS, and this is not the current mailbox. * There is no lightweight way to check recent arrivals */ return -1; } if (queue) { imap_exec(idata, buf, IMAP_CMD_QUEUE); queued = 1; return 0; } else if (!queued) imap_exec(idata, buf, 0); queued = 0; status = imap_mboxcache_get(idata, mbox, 0); if (status) return status->messages; return 0; } /** * imap_mboxcache_get - Open an hcache for a mailbox * @param idata Server data * @param mbox Mailbox to cache * @param create Should it be created if it doesn't exist? * @retval ptr Stats of cached mailbox * @retval ptr Stats of new cache entry * @retval NULL Not in cache and create is false * * return cached mailbox stats or NULL if create is 0 */ struct ImapStatus *imap_mboxcache_get(struct ImapData *idata, const char *mbox, bool create) { struct ImapStatus *status = NULL; #ifdef USE_HCACHE header_cache_t *hc = NULL; void *uidvalidity = NULL; void *uidnext = NULL; #endif struct ListNode *np; STAILQ_FOREACH(np, &idata->mboxcache, entries) { status = (struct ImapStatus *) np->data; if (imap_mxcmp(mbox, status->name) == 0) return status; } status = NULL; /* lame */ if (create) { struct ImapStatus *scache = mutt_mem_calloc(1, sizeof(struct ImapStatus)); scache->name = (char *) mbox; mutt_list_insert_tail(&idata->mboxcache, (char *) scache); status = imap_mboxcache_get(idata, mbox, 0); status->name = mutt_str_strdup(mbox); } #ifdef USE_HCACHE hc = imap_hcache_open(idata, mbox); if (hc) { uidvalidity = mutt_hcache_fetch_raw(hc, "/UIDVALIDITY", 12); uidnext = mutt_hcache_fetch_raw(hc, "/UIDNEXT", 8); if (uidvalidity) { if (!status) { mutt_hcache_free(hc, &uidvalidity); mutt_hcache_free(hc, &uidnext); mutt_hcache_close(hc); return imap_mboxcache_get(idata, mbox, 1); } status->uidvalidity = *(unsigned int *) uidvalidity; status->uidnext = uidnext ? *(unsigned int *) uidnext : 0; mutt_debug(3, "hcache uidvalidity %u, uidnext %u\n", status->uidvalidity, status->uidnext); } mutt_hcache_free(hc, &uidvalidity); mutt_hcache_free(hc, &uidnext); mutt_hcache_close(hc); } #endif return status; } /** * imap_mboxcache_free - Free the cached ImapStatus * @param idata Server data */ void imap_mboxcache_free(struct ImapData *idata) { struct ImapStatus *status = NULL; struct ListNode *np; STAILQ_FOREACH(np, &idata->mboxcache, entries) { status = (struct ImapStatus *) np->data; FREE(&status->name); } mutt_list_free(&idata->mboxcache); } /** * imap_search - Find a matching mailbox * @param ctx Context * @param pat Pattern to match * @retval 0 Success * @retval -1 Failure */ int imap_search(struct Context *ctx, const struct Pattern *pat) { struct Buffer buf; struct ImapData *idata = ctx->data; for (int i = 0; i < ctx->msgcount; i++) ctx->hdrs[i]->matched = false; if (do_search(pat, 1) == 0) return 0; mutt_buffer_init(&buf); mutt_buffer_addstr(&buf, "UID SEARCH "); if (compile_search(ctx, pat, &buf) < 0) { FREE(&buf.data); return -1; } if (imap_exec(idata, buf.data, 0) < 0) { FREE(&buf.data); return -1; } FREE(&buf.data); return 0; } /** * imap_subscribe - Subscribe to a mailbox * @param path Mailbox path * @param subscribe True: subscribe, false: unsubscribe * @retval 0 Success * @retval -1 Failure */ int imap_subscribe(char *path, bool subscribe) { struct ImapData *idata = NULL; char buf[LONG_STRING]; char mbox[LONG_STRING]; char errstr[STRING]; struct Buffer err, token; struct ImapMbox mx; size_t len = 0; if (!mx_is_imap(path) || imap_parse_path(path, &mx) || !mx.mbox) { mutt_error(_("Bad mailbox name")); return -1; } idata = imap_conn_find(&(mx.account), 0); if (!idata) goto fail; imap_fix_path(idata, mx.mbox, buf, sizeof(buf)); if (!*buf) mutt_str_strfcpy(buf, "INBOX", sizeof(buf)); if (ImapCheckSubscribed) { mutt_buffer_init(&token); mutt_buffer_init(&err); err.data = errstr; err.dsize = sizeof(errstr); len = snprintf(mbox, sizeof(mbox), "%smailboxes ", subscribe ? "" : "un"); imap_quote_string(mbox + len, sizeof(mbox) - len, path, true); if (mutt_parse_rc_line(mbox, &token, &err)) mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr); FREE(&token.data); } if (subscribe) mutt_message(_("Subscribing to %s..."), buf); else mutt_message(_("Unsubscribing from %s..."), buf); imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf); snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox); if (imap_exec(idata, buf, 0) < 0) goto fail; imap_unmunge_mbox_name(idata, mx.mbox); if (subscribe) mutt_message(_("Subscribed to %s"), mx.mbox); else mutt_message(_("Unsubscribed from %s"), mx.mbox); FREE(&mx.mbox); return 0; fail: FREE(&mx.mbox); return -1; } /** * imap_complete - Try to complete an IMAP folder path * @param buf Buffer for result * @param buflen Length of buffer * @param path Partial mailbox name to complete * @retval 0 Success * @retval -1 Failure * * Given a partial IMAP folder path, return a string which adds as much to the * path as is unique */ int imap_complete(char *buf, size_t buflen, char *path) { struct ImapData *idata = NULL; char list[LONG_STRING]; char tmp[LONG_STRING]; struct ImapList listresp; char completion[LONG_STRING]; int clen; size_t matchlen = 0; int completions = 0; struct ImapMbox mx; int rc; if (imap_parse_path(path, &mx)) { mutt_str_strfcpy(buf, path, buflen); return complete_hosts(buf, buflen); } /* don't open a new socket just for completion. Instead complete over * known mailboxes/hooks/etc */ idata = imap_conn_find(&(mx.account), MUTT_IMAP_CONN_NONEW); if (!idata) { FREE(&mx.mbox); mutt_str_strfcpy(buf, path, buflen); return complete_hosts(buf, buflen); } /* reformat path for IMAP list, and append wildcard */ /* don't use INBOX in place of "" */ if (mx.mbox && mx.mbox[0]) imap_fix_path(idata, mx.mbox, list, sizeof(list)); else list[0] = '\0'; /* fire off command */ snprintf(tmp, sizeof(tmp), "%s \"\" \"%s%%\"", ImapListSubscribed ? "LSUB" : "LIST", list); imap_cmd_start(idata, tmp); /* and see what the results are */ mutt_str_strfcpy(completion, NONULL(mx.mbox), sizeof(completion)); idata->cmdtype = IMAP_CT_LIST; idata->cmddata = &listresp; do { listresp.name = NULL; rc = imap_cmd_step(idata); if (rc == IMAP_CMD_CONTINUE && listresp.name) { /* if the folder isn't selectable, append delimiter to force browse * to enter it on second tab. */ if (listresp.noselect) { clen = strlen(listresp.name); listresp.name[clen++] = listresp.delim; listresp.name[clen] = '\0'; } /* copy in first word */ if (!completions) { mutt_str_strfcpy(completion, listresp.name, sizeof(completion)); matchlen = strlen(completion); completions++; continue; } matchlen = longest_common_prefix(completion, listresp.name, 0, matchlen); completions++; } } while (rc == IMAP_CMD_CONTINUE); idata->cmddata = NULL; if (completions) { /* reformat output */ imap_qualify_path(buf, buflen, &mx, completion); mutt_pretty_mailbox(buf, buflen); FREE(&mx.mbox); return 0; } return -1; } /** * imap_fast_trash - Use server COPY command to copy deleted messages to trash * @param ctx Context * @param dest Mailbox to move to * @retval -1 Error * @retval 0 Success * @retval 1 Non-fatal error - try fetch/append */ int imap_fast_trash(struct Context *ctx, char *dest) { char mbox[LONG_STRING]; char mmbox[LONG_STRING]; char prompt[LONG_STRING]; int rc; struct ImapMbox mx; bool triedcreate = false; struct Buffer *sync_cmd = NULL; int err_continue = MUTT_NO; struct ImapData *idata = ctx->data; if (imap_parse_path(dest, &mx)) { mutt_debug(1, "bad destination %s\n", dest); return -1; } /* check that the save-to folder is in the same account */ if (mutt_account_match(&(idata->conn->account), &(mx.account)) == 0) { mutt_debug(3, "%s not same server as %s\n", dest, ctx->path); return 1; } imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox)); if (!*mbox) mutt_str_strfcpy(mbox, "INBOX", sizeof(mbox)); imap_munge_mbox_name(idata, mmbox, sizeof(mmbox), mbox); sync_cmd = mutt_buffer_new(); for (int i = 0; i < ctx->msgcount; i++) { if (ctx->hdrs[i]->active && ctx->hdrs[i]->changed && ctx->hdrs[i]->deleted && !ctx->hdrs[i]->purge) { rc = imap_sync_message_for_copy(idata, ctx->hdrs[i], sync_cmd, &err_continue); if (rc < 0) { mutt_debug(1, "could not sync\n"); goto out; } } } /* loop in case of TRYCREATE */ do { rc = imap_exec_msgset(idata, "UID COPY", mmbox, MUTT_TRASH, 0, 0); if (!rc) { mutt_debug(1, "No messages to trash\n"); rc = -1; goto out; } else if (rc < 0) { mutt_debug(1, "could not queue copy\n"); goto out; } else { mutt_message(ngettext("Copying %d message to %s...", "Copying %d messages to %s...", rc), rc, mbox); } /* let's get it on */ rc = imap_exec(idata, NULL, IMAP_CMD_FAIL_OK); if (rc == -2) { if (triedcreate) { mutt_debug(1, "Already tried to create mailbox %s\n", mbox); break; } /* bail out if command failed for reasons other than nonexistent target */ if (mutt_str_strncasecmp(imap_get_qualifier(idata->buf), "[TRYCREATE]", 11) != 0) break; mutt_debug(3, "server suggests TRYCREATE\n"); snprintf(prompt, sizeof(prompt), _("Create %s?"), mbox); if (Confirmcreate && mutt_yesorno(prompt, 1) != MUTT_YES) { mutt_clear_error(); goto out; } if (imap_create_mailbox(idata, mbox) < 0) break; triedcreate = true; } } while (rc == -2); if (rc != 0) { imap_error("imap_fast_trash", idata->buf); goto out; } rc = 0; out: mutt_buffer_free(&sync_cmd); FREE(&mx.mbox); return (rc < 0) ? -1 : rc; } /** * imap_mbox_open - Implements MxOps::mbox_open() */ static int imap_mbox_open(struct Context *ctx) { struct ImapData *idata = NULL; struct ImapStatus *status = NULL; char buf[PATH_MAX]; char bufout[PATH_MAX]; int count = 0; struct ImapMbox mx, pmx; int rc; if (imap_parse_path(ctx->path, &mx)) { mutt_error(_("%s is an invalid IMAP path"), ctx->path); return -1; } /* we require a connection which isn't currently in IMAP_SELECTED state */ idata = imap_conn_find(&(mx.account), MUTT_IMAP_CONN_NOSELECT); if (!idata) goto fail_noidata; if (idata->state < IMAP_AUTHENTICATED) goto fail; /* once again the context is new */ ctx->data = idata; /* Clean up path and replace the one in the ctx */ imap_fix_path(idata, mx.mbox, buf, sizeof(buf)); if (!*buf) mutt_str_strfcpy(buf, "INBOX", sizeof(buf)); FREE(&(idata->mailbox)); idata->mailbox = mutt_str_strdup(buf); imap_qualify_path(buf, sizeof(buf), &mx, idata->mailbox); FREE(&(ctx->path)); FREE(&(ctx->realpath)); ctx->path = mutt_str_strdup(buf); ctx->realpath = mutt_str_strdup(ctx->path); idata->ctx = ctx; /* clear mailbox status */ idata->status = false; memset(idata->ctx->rights, 0, sizeof(idata->ctx->rights)); idata->new_mail_count = 0; idata->max_msn = 0; mutt_message(_("Selecting %s..."), idata->mailbox); imap_munge_mbox_name(idata, buf, sizeof(buf), idata->mailbox); /* pipeline ACL test */ if (mutt_bit_isset(idata->capabilities, ACL)) { snprintf(bufout, sizeof(bufout), "MYRIGHTS %s", buf); imap_exec(idata, bufout, IMAP_CMD_QUEUE); } /* assume we have all rights if ACL is unavailable */ else { mutt_bit_set(idata->ctx->rights, MUTT_ACL_LOOKUP); mutt_bit_set(idata->ctx->rights, MUTT_ACL_READ); mutt_bit_set(idata->ctx->rights, MUTT_ACL_SEEN); mutt_bit_set(idata->ctx->rights, MUTT_ACL_WRITE); mutt_bit_set(idata->ctx->rights, MUTT_ACL_INSERT); mutt_bit_set(idata->ctx->rights, MUTT_ACL_POST); mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE); mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE); } /* pipeline the postponed count if possible */ pmx.mbox = NULL; if (mx_is_imap(Postponed) && !imap_parse_path(Postponed, &pmx) && mutt_account_match(&pmx.account, &mx.account)) { imap_status(Postponed, 1); } FREE(&pmx.mbox); if (ImapCheckSubscribed) imap_exec(idata, "LSUB \"\" \"*\"", IMAP_CMD_QUEUE); snprintf(bufout, sizeof(bufout), "%s %s", ctx->readonly ? "EXAMINE" : "SELECT", buf); idata->state = IMAP_SELECTED; imap_cmd_start(idata, bufout); status = imap_mboxcache_get(idata, idata->mailbox, 1); do { char *pc = NULL; rc = imap_cmd_step(idata); if (rc != IMAP_CMD_CONTINUE) break; pc = idata->buf + 2; /* Obtain list of available flags here, may be overridden by a * PERMANENTFLAGS tag in the OK response */ if (mutt_str_strncasecmp("FLAGS", pc, 5) == 0) { /* don't override PERMANENTFLAGS */ if (STAILQ_EMPTY(&idata->flags)) { mutt_debug(3, "Getting mailbox FLAGS\n"); pc = get_flags(&idata->flags, pc); if (!pc) goto fail; } } /* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */ else if (mutt_str_strncasecmp("OK [PERMANENTFLAGS", pc, 18) == 0) { mutt_debug(3, "Getting mailbox PERMANENTFLAGS\n"); /* safe to call on NULL */ mutt_list_free(&idata->flags); /* skip "OK [PERMANENT" so syntax is the same as FLAGS */ pc += 13; pc = get_flags(&(idata->flags), pc); if (!pc) goto fail; } /* save UIDVALIDITY for the header cache */ else if (mutt_str_strncasecmp("OK [UIDVALIDITY", pc, 14) == 0) { mutt_debug(3, "Getting mailbox UIDVALIDITY\n"); pc += 3; pc = imap_next_word(pc); if (mutt_str_atoui(pc, &idata->uid_validity) < 0) goto fail; status->uidvalidity = idata->uid_validity; } else if (mutt_str_strncasecmp("OK [UIDNEXT", pc, 11) == 0) { mutt_debug(3, "Getting mailbox UIDNEXT\n"); pc += 3; pc = imap_next_word(pc); if (mutt_str_atoui(pc, &idata->uidnext) < 0) goto fail; status->uidnext = idata->uidnext; } else { pc = imap_next_word(pc); if (mutt_str_strncasecmp("EXISTS", pc, 6) == 0) { count = idata->new_mail_count; idata->new_mail_count = 0; } } } while (rc == IMAP_CMD_CONTINUE); if (rc == IMAP_CMD_NO) { char *s = imap_next_word(idata->buf); /* skip seq */ s = imap_next_word(s); /* Skip response */ mutt_error("%s", s); goto fail; } if (rc != IMAP_CMD_OK) goto fail; /* check for READ-ONLY notification */ if ((mutt_str_strncasecmp(imap_get_qualifier(idata->buf), "[READ-ONLY]", 11) == 0) && !mutt_bit_isset(idata->capabilities, ACL)) { mutt_debug(2, "Mailbox is read-only.\n"); ctx->readonly = true; } /* dump the mailbox flags we've found */ if (DebugLevel > 2) { if (STAILQ_EMPTY(&idata->flags)) mutt_debug(3, "No folder flags found\n"); else { struct ListNode *np; struct Buffer flag_buffer; mutt_buffer_init(&flag_buffer); mutt_buffer_printf(&flag_buffer, "Mailbox flags: "); STAILQ_FOREACH(np, &idata->flags, entries) { mutt_buffer_printf(&flag_buffer, "[%s] ", np->data); } mutt_debug(3, "%s\n", flag_buffer.data); FREE(&flag_buffer.data); } } if (!(mutt_bit_isset(idata->ctx->rights, MUTT_ACL_DELETE) || mutt_bit_isset(idata->ctx->rights, MUTT_ACL_SEEN) || mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE) || mutt_bit_isset(idata->ctx->rights, MUTT_ACL_INSERT))) { ctx->readonly = true; } ctx->hdrmax = count; ctx->hdrs = mutt_mem_calloc(count, sizeof(struct Header *)); ctx->v2r = mutt_mem_calloc(count, sizeof(int)); ctx->msgcount = 0; if (count && (imap_read_headers(idata, 1, count) < 0)) { mutt_error(_("Error opening mailbox")); goto fail; } mutt_debug(2, "msgcount is %d\n", ctx->msgcount); FREE(&mx.mbox); return 0; fail: if (idata->state == IMAP_SELECTED) idata->state = IMAP_AUTHENTICATED; fail_noidata: FREE(&mx.mbox); return -1; } /** * imap_mbox_open_append - Implements MxOps::mbox_open_append() */ static int imap_mbox_open_append(struct Context *ctx, int flags) { struct ImapData *idata = NULL; char mailbox[PATH_MAX]; struct ImapMbox mx; int rc; if (imap_parse_path(ctx->path, &mx)) return -1; /* in APPEND mode, we appear to hijack an existing IMAP connection - * ctx is brand new and mostly empty */ idata = imap_conn_find(&(mx.account), 0); if (!idata) { FREE(&mx.mbox); return -1; } ctx->data = idata; imap_fix_path(idata, mx.mbox, mailbox, sizeof(mailbox)); if (!*mailbox) mutt_str_strfcpy(mailbox, "INBOX", sizeof(mailbox)); FREE(&mx.mbox); rc = imap_access(ctx->path); if (rc == 0) return 0; if (rc == -1) return -1; char buf[PATH_MAX + 64]; snprintf(buf, sizeof(buf), _("Create %s?"), mailbox); if (Confirmcreate && mutt_yesorno(buf, 1) != MUTT_YES) return -1; if (imap_create_mailbox(idata, mailbox) < 0) return -1; return 0; } /** * imap_mbox_close - Implements MxOps::mbox_close() * @retval 0 Always */ static int imap_mbox_close(struct Context *ctx) { struct ImapData *idata = ctx->data; /* Check to see if the mailbox is actually open */ if (!idata) return 0; /* imap_mbox_open_append() borrows the struct ImapData temporarily, * just for the connection, but does not set idata->ctx to the * open-append ctx. * * So when these are equal, it means we are actually closing the * mailbox and should clean up idata. Otherwise, we don't want to * touch idata - it's still being used. */ if (ctx == idata->ctx) { if (idata->status != IMAP_FATAL && idata->state >= IMAP_SELECTED) { /* mx_mbox_close won't sync if there are no deleted messages * and the mailbox is unchanged, so we may have to close here */ if (!ctx->deleted) imap_exec(idata, "CLOSE", IMAP_CMD_QUEUE); idata->state = IMAP_AUTHENTICATED; } idata->reopen &= IMAP_REOPEN_ALLOW; FREE(&(idata->mailbox)); mutt_list_free(&idata->flags); idata->ctx = NULL; mutt_hash_destroy(&idata->uid_hash); FREE(&idata->msn_index); idata->msn_index_size = 0; idata->max_msn = 0; for (int i = 0; i < IMAP_CACHE_LEN; i++) { if (idata->cache[i].path) { unlink(idata->cache[i].path); FREE(&idata->cache[i].path); } } mutt_bcache_close(&idata->bcache); } /* free IMAP part of headers */ for (int i = 0; i < ctx->msgcount; i++) { /* mailbox may not have fully loaded */ if (ctx->hdrs[i] && ctx->hdrs[i]->data) imap_free_header_data((struct ImapHeaderData **) &(ctx->hdrs[i]->data)); } return 0; } /** * imap_msg_open_new - Implements MxOps::msg_open_new() */ static int imap_msg_open_new(struct Context *ctx, struct Message *msg, struct Header *hdr) { char tmp[PATH_MAX]; mutt_mktemp(tmp, sizeof(tmp)); msg->fp = mutt_file_fopen(tmp, "w"); if (!msg->fp) { mutt_perror(tmp); return -1; } msg->path = mutt_str_strdup(tmp); return 0; } /** * imap_mbox_check - Implements MxOps::mbox_check() * @param ctx Context * @param index_hint Remember our place in the index * @retval >0 Success, e.g. #MUTT_REOPENED * @retval -1 Failure */ static int imap_mbox_check(struct Context *ctx, int *index_hint) { int rc; (void) index_hint; imap_allow_reopen(ctx); rc = imap_check(ctx->data, 0); imap_disallow_reopen(ctx); return rc; } /** * imap_sync_mailbox - Sync all the changes to the server * @param ctx Context * @param expunge 0 or 1 - do expunge? * @retval 0 Success * @retval -1 Error */ int imap_sync_mailbox(struct Context *ctx, int expunge) { struct Context *appendctx = NULL; struct Header *h = NULL; struct Header **hdrs = NULL; int oldsort; int rc; struct ImapData *idata = ctx->data; if (idata->state < IMAP_SELECTED) { mutt_debug(2, "no mailbox selected\n"); return -1; } /* This function is only called when the calling code expects the context * to be changed. */ imap_allow_reopen(ctx); rc = imap_check(idata, 0); if (rc != 0) return rc; /* if we are expunging anyway, we can do deleted messages very quickly... */ if (expunge && mutt_bit_isset(ctx->rights, MUTT_ACL_DELETE)) { rc = imap_exec_msgset(idata, "UID STORE", "+FLAGS.SILENT (\\Deleted)", MUTT_DELETED, 1, 0); if (rc < 0) { mutt_error(_("Expunge failed")); goto out; } if (rc > 0) { /* mark these messages as unchanged so second pass ignores them. Done * here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */ for (int i = 0; i < ctx->msgcount; i++) if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->changed) ctx->hdrs[i]->active = false; mutt_message(ngettext("Marking %d message deleted...", "Marking %d messages deleted...", rc), rc); } } #ifdef USE_HCACHE idata->hcache = imap_hcache_open(idata, NULL); #endif /* save messages with real (non-flag) changes */ for (int i = 0; i < ctx->msgcount; i++) { h = ctx->hdrs[i]; if (h->deleted) { imap_cache_del(idata, h); #ifdef USE_HCACHE imap_hcache_del(idata, HEADER_DATA(h)->uid); #endif } if (h->active && h->changed) { #ifdef USE_HCACHE imap_hcache_put(idata, h); #endif /* if the message has been rethreaded or attachments have been deleted * we delete the message and reupload it. * This works better if we're expunging, of course. */ if ((h->env && (h->env->refs_changed || h->env->irt_changed)) || h->attach_del || h->xlabel_changed) { /* L10N: The plural is choosen by the last %d, i.e. the total number */ mutt_message(ngettext("Saving changed message... [%d/%d]", "Saving changed messages... [%d/%d]", ctx->msgcount), i + 1, ctx->msgcount); if (!appendctx) appendctx = mx_mbox_open(ctx->path, MUTT_APPEND | MUTT_QUIET, NULL); if (!appendctx) mutt_debug(1, "Error opening mailbox in append mode\n"); else mutt_save_message_ctx(h, 1, 0, 0, appendctx); h->xlabel_changed = false; } } } #ifdef USE_HCACHE imap_hcache_close(idata); #endif /* presort here to avoid doing 10 resorts in imap_exec_msgset */ oldsort = Sort; if (Sort != SORT_ORDER) { hdrs = ctx->hdrs; ctx->hdrs = mutt_mem_malloc(ctx->msgcount * sizeof(struct Header *)); memcpy(ctx->hdrs, hdrs, ctx->msgcount * sizeof(struct Header *)); Sort = SORT_ORDER; qsort(ctx->hdrs, ctx->msgcount, sizeof(struct Header *), mutt_get_sort_func(SORT_ORDER)); } rc = sync_helper(idata, MUTT_ACL_DELETE, MUTT_DELETED, "\\Deleted"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_WRITE, MUTT_FLAG, "\\Flagged"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_WRITE, MUTT_OLD, "Old"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_SEEN, MUTT_READ, "\\Seen"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_WRITE, MUTT_REPLIED, "\\Answered"); if (oldsort != Sort) { Sort = oldsort; FREE(&ctx->hdrs); ctx->hdrs = hdrs; } /* Flush the queued flags if any were changed in sync_helper. */ if (rc > 0) if (imap_exec(idata, NULL, 0) != IMAP_CMD_OK) rc = -1; if (rc < 0) { if (ctx->closing) { if (mutt_yesorno(_("Error saving flags. Close anyway?"), 0) == MUTT_YES) { rc = 0; idata->state = IMAP_AUTHENTICATED; goto out; } } else mutt_error(_("Error saving flags")); rc = -1; goto out; } /* Update local record of server state to reflect the synchronization just * completed. imap_read_headers always overwrites hcache-origin flags, so * there is no need to mutate the hcache after flag-only changes. */ for (int i = 0; i < ctx->msgcount; i++) { HEADER_DATA(ctx->hdrs[i])->deleted = ctx->hdrs[i]->deleted; HEADER_DATA(ctx->hdrs[i])->flagged = ctx->hdrs[i]->flagged; HEADER_DATA(ctx->hdrs[i])->old = ctx->hdrs[i]->old; HEADER_DATA(ctx->hdrs[i])->read = ctx->hdrs[i]->read; HEADER_DATA(ctx->hdrs[i])->replied = ctx->hdrs[i]->replied; ctx->hdrs[i]->changed = false; } ctx->changed = false; /* We must send an EXPUNGE command if we're not closing. */ if (expunge && !(ctx->closing) && mutt_bit_isset(ctx->rights, MUTT_ACL_DELETE)) { mutt_message(_("Expunging messages from server...")); /* Set expunge bit so we don't get spurious reopened messages */ idata->reopen |= IMAP_EXPUNGE_EXPECTED; if (imap_exec(idata, "EXPUNGE", 0) != 0) { idata->reopen &= ~IMAP_EXPUNGE_EXPECTED; imap_error(_("imap_sync_mailbox: EXPUNGE failed"), idata->buf); rc = -1; goto out; } idata->reopen &= ~IMAP_EXPUNGE_EXPECTED; } if (expunge && ctx->closing) { imap_exec(idata, "CLOSE", IMAP_CMD_QUEUE); idata->state = IMAP_AUTHENTICATED; } if (MessageCacheClean) imap_cache_clean(idata); rc = 0; out: if (appendctx) { mx_fastclose_mailbox(appendctx); FREE(&appendctx); } return rc; } /** * imap_tags_edit - Implements MxOps::tags_edit() */ static int imap_tags_edit(struct Context *ctx, const char *tags, char *buf, size_t buflen) { char *new = NULL; char *checker = NULL; struct ImapData *idata = (struct ImapData *) ctx->data; /* Check for \* flags capability */ if (!imap_has_flag(&idata->flags, NULL)) { mutt_error(_("IMAP server doesn't support custom flags")); return -1; } *buf = '\0'; if (tags) strncpy(buf, tags, buflen); if (mutt_get_field("Tags: ", buf, buflen, 0) != 0) return -1; /* each keyword must be atom defined by rfc822 as: * * atom = 1*<any CHAR except specials, SPACE and CTLs> * CHAR = ( 0.-127. ) * specials = "(" / ")" / "<" / ">" / "@" * / "," / ";" / ":" / "\" / <"> * / "." / "[" / "]" * SPACE = ( 32. ) * CTLS = ( 0.-31., 127.) * * And must be separated by one space. */ new = buf; checker = buf; SKIPWS(checker); while (*checker != '\0') { if (*checker < 32 || *checker >= 127 || // We allow space because it's the separator *checker == 40 || // ( *checker == 41 || // ) *checker == 60 || // < *checker == 62 || // > *checker == 64 || // @ *checker == 44 || // , *checker == 59 || // ; *checker == 58 || // : *checker == 92 || // backslash *checker == 34 || // " *checker == 46 || // . *checker == 91 || // [ *checker == 93) // ] { mutt_error(_("Invalid IMAP flags")); return 0; } /* Skip duplicate space */ while (*checker == ' ' && *(checker + 1) == ' ') checker++; /* copy char to new and go the next one */ *new ++ = *checker++; } *new = '\0'; new = buf; /* rewind */ mutt_str_remove_trailing_ws(new); if (mutt_str_strcmp(tags, buf) == 0) return 0; return 1; } /** * imap_tags_commit - Implements MxOps::tags_commit() * * This method update the server flags on the server by * removing the last know custom flags of a header * and adds the local flags * * If everything success we push the local flags to the * last know custom flags (flags_remote). * * Also this method check that each flags is support by the server * first and remove unsupported one. */ static int imap_tags_commit(struct Context *ctx, struct Header *hdr, char *buf) { struct Buffer *cmd = NULL; char uid[11]; struct ImapData *idata = ctx->data; if (*buf == '\0') buf = NULL; if (!mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE)) return 0; snprintf(uid, sizeof(uid), "%u", HEADER_DATA(hdr)->uid); /* Remove old custom flags */ if (HEADER_DATA(hdr)->flags_remote) { cmd = mutt_buffer_new(); if (!cmd) { mutt_debug(1, "unable to allocate buffer\n"); return -1; } cmd->dptr = cmd->data; mutt_buffer_addstr(cmd, "UID STORE "); mutt_buffer_addstr(cmd, uid); mutt_buffer_addstr(cmd, " -FLAGS.SILENT ("); mutt_buffer_addstr(cmd, HEADER_DATA(hdr)->flags_remote); mutt_buffer_addstr(cmd, ")"); /* Should we return here, or we are fine and we could * continue to add new flags * */ if (imap_exec(idata, cmd->data, 0) != 0) { mutt_buffer_free(&cmd); return -1; } mutt_buffer_free(&cmd); } /* Add new custom flags */ if (buf) { cmd = mutt_buffer_new(); if (!cmd) { mutt_debug(1, "fail to remove old flags\n"); return -1; } cmd->dptr = cmd->data; mutt_buffer_addstr(cmd, "UID STORE "); mutt_buffer_addstr(cmd, uid); mutt_buffer_addstr(cmd, " +FLAGS.SILENT ("); mutt_buffer_addstr(cmd, buf); mutt_buffer_addstr(cmd, ")"); if (imap_exec(idata, cmd->data, 0) != 0) { mutt_debug(1, "fail to add new flags\n"); mutt_buffer_free(&cmd); return -1; } mutt_buffer_free(&cmd); } /* We are good sync them */ mutt_debug(1, "NEW TAGS: %d\n", buf); driver_tags_replace(&hdr->tags, buf); FREE(&HEADER_DATA(hdr)->flags_remote); HEADER_DATA(hdr)->flags_remote = driver_tags_get_with_hidden(&hdr->tags); return 0; } // clang-format off /** * struct mx_imap_ops - Mailbox callback functions for IMAP mailboxes */ struct MxOps mx_imap_ops = { .mbox_open = imap_mbox_open, .mbox_open_append = imap_mbox_open_append, .mbox_check = imap_mbox_check, .mbox_sync = NULL, /* imap syncing is handled by imap_sync_mailbox */ .mbox_close = imap_mbox_close, .msg_open = imap_msg_open, .msg_open_new = imap_msg_open_new, .msg_commit = imap_msg_commit, .msg_close = imap_msg_close, .tags_edit = imap_tags_edit, .tags_commit = imap_tags_commit, }; // clang-format on
./CrossVul/dataset_final_sorted/CWE-77/c/good_248_0
crossvul-cpp_data_bad_2351_0
/* * read.c - read the blkid cache from disk, to avoid scanning all devices * * Copyright (C) 2001, 2003 Theodore Y. Ts'o * Copyright (C) 2001 Andreas Dilger * * %Begin-Header% * This file may be redistributed under the terms of the * GNU Lesser General Public License. * %End-Header% */ #include <stdio.h> #include <ctype.h> #include <string.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #ifdef HAVE_ERRNO_H #include <errno.h> #endif #include "blkidP.h" #ifdef HAVE_STDLIB_H # ifndef _XOPEN_SOURCE # define _XOPEN_SOURCE 600 /* for inclusion of strtoull */ # endif # include <stdlib.h> #endif #ifdef HAVE_STRTOULL #define STRTOULL strtoull /* defined in stdlib.h if you try hard enough */ #else /* FIXME: need to support real strtoull here */ #define STRTOULL strtoul #endif #ifdef TEST_PROGRAM #define blkid_debug_dump_dev(dev) (debug_dump_dev(dev)) static void debug_dump_dev(blkid_dev dev); #endif /* * File format: * * <device [<NAME="value"> ...]>device_name</device> * * The following tags are required for each entry: * <ID="id"> unique (within this file) ID number of this device * <TIME="sec.usec"> (time_t and suseconds_t) time this entry was last * read from disk * <TYPE="type"> (detected) type of filesystem/data for this partition * * The following tags may be present, depending on the device contents * <LABEL="label"> (user supplied) label (volume name, etc) * <UUID="uuid"> (generated) universally unique identifier (serial no) */ static char *skip_over_blank(char *cp) { while (*cp && isspace(*cp)) cp++; return cp; } static char *skip_over_word(char *cp) { char ch; while ((ch = *cp)) { /* If we see a backslash, skip the next character */ if (ch == '\\') { cp++; if (*cp == '\0') break; cp++; continue; } if (isspace(ch) || ch == '<' || ch == '>') break; cp++; } return cp; } static char *strip_line(char *line) { char *p; line = skip_over_blank(line); p = line + strlen(line) - 1; while (*line) { if (isspace(*p)) *p-- = '\0'; else break; } return line; } #if 0 static char *parse_word(char **buf) { char *word, *next; word = *buf; if (*word == '\0') return NULL; word = skip_over_blank(word); next = skip_over_word(word); if (*next) { char *end = next - 1; if (*end == '"' || *end == '\'') *end = '\0'; *next++ = '\0'; } *buf = next; if (*word == '"' || *word == '\'') word++; return word; } #endif /* * Start parsing a new line from the cache. * * line starts with "<device" return 1 -> continue parsing line * line starts with "<foo", empty, or # return 0 -> skip line * line starts with other, return -BLKID_ERR_CACHE -> error */ static int parse_start(char **cp) { char *p; p = strip_line(*cp); /* Skip comment or blank lines. We can't just NUL the first '#' char, * in case it is inside quotes, or escaped. */ if (*p == '\0' || *p == '#') return 0; if (!strncmp(p, "<device", 7)) { DBG(READ, ul_debug("found device header: %8s", p)); p += 7; *cp = p; return 1; } if (*p == '<') return 0; return -BLKID_ERR_CACHE; } /* Consume the remaining XML on the line (cosmetic only) */ static int parse_end(char **cp) { *cp = skip_over_blank(*cp); if (!strncmp(*cp, "</device>", 9)) { DBG(READ, ul_debug("found device trailer %9s", *cp)); *cp += 9; return 0; } return -BLKID_ERR_CACHE; } /* * Allocate a new device struct with device name filled in. Will handle * finding the device on lines of the form: * <device foo=bar>devname</device> * <device>devname<foo>bar</foo></device> */ static int parse_dev(blkid_cache cache, blkid_dev *dev, char **cp) { char *start, *tmp, *end, *name; int ret; if ((ret = parse_start(cp)) <= 0) return ret; start = tmp = strchr(*cp, '>'); if (!start) { DBG(READ, ul_debug("blkid: short line parsing dev: %s", *cp)); return -BLKID_ERR_CACHE; } start = skip_over_blank(start + 1); end = skip_over_word(start); DBG(READ, ul_debug("device should be %*s", (int)(end - start), start)); if (**cp == '>') *cp = end; else (*cp)++; *tmp = '\0'; if (!(tmp = strrchr(end, '<')) || parse_end(&tmp) < 0) { DBG(READ, ul_debug("blkid: missing </device> ending: %s", end)); } else if (tmp) *tmp = '\0'; if (end - start <= 1) { DBG(READ, ul_debug("blkid: empty device name: %s", *cp)); return -BLKID_ERR_CACHE; } name = strndup(start, end - start); if (name == NULL) return -BLKID_ERR_MEM; DBG(READ, ul_debug("found dev %s", name)); if (!(*dev = blkid_get_dev(cache, name, BLKID_DEV_CREATE))) { free(name); return -BLKID_ERR_MEM; } free(name); return 1; } /* * Extract a tag of the form NAME="value" from the line. */ static int parse_token(char **name, char **value, char **cp) { char *end; if (!name || !value || !cp) return -BLKID_ERR_PARAM; if (!(*value = strchr(*cp, '='))) return 0; **value = '\0'; *name = strip_line(*cp); *value = skip_over_blank(*value + 1); if (**value == '"') { end = strchr(*value + 1, '"'); if (!end) { DBG(READ, ul_debug("unbalanced quotes at: %s", *value)); *cp = *value; return -BLKID_ERR_CACHE; } (*value)++; *end = '\0'; end++; } else { end = skip_over_word(*value); if (*end) { *end = '\0'; end++; } } *cp = end; return 1; } /* * Extract a tag of the form <NAME>value</NAME> from the line. */ /* static int parse_xml(char **name, char **value, char **cp) { char *end; if (!name || !value || !cp) return -BLKID_ERR_PARAM; *name = strip_line(*cp); if ((*name)[0] != '<' || (*name)[1] == '/') return 0; FIXME: finish this. } */ /* * Extract a tag from the line. * * Return 1 if a valid tag was found. * Return 0 if no tag found. * Return -ve error code. */ static int parse_tag(blkid_cache cache, blkid_dev dev, char **cp) { char *name = NULL; char *value = NULL; int ret; if (!cache || !dev) return -BLKID_ERR_PARAM; if ((ret = parse_token(&name, &value, cp)) <= 0 /* && (ret = parse_xml(&name, &value, cp)) <= 0 */) return ret; /* Some tags are stored directly in the device struct */ if (!strcmp(name, "DEVNO")) dev->bid_devno = STRTOULL(value, 0, 0); else if (!strcmp(name, "PRI")) dev->bid_pri = strtol(value, 0, 0); else if (!strcmp(name, "TIME")) { char *end = NULL; dev->bid_time = STRTOULL(value, &end, 0); if (end && *end == '.') dev->bid_utime = STRTOULL(end + 1, 0, 0); } else ret = blkid_set_tag(dev, name, value, strlen(value)); DBG(READ, ul_debug(" tag: %s=\"%s\"", name, value)); return ret < 0 ? ret : 1; } /* * Parse a single line of data, and return a newly allocated dev struct. * Add the new device to the cache struct, if one was read. * * Lines are of the form <device [TAG="value" ...]>/dev/foo</device> * * Returns -ve value on error. * Returns 0 otherwise. * If a valid device was read, *dev_p is non-NULL, otherwise it is NULL * (e.g. comment lines, unknown XML content, etc). */ static int blkid_parse_line(blkid_cache cache, blkid_dev *dev_p, char *cp) { blkid_dev dev; int ret; if (!cache || !dev_p) return -BLKID_ERR_PARAM; *dev_p = NULL; DBG(READ, ul_debug("line: %s", cp)); if ((ret = parse_dev(cache, dev_p, &cp)) <= 0) return ret; dev = *dev_p; while ((ret = parse_tag(cache, dev, &cp)) > 0) { ; } if (dev->bid_type == NULL) { DBG(READ, ul_debug("blkid: device %s has no TYPE",dev->bid_name)); blkid_free_dev(dev); goto done; } DBG(READ, blkid_debug_dump_dev(dev)); done: return ret; } /* * Parse the specified filename, and return the data in the supplied or * a newly allocated cache struct. If the file doesn't exist, return a * new empty cache struct. */ void blkid_read_cache(blkid_cache cache) { FILE *file; char buf[4096]; int fd, lineno = 0; struct stat st; if (!cache) return; /* * If the file doesn't exist, then we just return an empty * struct so that the cache can be populated. */ if ((fd = open(cache->bic_filename, O_RDONLY|O_CLOEXEC)) < 0) return; if (fstat(fd, &st) < 0) goto errout; if ((st.st_mtime == cache->bic_ftime) || (cache->bic_flags & BLKID_BIC_FL_CHANGED)) { DBG(CACHE, ul_debug("skipping re-read of %s", cache->bic_filename)); goto errout; } DBG(CACHE, ul_debug("reading cache file %s", cache->bic_filename)); file = fdopen(fd, "r" UL_CLOEXECSTR); if (!file) goto errout; while (fgets(buf, sizeof(buf), file)) { blkid_dev dev; unsigned int end; lineno++; if (buf[0] == 0) continue; end = strlen(buf) - 1; /* Continue reading next line if it ends with a backslash */ while (end < (sizeof(buf) - 2) && buf[end] == '\\' && fgets(buf + end, sizeof(buf) - end, file)) { end = strlen(buf) - 1; lineno++; } if (blkid_parse_line(cache, &dev, buf) < 0) { DBG(READ, ul_debug("blkid: bad format on line %d", lineno)); continue; } } fclose(file); /* * Initially we do not need to write out the cache file. */ cache->bic_flags &= ~BLKID_BIC_FL_CHANGED; cache->bic_ftime = st.st_mtime; return; errout: close(fd); return; } #ifdef TEST_PROGRAM static void debug_dump_dev(blkid_dev dev) { struct list_head *p; if (!dev) { printf(" dev: NULL\n"); return; } printf(" dev: name = %s\n", dev->bid_name); printf(" dev: DEVNO=\"0x%0llx\"\n", (long long)dev->bid_devno); printf(" dev: TIME=\"%ld.%ld\"\n", (long)dev->bid_time, (long)dev->bid_utime); printf(" dev: PRI=\"%d\"\n", dev->bid_pri); printf(" dev: flags = 0x%08X\n", dev->bid_flags); list_for_each(p, &dev->bid_tags) { blkid_tag tag = list_entry(p, struct blkid_struct_tag, bit_tags); if (tag) printf(" tag: %s=\"%s\"\n", tag->bit_name, tag->bit_val); else printf(" tag: NULL\n"); } printf("\n"); } int main(int argc, char**argv) { blkid_cache cache = NULL; int ret; blkid_init_debug(BLKID_DEBUG_ALL); if (argc > 2) { fprintf(stderr, "Usage: %s [filename]\n" "Test parsing of the cache (filename)\n", argv[0]); exit(1); } if ((ret = blkid_get_cache(&cache, argv[1])) < 0) fprintf(stderr, "error %d reading cache file %s\n", ret, argv[1] ? argv[1] : blkid_get_cache_filename(NULL)); blkid_put_cache(cache); return ret; } #endif
./CrossVul/dataset_final_sorted/CWE-77/c/bad_2351_0
crossvul-cpp_data_good_1866_1
/* vi: set sw=4 ts=4: * * picocom.c * * simple dumb-terminal program. Helps you manually configure and test * stuff like modems, devices w. serial ports etc. * * by Nick Patavalis (npat@efault.net) * * 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 <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <assert.h> #include <stdarg.h> #include <signal.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <limits.h> #ifdef USE_FLOCK #include <sys/file.h> #endif #ifdef LINENOISE #include <dirent.h> #include <libgen.h> #endif #define _GNU_SOURCE #include <getopt.h> #include "split.h" #include "term.h" #ifdef LINENOISE #include "linenoise-1.0/linenoise.h" #endif /**********************************************************************/ /* parity modes names */ const char *parity_str[] = { [P_NONE] = "none", [P_EVEN] = "even", [P_ODD] = "odd", [P_MARK] = "mark", [P_SPACE] = "space", }; /* flow control modes names */ const char *flow_str[] = { [FC_NONE] = "none", [FC_RTSCTS] = "RTS/CTS", [FC_XONXOFF] = "xon/xoff", [FC_OTHER] = "other", }; /**********************************************************************/ #define KEY_EXIT '\x18' /* C-x: exit picocom */ #define KEY_QUIT '\x11' /* C-q: exit picocom without reseting port */ #define KEY_PULSE '\x10' /* C-p: pulse DTR */ #define KEY_TOGGLE '\x14' /* C-t: toggle DTR */ #define KEY_BAUD_UP '\x15' /* C-u: increase baudrate (up) */ #define KEY_BAUD_DN '\x04' /* C-d: decrase baudrate (down) */ #define KEY_FLOW '\x06' /* C-f: change flowcntrl mode */ #define KEY_PARITY '\x19' /* C-y: change parity mode */ #define KEY_BITS '\x02' /* C-b: change number of databits */ #define KEY_LECHO '\x03' /* C-c: toggle local echo */ #define KEY_STATUS '\x16' /* C-v: show program option */ #define KEY_SEND '\x13' /* C-s: send file */ #define KEY_RECEIVE '\x12' /* C-r: receive file */ #define KEY_BREAK '\x1c' /* C-\: break */ /**********************************************************************/ /* implemented caracter mappings */ #define M_CRLF (1 << 0) /* map CR --> LF */ #define M_CRCRLF (1 << 1) /* map CR --> CR + LF */ #define M_IGNCR (1 << 2) /* map CR --> <nothing> */ #define M_LFCR (1 << 3) /* map LF --> CR */ #define M_LFCRLF (1 << 4) /* map LF --> CR + LF */ #define M_IGNLF (1 << 5) /* map LF --> <nothing> */ #define M_DELBS (1 << 6) /* map DEL --> BS */ #define M_BSDEL (1 << 7) /* map BS --> DEL */ #define M_NFLAGS 8 /* default character mappings */ #define M_I_DFL 0 #define M_O_DFL 0 #define M_E_DFL (M_DELBS | M_CRCRLF) /* character mapping names */ struct map_names_s { char *name; int flag; } map_names[] = { { "crlf", M_CRLF }, { "crcrlf", M_CRCRLF }, { "igncr", M_IGNCR }, { "lfcr", M_LFCR }, { "lfcrlf", M_LFCRLF }, { "ignlf", M_IGNLF }, { "delbs", M_DELBS }, { "bsdel", M_BSDEL }, /* Sentinel */ { NULL, 0 } }; int parse_map (char *s) { char *m, *t; int f, flags, i; flags = 0; while ( (t = strtok(s, ", \t")) ) { for (i=0; (m = map_names[i].name); i++) { if ( ! strcmp(t, m) ) { f = map_names[i].flag; break; } } if ( m ) flags |= f; else { flags = -1; break; } s = NULL; } return flags; } void print_map (int flags) { int i; for (i = 0; i < M_NFLAGS; i++) if ( flags & (1 << i) ) printf("%s,", map_names[i].name); printf("\n"); } /**********************************************************************/ struct { char port[128]; int baud; enum flowcntrl_e flow; enum parity_e parity; int databits; int lecho; int noinit; int noreset; #if defined (UUCP_LOCK_DIR) || defined (USE_FLOCK) int nolock; #endif unsigned char escape; char send_cmd[128]; char receive_cmd[128]; int imap; int omap; int emap; } opts = { .port = "", .baud = 9600, .flow = FC_NONE, .parity = P_NONE, .databits = 8, .lecho = 0, .noinit = 0, .noreset = 0, #if defined (UUCP_LOCK_DIR) || defined (USE_FLOCK) .nolock = 0, #endif .escape = '\x01', .send_cmd = "sz -vv", .receive_cmd = "rz -vv", .imap = M_I_DFL, .omap = M_O_DFL, .emap = M_E_DFL }; int sig_exit = 0; #define STO STDOUT_FILENO #define STI STDIN_FILENO int tty_fd; #ifndef TTY_Q_SZ #define TTY_Q_SZ 256 #endif struct tty_q { int len; unsigned char buff[TTY_Q_SZ]; } tty_q; int tty_write_sz; #define TTY_WRITE_SZ_DIV 10 #define TTY_WRITE_SZ_MIN 8 #define set_tty_write_sz(baud) \ do { \ tty_write_sz = (baud) / TTY_WRITE_SZ_DIV; \ if ( tty_write_sz < TTY_WRITE_SZ_MIN ) \ tty_write_sz = TTY_WRITE_SZ_MIN; \ } while (0) /**********************************************************************/ #ifdef UUCP_LOCK_DIR /* use HDB UUCP locks .. see * <http://www.faqs.org/faqs/uucp-internals> for details */ char lockname[_POSIX_PATH_MAX] = ""; int uucp_lockname(const char *dir, const char *file) { char *p, *cp; struct stat sb; if ( ! dir || *dir == '\0' || stat(dir, &sb) != 0 ) return -1; /* cut-off initial "/dev/" from file-name */ p = strchr(file + 1, '/'); p = p ? p + 1 : (char *)file; /* replace '/'s with '_'s in what remains (after making a copy) */ p = cp = strdup(p); do { if ( *p == '/' ) *p = '_'; } while(*p++); /* build lockname */ snprintf(lockname, sizeof(lockname), "%s/LCK..%s", dir, cp); /* destroy the copy */ free(cp); return 0; } int uucp_lock(void) { int r, fd, pid; char buf[16]; mode_t m; if ( lockname[0] == '\0' ) return 0; fd = open(lockname, O_RDONLY); if ( fd >= 0 ) { r = read(fd, buf, sizeof(buf)); close(fd); /* if r == 4, lock file is binary (old-style) */ pid = (r == 4) ? *(int *)buf : strtol(buf, NULL, 10); if ( pid > 0 && kill((pid_t)pid, 0) < 0 && errno == ESRCH ) { /* stale lock file */ printf("Removing stale lock: %s\n", lockname); sleep(1); unlink(lockname); } else { lockname[0] = '\0'; errno = EEXIST; return -1; } } /* lock it */ m = umask(022); fd = open(lockname, O_WRONLY|O_CREAT|O_EXCL, 0666); if ( fd < 0 ) { lockname[0] = '\0'; return -1; } umask(m); snprintf(buf, sizeof(buf), "%04d\n", getpid()); write(fd, buf, strlen(buf)); close(fd); return 0; } int uucp_unlock(void) { if ( lockname[0] ) unlink(lockname); return 0; } #endif /* of UUCP_LOCK_DIR */ /**********************************************************************/ ssize_t writen_ni(int fd, const void *buff, size_t n) { size_t nl; ssize_t nw; const char *p; p = buff; nl = n; while (nl > 0) { do { nw = write(fd, p, nl); } while ( nw < 0 && errno == EINTR ); if ( nw <= 0 ) break; nl -= nw; p += nw; } return n - nl; } int fd_printf (int fd, const char *format, ...) { char buf[256]; va_list args; int len; va_start(args, format); len = vsnprintf(buf, sizeof(buf), format, args); buf[sizeof(buf) - 1] = '\0'; va_end(args); return writen_ni(fd, buf, len); } void fatal (const char *format, ...) { char *s, buf[256]; va_list args; int len; term_reset(STO); term_reset(STI); va_start(args, format); len = vsnprintf(buf, sizeof(buf), format, args); buf[sizeof(buf) - 1] = '\0'; va_end(args); s = "\r\nFATAL: "; writen_ni(STO, s, strlen(s)); writen_ni(STO, buf, len); s = "\r\n"; writen_ni(STO, s, strlen(s)); /* wait a bit for output to drain */ sleep(1); #ifdef UUCP_LOCK_DIR uucp_unlock(); #endif exit(EXIT_FAILURE); } /**********************************************************************/ #ifndef LINENOISE int cput(int fd, char c) { return write(fd, &c, 1); } int fd_readline (int fdi, int fdo, char *b, int bsz) { int r; unsigned char c; unsigned char *bp, *bpe; bp = (unsigned char *)b; bpe = (unsigned char *)b + bsz - 1; while (1) { r = read(fdi, &c, 1); if ( r <= 0 ) { r = -1; goto out; } switch (c) { case '\b': case '\x7f': if ( bp > (unsigned char *)b ) { bp--; cput(fdo, '\b'); cput(fdo, ' '); cput(fdo, '\b'); } else { cput(fdo, '\x07'); } break; case '\x03': /* CTRL-c */ r = -1; errno = EINTR; goto out; case '\r': *bp = '\0'; r = bp - (unsigned char *)b; goto out; default: if ( bp < bpe ) { *bp++ = c; cput(fdo, c); } else { cput(fdo, '\x07'); } break; } } out: return r; } char * read_filename (void) { char fname[_POSIX_PATH_MAX]; int r; fd_printf(STO, "\r\n*** file: "); r = fd_readline(STI, STO, fname, sizeof(fname)); fd_printf(STO, "\r\n"); if ( r < 0 ) return NULL; else return strdup(fname); } #else /* LINENOISE defined */ void file_completion_cb (const char *buf, linenoiseCompletions *lc) { DIR *dirp; struct dirent *dp; char *basec, *basen, *dirc, *dirn; int baselen, dirlen; char *fullpath; struct stat filestat; basec = strdup(buf); dirc = strdup(buf); dirn = dirname(dirc); dirlen = strlen(dirn); basen = basename(basec); baselen = strlen(basen); dirp = opendir(dirn); if (dirp) { while ((dp = readdir(dirp)) != NULL) { if (strncmp(basen, dp->d_name, baselen) == 0) { /* add 2 extra bytes for possible / in middle & at end */ fullpath = (char *) malloc(strlen(dp->d_name) + dirlen + 3); strcpy(fullpath, dirn); if (fullpath[dirlen-1] != '/') strcat(fullpath, "/"); strcat(fullpath, dp->d_name); if (stat(fullpath, &filestat) == 0) { if (S_ISDIR(filestat.st_mode)) { strcat(fullpath, "/"); } linenoiseAddCompletion(lc,fullpath); } free(fullpath); } } closedir(dirp); } free(basec); free(dirc); } static char *send_receive_history_file_path = NULL; void init_send_receive_history (void) { char *home_directory; home_directory = getenv("HOME"); if (home_directory) { send_receive_history_file_path = malloc(strlen(home_directory) + 2 + strlen(SEND_RECEIVE_HISTFILE)); strcpy(send_receive_history_file_path, home_directory); if (home_directory[strlen(home_directory)-1] != '/') { strcat(send_receive_history_file_path, "/"); } strcat(send_receive_history_file_path, SEND_RECEIVE_HISTFILE); linenoiseHistoryLoad(send_receive_history_file_path); } } void cleanup_send_receive_history (void) { if (send_receive_history_file_path) free(send_receive_history_file_path); } void add_send_receive_history (char *fname) { linenoiseHistoryAdd(fname); if (send_receive_history_file_path) linenoiseHistorySave(send_receive_history_file_path); } char * read_filename (void) { char *fname; linenoiseSetCompletionCallback(file_completion_cb); printf("\r\n"); fname = linenoise("*** file: "); printf("\r\n"); linenoiseSetCompletionCallback(NULL); if (fname != NULL) add_send_receive_history(fname); return fname; } #endif /* of ifndef LINENOISE */ /**********************************************************************/ /* maximum number of chars that can replace a single characted due to mapping */ #define M_MAXMAP 4 int do_map (char *b, int map, char c) { int n; switch (c) { case '\x7f': /* DEL mapings */ if ( map & M_DELBS ) { b[0] = '\x08'; n = 1; } else { b[0] = c; n = 1; } break; case '\x08': /* BS mapings */ if ( map & M_BSDEL ) { b[0] = '\x7f'; n = 1; } else { b[0] = c; n = 1; } break; case '\x0d': /* CR mappings */ if ( map & M_CRLF ) { b[0] = '\x0a'; n = 1; } else if ( map & M_CRCRLF ) { b[0] = '\x0d'; b[1] = '\x0a'; n = 2; } else if ( map & M_IGNCR ) { n = 0; } else { b[0] = c; n = 1; } break; case '\x0a': /* LF mappings */ if ( map & M_LFCR ) { b[0] = '\x0d'; n = 1; } else if ( map & M_LFCRLF ) { b[0] = '\x0d'; b[1] = '\x0a'; n = 2; } else if ( map & M_IGNLF ) { n = 0; } else { b[0] = c; n = 1; } break; default: b[0] = c; n = 1; break; } return n; } void map_and_write (int fd, int map, char c) { char b[M_MAXMAP]; int n; n = do_map(b, map, c); if ( n ) if ( writen_ni(fd, b, n) < n ) fatal("write to stdout failed: %s", strerror(errno)); } /**********************************************************************/ int baud_up (int baud) { return term_baud_up(baud); } int baud_down (int baud) { int nb; nb = term_baud_down(baud); if (nb == 0) nb = baud; return nb; } int flow_next (int flow) { switch(flow) { case FC_NONE: flow = FC_RTSCTS; break; case FC_RTSCTS: flow = FC_XONXOFF; break; case FC_XONXOFF: flow = FC_NONE; break; default: flow = FC_NONE; break; } return flow; } int parity_next (int parity) { switch(parity) { case P_NONE: parity = P_EVEN; break; case P_EVEN: parity = P_ODD; break; case P_ODD: parity = P_NONE; break; default: parity = P_NONE; break; } return parity; } int bits_next (int bits) { bits++; if (bits > 8) bits = 5; return bits; } void show_status (int dtr_up) { int baud, bits; enum flowcntrl_e flow; enum parity_e parity; term_refresh(tty_fd); baud = term_get_baudrate(tty_fd, NULL); flow = term_get_flowcntrl(tty_fd); parity = term_get_parity(tty_fd); bits = term_get_databits(tty_fd); fd_printf(STO, "\r\n"); if ( baud != opts.baud ) { fd_printf(STO, "*** baud: %d (%d)\r\n", opts.baud, baud); } else { fd_printf(STO, "*** baud: %d\r\n", opts.baud); } if ( flow != opts.flow ) { fd_printf(STO, "*** flow: %s (%s)\r\n", flow_str[opts.flow], flow_str[flow]); } else { fd_printf(STO, "*** flow: %s\r\n", flow_str[opts.flow]); } if ( parity != opts.parity ) { fd_printf(STO, "*** parity: %s (%s)\r\n", parity_str[opts.parity], parity_str[parity]); } else { fd_printf(STO, "*** parity: %s\r\n", parity_str[opts.parity]); } if ( bits != opts.databits ) { fd_printf(STO, "*** databits: %d (%d)\r\n", opts.databits, bits); } else { fd_printf(STO, "*** databits: %d\r\n", opts.databits); } fd_printf(STO, "*** dtr: %s\r\n", dtr_up ? "up" : "down"); } /**********************************************************************/ #define RUNCMD_ARGS_MAX 32 #define RUNCMD_EXEC_FAIL 126 void establish_child_signal_handlers (void) { struct sigaction dfl_action; /* Set up the structure to specify the default action. */ dfl_action.sa_handler = SIG_DFL; sigemptyset (&dfl_action.sa_mask); dfl_action.sa_flags = 0; sigaction (SIGINT, &dfl_action, NULL); sigaction (SIGTERM, &dfl_action, NULL); } int run_cmd(int fd, const char *cmd, const char *args_extra) { pid_t pid; sigset_t sigm, sigm_old; /* block signals, let child establish its own handlers */ sigemptyset(&sigm); sigaddset(&sigm, SIGTERM); sigprocmask(SIG_BLOCK, &sigm, &sigm_old); pid = fork(); if ( pid < 0 ) { sigprocmask(SIG_SETMASK, &sigm_old, NULL); fd_printf(STO, "*** cannot fork: %s ***\r\n", strerror(errno)); return -1; } else if ( pid ) { /* father: picocom */ int status, r; /* reset the mask */ sigprocmask(SIG_SETMASK, &sigm_old, NULL); /* wait for child to finish */ do { r = waitpid(pid, &status, 0); } while ( r < 0 && errno == EINTR ); /* reset terminal (back to raw mode) */ term_apply(STI); /* check and report child return status */ if ( WIFEXITED(status) ) { fd_printf(STO, "\r\n*** exit status: %d ***\r\n", WEXITSTATUS(status)); return WEXITSTATUS(status); } else if ( WIFSIGNALED(status) ) { fd_printf(STO, "\r\n*** killed by signal: %d ***\r\n", WTERMSIG(status)); return -1; } else { fd_printf(STO, "\r\n*** abnormal termination: 0x%x ***\r\n", r); return -1; } } else { /* child: external program */ long fl; int argc; char *argv[RUNCMD_ARGS_MAX + 1]; int r; /* unmanage terminal, and reset it to canonical mode */ term_remove(STI); /* unmanage serial port fd, without reset */ term_erase(fd); /* set serial port fd to blocking mode */ fl = fcntl(fd, F_GETFL); fl &= ~O_NONBLOCK; fcntl(fd, F_SETFL, fl); /* connect stdin and stdout to serial port */ close(STI); close(STO); dup2(fd, STI); dup2(fd, STO); /* build command arguments vector */ argc = 0; r = split_quoted(cmd, &argc, argv, RUNCMD_ARGS_MAX); if ( r < 0 ) { fd_printf(STDERR_FILENO, "Cannot parse command\n"); exit(RUNCMD_EXEC_FAIL); } r = split_quoted(args_extra, &argc, argv, RUNCMD_ARGS_MAX); if ( r < 0 ) { fd_printf(STDERR_FILENO, "Cannot parse extra args\n"); exit(RUNCMD_EXEC_FAIL); } if ( argc < 1 ) { fd_printf(STDERR_FILENO, "No command given\n"); exit(RUNCMD_EXEC_FAIL); } argv[argc] = NULL; /* run extenral command */ fd_printf(STDERR_FILENO, "$ %s %s\n", cmd, args_extra); establish_child_signal_handlers(); sigprocmask(SIG_SETMASK, &sigm_old, NULL); execvp(argv[0], argv); fd_printf(STDERR_FILENO, "exec: %s\n", strerror(errno)); exit(RUNCMD_EXEC_FAIL); } } /**********************************************************************/ /* Process command key. Returns non-zero if command results in picocom exit, zero otherwise. */ int do_command (unsigned char c) { static int dtr_up = 0; int newbaud, newflow, newparity, newbits; const char *xfr_cmd; char *fname; int r; switch (c) { case KEY_EXIT: return 1; case KEY_QUIT: term_set_hupcl(tty_fd, 0); term_flush(tty_fd); term_apply(tty_fd); term_erase(tty_fd); return 1; case KEY_STATUS: show_status(dtr_up); break; case KEY_PULSE: fd_printf(STO, "\r\n*** pulse DTR ***\r\n"); if ( term_pulse_dtr(tty_fd) < 0 ) fd_printf(STO, "*** FAILED\r\n"); break; case KEY_TOGGLE: if ( dtr_up ) r = term_lower_dtr(tty_fd); else r = term_raise_dtr(tty_fd); if ( r >= 0 ) dtr_up = ! dtr_up; fd_printf(STO, "\r\n*** DTR: %s ***\r\n", dtr_up ? "up" : "down"); break; case KEY_BAUD_UP: case KEY_BAUD_DN: if (c == KEY_BAUD_UP) opts.baud = baud_up(opts.baud); else opts.baud = baud_down(opts.baud); term_set_baudrate(tty_fd, opts.baud); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newbaud = term_get_baudrate(tty_fd, NULL); if ( opts.baud != newbaud ) { fd_printf(STO, "\r\n*** baud: %d (%d) ***\r\n", opts.baud, newbaud); } else { fd_printf(STO, "\r\n*** baud: %d ***\r\n", opts.baud); } set_tty_write_sz(newbaud); break; case KEY_FLOW: opts.flow = flow_next(opts.flow); term_set_flowcntrl(tty_fd, opts.flow); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newflow = term_get_flowcntrl(tty_fd); if ( opts.flow != newflow ) { fd_printf(STO, "\r\n*** flow: %s (%s) ***\r\n", flow_str[opts.flow], flow_str[newflow]); } else { fd_printf(STO, "\r\n*** flow: %s ***\r\n", flow_str[opts.flow]); } break; case KEY_PARITY: opts.parity = parity_next(opts.parity); term_set_parity(tty_fd, opts.parity); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newparity = term_get_parity(tty_fd); if (opts.parity != newparity ) { fd_printf(STO, "\r\n*** parity: %s (%s) ***\r\n", parity_str[opts.parity], parity_str[newparity]); } else { fd_printf(STO, "\r\n*** parity: %s ***\r\n", parity_str[opts.parity]); } break; case KEY_BITS: opts.databits = bits_next(opts.databits); term_set_databits(tty_fd, opts.databits); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newbits = term_get_databits(tty_fd); if (opts.databits != newbits ) { fd_printf(STO, "\r\n*** databits: %d (%d) ***\r\n", opts.databits, newbits); } else { fd_printf(STO, "\r\n*** databits: %d ***\r\n", opts.databits); } break; case KEY_LECHO: opts.lecho = ! opts.lecho; fd_printf(STO, "\r\n*** local echo: %s ***\r\n", opts.lecho ? "yes" : "no"); break; case KEY_SEND: case KEY_RECEIVE: xfr_cmd = (c == KEY_SEND) ? opts.send_cmd : opts.receive_cmd; if ( xfr_cmd[0] == '\0' ) { fd_printf(STO, "\r\n*** command disabled ***\r\n"); break; } fname = read_filename(); if (fname == NULL) { fd_printf(STO, "*** cannot read filename ***\r\n"); break; } run_cmd(tty_fd, xfr_cmd, fname); free(fname); break; case KEY_BREAK: term_break(tty_fd); fd_printf(STO, "\r\n*** break sent ***\r\n"); break; default: break; } return 0; } /**********************************************************************/ void loop(void) { enum { ST_COMMAND, ST_TRANSPARENT } state; fd_set rdset, wrset; int r, n; unsigned char c; tty_q.len = 0; state = ST_TRANSPARENT; while ( ! sig_exit ) { FD_ZERO(&rdset); FD_ZERO(&wrset); FD_SET(STI, &rdset); FD_SET(tty_fd, &rdset); if ( tty_q.len ) FD_SET(tty_fd, &wrset); r = select(tty_fd + 1, &rdset, &wrset, NULL, NULL); if ( r < 0 ) { if ( errno == EINTR ) continue; else fatal("select failed: %d : %s", errno, strerror(errno)); } if ( FD_ISSET(STI, &rdset) ) { /* read from terminal */ do { n = read(STI, &c, 1); } while (n < 0 && errno == EINTR); if (n == 0) { fatal("stdin closed"); } else if (n < 0) { /* is this really necessary? better safe than sory! */ if ( errno != EAGAIN && errno != EWOULDBLOCK ) fatal("read from stdin failed: %s", strerror(errno)); else goto skip_proc_STI; } switch (state) { case ST_COMMAND: if ( c == opts.escape ) { /* pass the escape character down */ if (tty_q.len + M_MAXMAP <= TTY_Q_SZ) { n = do_map((char *)tty_q.buff + tty_q.len, opts.omap, c); tty_q.len += n; if ( opts.lecho ) map_and_write(STO, opts.emap, c); } else { fd_printf(STO, "\x07"); } } else { /* process command key */ if ( do_command(c) ) /* picocom exit */ return; } state = ST_TRANSPARENT; break; case ST_TRANSPARENT: if ( c == opts.escape ) { state = ST_COMMAND; } else { if (tty_q.len + M_MAXMAP <= TTY_Q_SZ) { n = do_map((char *)tty_q.buff + tty_q.len, opts.omap, c); tty_q.len += n; if ( opts.lecho ) map_and_write(STO, opts.emap, c); } else fd_printf(STO, "\x07"); } break; default: assert(0); break; } } skip_proc_STI: if ( FD_ISSET(tty_fd, &rdset) ) { /* read from port */ do { n = read(tty_fd, &c, 1); } while (n < 0 && errno == EINTR); if (n == 0) { fatal("term closed"); } else if ( n < 0 ) { if ( errno != EAGAIN && errno != EWOULDBLOCK ) fatal("read from term failed: %s", strerror(errno)); } else { map_and_write(STO, opts.imap, c); } } if ( FD_ISSET(tty_fd, &wrset) ) { /* write to port */ int sz; sz = (tty_q.len < tty_write_sz) ? tty_q.len : tty_write_sz; do { n = write(tty_fd, tty_q.buff, sz); } while ( n < 0 && errno == EINTR ); if ( n <= 0 ) fatal("write to term failed: %s", strerror(errno)); memmove(tty_q.buff, tty_q.buff + n, tty_q.len - n); tty_q.len -= n; } } } /**********************************************************************/ void deadly_handler(int signum) { if ( ! sig_exit ) { sig_exit = 1; kill(0, SIGTERM); } } void establish_signal_handlers (void) { struct sigaction exit_action, ign_action; /* Set up the structure to specify the exit action. */ exit_action.sa_handler = deadly_handler; sigemptyset (&exit_action.sa_mask); exit_action.sa_flags = 0; /* Set up the structure to specify the ignore action. */ ign_action.sa_handler = SIG_IGN; sigemptyset (&ign_action.sa_mask); ign_action.sa_flags = 0; sigaction (SIGTERM, &exit_action, NULL); sigaction (SIGINT, &ign_action, NULL); sigaction (SIGHUP, &ign_action, NULL); sigaction (SIGQUIT, &ign_action, NULL); sigaction (SIGALRM, &ign_action, NULL); sigaction (SIGUSR1, &ign_action, NULL); sigaction (SIGUSR2, &ign_action, NULL); sigaction (SIGPIPE, &ign_action, NULL); } /**********************************************************************/ void show_usage(char *name) { char *s; s = strrchr(name, '/'); s = s ? s+1 : name; printf("picocom v%s\n", VERSION_STR); printf("\nCompiled-in options:\n"); printf(" TTY_Q_SZ is %d\n", TTY_Q_SZ); #ifdef USE_HIGH_BAUD printf(" HIGH_BAUD is enabled\n"); #endif #ifdef USE_FLOCK printf(" USE_FLOCK is enabled\n"); #endif #ifdef UUCP_LOCK_DIR printf(" UUCP_LOCK_DIR is: %s\n", UUCP_LOCK_DIR); #endif #ifdef LINENOISE printf(" LINENOISE is enabled\n"); printf(" SEND_RECEIVE_HISTFILE is: %s\n", SEND_RECEIVE_HISTFILE); #endif printf("\nUsage is: %s [options] <tty device>\n", s); printf("Options are:\n"); printf(" --<b>aud <baudrate>\n"); printf(" --<f>low s (=soft) | h (=hard) | n (=none)\n"); printf(" --<p>arity o (=odd) | e (=even) | n (=none)\n"); printf(" --<d>atabits 5 | 6 | 7 | 8\n"); printf(" --<e>scape <char>\n"); printf(" --e<c>ho\n"); printf(" --no<i>nit\n"); printf(" --no<r>eset\n"); printf(" --no<l>ock\n"); printf(" --<s>end-cmd <command>\n"); printf(" --recei<v>e-cmd <command>\n"); printf(" --imap <map> (input mappings)\n"); printf(" --omap <map> (output mappings)\n"); printf(" --emap <map> (local-echo mappings)\n"); printf(" --<h>elp\n"); printf("<map> is a comma-separated list of one or more of:\n"); printf(" crlf : map CR --> LF\n"); printf(" crcrlf : map CR --> CR + LF\n"); printf(" igncr : ignore CR\n"); printf(" lfcr : map LF --> CR\n"); printf(" lfcrlf : map LF --> CR + LF\n"); printf(" ignlf : ignore LF\n"); printf(" bsdel : map BS --> DEL\n"); printf(" delbs : map DEL --> BS\n"); printf("<?> indicates the equivalent short option.\n"); printf("Short options are prefixed by \"-\" instead of by \"--\".\n"); } /**********************************************************************/ void parse_args(int argc, char *argv[]) { int r; static struct option longOptions[] = { {"receive-cmd", required_argument, 0, 'v'}, {"send-cmd", required_argument, 0, 's'}, {"imap", required_argument, 0, 'I' }, {"omap", required_argument, 0, 'O' }, {"emap", required_argument, 0, 'E' }, {"escape", required_argument, 0, 'e'}, {"echo", no_argument, 0, 'c'}, {"noinit", no_argument, 0, 'i'}, {"noreset", no_argument, 0, 'r'}, {"nolock", no_argument, 0, 'l'}, {"flow", required_argument, 0, 'f'}, {"baud", required_argument, 0, 'b'}, {"parity", required_argument, 0, 'p'}, {"databits", required_argument, 0, 'd'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; r = 0; while (1) { int optionIndex = 0; int c; int map; /* no default error messages printed. */ opterr = 0; c = getopt_long(argc, argv, "hirlcv:s:r:e:f:b:p:d:", longOptions, &optionIndex); if (c < 0) break; switch (c) { case 's': strncpy(opts.send_cmd, optarg, sizeof(opts.send_cmd)); opts.send_cmd[sizeof(opts.send_cmd) - 1] = '\0'; break; case 'v': strncpy(opts.receive_cmd, optarg, sizeof(opts.receive_cmd)); opts.receive_cmd[sizeof(opts.receive_cmd) - 1] = '\0'; break; case 'I': map = parse_map(optarg); if (map >= 0) opts.imap = map; else { fprintf(stderr, "Invalid --imap\n"); r = -1; } break; case 'O': map = parse_map(optarg); if (map >= 0) opts.omap = map; else { fprintf(stderr, "Invalid --omap\n"); r = -1; } break; case 'E': map = parse_map(optarg); if (map >= 0) opts.emap = map; else { fprintf(stderr, "Invalid --emap\n"); r = -1; } break; case 'c': opts.lecho = 1; break; case 'i': opts.noinit = 1; break; case 'r': opts.noreset = 1; break; case 'l': #if defined (UUCP_LOCK_DIR) || defined (USE_FLOCK) opts.nolock = 1; #endif break; case 'e': opts.escape = optarg[0] & 0x1f; break; case 'f': switch (optarg[0]) { case 'X': case 'x': opts.flow = FC_XONXOFF; break; case 'H': case 'h': opts.flow = FC_RTSCTS; break; case 'N': case 'n': opts.flow = FC_NONE; break; default: fprintf(stderr, "Invalid --flow: %c\n", optarg[0]); r = -1; break; } break; case 'b': opts.baud = atoi(optarg); break; case 'p': switch (optarg[0]) { case 'e': opts.parity = P_EVEN; break; case 'o': opts.parity = P_ODD; break; case 'n': opts.parity = P_NONE; break; default: fprintf(stderr, "Invalid --parity: %c\n", optarg[0]); r = -1; break; } break; case 'd': switch (optarg[0]) { case '5': opts.databits = 5; break; case '6': opts.databits = 6; break; case '7': opts.databits = 7; break; case '8': opts.databits = 8; break; default: fprintf(stderr, "Invalid --databits: %c\n", optarg[0]); r = -1; break; } break; case 'h': show_usage(argv[0]); exit(EXIT_SUCCESS); case '?': default: fprintf(stderr, "Unrecognized option(s)\n"); r = -1; break; } if ( r < 0 ) { fprintf(stderr, "Run with '--help'.\n"); exit(EXIT_FAILURE); } } /* while */ if ( (argc - optind) < 1) { fprintf(stderr, "No port given\n"); fprintf(stderr, "Run with '--help'.\n"); exit(EXIT_FAILURE); } strncpy(opts.port, argv[optind], sizeof(opts.port) - 1); opts.port[sizeof(opts.port) - 1] = '\0'; printf("picocom v%s\n", VERSION_STR); printf("\n"); printf("port is : %s\n", opts.port); printf("flowcontrol : %s\n", flow_str[opts.flow]); printf("baudrate is : %d\n", opts.baud); printf("parity is : %s\n", parity_str[opts.parity]); printf("databits are : %d\n", opts.databits); printf("escape is : C-%c\n", 'a' + opts.escape - 1); printf("local echo is : %s\n", opts.lecho ? "yes" : "no"); printf("noinit is : %s\n", opts.noinit ? "yes" : "no"); printf("noreset is : %s\n", opts.noreset ? "yes" : "no"); #if defined (UUCP_LOCK_DIR) || defined (USE_FLOCK) printf("nolock is : %s\n", opts.nolock ? "yes" : "no"); #endif printf("send_cmd is : %s\n", (opts.send_cmd[0] == '\0') ? "disabled" : opts.send_cmd); printf("receive_cmd is : %s\n", (opts.receive_cmd[0] == '\0') ? "disabled" : opts.receive_cmd); printf("imap is : "); print_map(opts.imap); printf("omap is : "); print_map(opts.omap); printf("emap is : "); print_map(opts.emap); printf("\n"); } /**********************************************************************/ int main(int argc, char *argv[]) { int r; parse_args(argc, argv); establish_signal_handlers(); r = term_lib_init(); if ( r < 0 ) fatal("term_init failed: %s", term_strerror(term_errno, errno)); #ifdef UUCP_LOCK_DIR if ( ! opts.nolock ) uucp_lockname(UUCP_LOCK_DIR, opts.port); if ( uucp_lock() < 0 ) fatal("cannot lock %s: %s", opts.port, strerror(errno)); #endif tty_fd = open(opts.port, O_RDWR | O_NONBLOCK | O_NOCTTY); if (tty_fd < 0) fatal("cannot open %s: %s", opts.port, strerror(errno)); #ifdef USE_FLOCK if ( ! opts.nolock ) { r = flock(tty_fd, LOCK_EX | LOCK_NB); if ( r < 0 ) fatal("cannot lock %s: %s", opts.port, strerror(errno)); } #endif if ( opts.noinit ) { r = term_add(tty_fd); } else { r = term_set(tty_fd, 1, /* raw mode. */ opts.baud, /* baud rate. */ opts.parity, /* parity. */ opts.databits, /* data bits. */ opts.flow, /* flow control. */ 1, /* local or modem */ !opts.noreset); /* hup-on-close. */ } if ( r < 0 ) fatal("failed to add device %s: %s", opts.port, term_strerror(term_errno, errno)); r = term_apply(tty_fd); if ( r < 0 ) fatal("failed to config device %s: %s", opts.port, term_strerror(term_errno, errno)); set_tty_write_sz(term_get_baudrate(tty_fd, NULL)); r = term_add(STI); if ( r < 0 ) fatal("failed to add I/O device: %s", term_strerror(term_errno, errno)); term_set_raw(STI); r = term_apply(STI); if ( r < 0 ) fatal("failed to set I/O device to raw mode: %s", term_strerror(term_errno, errno)); #ifdef LINENOISE init_send_receive_history(); #endif fd_printf(STO, "Terminal ready\r\n"); loop(); #ifdef LINENOISE cleanup_send_receive_history(); #endif fd_printf(STO, "\r\n"); if ( opts.noreset ) { fd_printf(STO, "Skipping tty reset...\r\n"); term_erase(tty_fd); } if ( sig_exit ) fd_printf(STO, "Picocom was killed\r\n"); else fd_printf(STO, "Thanks for using picocom\r\n"); /* wait a bit for output to drain */ sleep(1); #ifdef UUCP_LOCK_DIR uucp_unlock(); #endif return EXIT_SUCCESS; } /**********************************************************************/ /* * Local Variables: * mode:c * tab-width: 4 * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-77/c/good_1866_1
crossvul-cpp_data_bad_2351_1
/* * save.c - write the cache struct to disk * * Copyright (C) 2001 by Andreas Dilger * Copyright (C) 2003 Theodore Ts'o * * %Begin-Header% * This file may be redistributed under the terms of the * GNU Lesser General Public License. * %End-Header% */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #ifdef HAVE_ERRNO_H #include <errno.h> #endif #include "closestream.h" #include "blkidP.h" static int save_dev(blkid_dev dev, FILE *file) { struct list_head *p; if (!dev || dev->bid_name[0] != '/') return 0; DBG(SAVE, ul_debug("device %s, type %s", dev->bid_name, dev->bid_type ? dev->bid_type : "(null)")); fprintf(file, "<device DEVNO=\"0x%04lx\" TIME=\"%ld.%ld\"", (unsigned long) dev->bid_devno, (long) dev->bid_time, (long) dev->bid_utime); if (dev->bid_pri) fprintf(file, " PRI=\"%d\"", dev->bid_pri); list_for_each(p, &dev->bid_tags) { blkid_tag tag = list_entry(p, struct blkid_struct_tag, bit_tags); fprintf(file, " %s=\"%s\"", tag->bit_name,tag->bit_val); } fprintf(file, ">%s</device>\n", dev->bid_name); return 0; } /* * Write out the cache struct to the cache file on disk. */ int blkid_flush_cache(blkid_cache cache) { struct list_head *p; char *tmp = NULL; char *opened = NULL; char *filename; FILE *file = NULL; int fd, ret = 0; struct stat st; if (!cache) return -BLKID_ERR_PARAM; if (list_empty(&cache->bic_devs) || !(cache->bic_flags & BLKID_BIC_FL_CHANGED)) { DBG(SAVE, ul_debug("skipping cache file write")); return 0; } filename = cache->bic_filename ? cache->bic_filename : blkid_get_cache_filename(NULL); if (!filename) return -BLKID_ERR_PARAM; if (strncmp(filename, BLKID_RUNTIME_DIR "/", sizeof(BLKID_RUNTIME_DIR)) == 0) { /* default destination, create the directory if necessary */ if (stat(BLKID_RUNTIME_DIR, &st) && errno == ENOENT && mkdir(BLKID_RUNTIME_DIR, S_IWUSR| S_IRUSR|S_IRGRP|S_IROTH| S_IXUSR|S_IXGRP|S_IXOTH) != 0 && errno != EEXIST) { DBG(SAVE, ul_debug("can't create %s directory for cache file", BLKID_RUNTIME_DIR)); return 0; } } /* If we can't write to the cache file, then don't even try */ if (((ret = stat(filename, &st)) < 0 && errno != ENOENT) || (ret == 0 && access(filename, W_OK) < 0)) { DBG(SAVE, ul_debug("can't write to cache file %s", filename)); return 0; } /* * Try and create a temporary file in the same directory so * that in case of error we don't overwrite the cache file. * If the cache file doesn't yet exist, it isn't a regular * file (e.g. /dev/null or a socket), or we couldn't create * a temporary file then we open it directly. */ if (ret == 0 && S_ISREG(st.st_mode)) { tmp = malloc(strlen(filename) + 8); if (tmp) { sprintf(tmp, "%s-XXXXXX", filename); fd = mkostemp(tmp, O_RDWR|O_CREAT|O_EXCL|O_CLOEXEC); if (fd >= 0) { if (fchmod(fd, 0644) != 0) DBG(SAVE, ul_debug("%s: fchmod failed", filename)); else if ((file = fdopen(fd, "w" UL_CLOEXECSTR))) opened = tmp; if (!file) close(fd); } } } if (!file) { file = fopen(filename, "w" UL_CLOEXECSTR); opened = filename; } DBG(SAVE, ul_debug("writing cache file %s (really %s)", filename, opened)); if (!file) { ret = errno; goto errout; } list_for_each(p, &cache->bic_devs) { blkid_dev dev = list_entry(p, struct blkid_struct_dev, bid_devs); if (!dev->bid_type || (dev->bid_flags & BLKID_BID_FL_REMOVABLE)) continue; if ((ret = save_dev(dev, file)) < 0) break; } if (ret >= 0) { cache->bic_flags &= ~BLKID_BIC_FL_CHANGED; ret = 1; } if (close_stream(file) != 0) DBG(SAVE, ul_debug("write failed: %s", filename)); if (opened != filename) { if (ret < 0) { unlink(opened); DBG(SAVE, ul_debug("unlinked temp cache %s", opened)); } else { char *backup; backup = malloc(strlen(filename) + 5); if (backup) { sprintf(backup, "%s.old", filename); unlink(backup); if (link(filename, backup)) { DBG(SAVE, ul_debug("can't link %s to %s", filename, backup)); } free(backup); } if (rename(opened, filename)) { ret = errno; DBG(SAVE, ul_debug("can't rename %s to %s", opened, filename)); } else { DBG(SAVE, ul_debug("moved temp cache %s", opened)); } } } errout: free(tmp); if (filename != cache->bic_filename) free(filename); return ret; } #ifdef TEST_PROGRAM int main(int argc, char **argv) { blkid_cache cache = NULL; int ret; blkid_init_debug(BLKID_DEBUG_ALL); if (argc > 2) { fprintf(stderr, "Usage: %s [filename]\n" "Test loading/saving a cache (filename)\n", argv[0]); exit(1); } if ((ret = blkid_get_cache(&cache, "/dev/null")) != 0) { fprintf(stderr, "%s: error creating cache (%d)\n", argv[0], ret); exit(1); } if ((ret = blkid_probe_all(cache)) < 0) { fprintf(stderr, "error (%d) probing devices\n", ret); exit(1); } cache->bic_filename = strdup(argv[1]); if ((ret = blkid_flush_cache(cache)) < 0) { fprintf(stderr, "error (%d) saving cache\n", ret); exit(1); } blkid_put_cache(cache); return ret; } #endif
./CrossVul/dataset_final_sorted/CWE-77/c/bad_2351_1
crossvul-cpp_data_good_251_2
/** * @file * IMAP network mailbox * * @authors * Copyright (C) 1996-1998,2012 Michael R. Elkins <me@mutt.org> * Copyright (C) 1996-1999 Brandon Long <blong@fiction.net> * Copyright (C) 1999-2009,2012,2017 Brendan Cully <brendan@kublai.com> * * @copyright * 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, see <http://www.gnu.org/licenses/>. */ /** * @page imap_imap IMAP network mailbox * * Support for IMAP4rev1, with the occasional nod to IMAP 4. */ #include "config.h" #include <ctype.h> #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include "imap_private.h" #include "mutt/mutt.h" #include "conn/conn.h" #include "mutt.h" #include "imap.h" #include "auth.h" #include "bcache.h" #include "body.h" #include "buffy.h" #include "context.h" #include "envelope.h" #include "globals.h" #include "header.h" #include "mailbox.h" #include "message.h" #include "mutt_account.h" #include "mutt_curses.h" #include "mutt_logging.h" #include "mutt_socket.h" #include "mx.h" #include "options.h" #include "pattern.h" #include "progress.h" #include "protos.h" #include "sort.h" #include "tags.h" #include "url.h" #ifdef USE_HCACHE #include "hcache/hcache.h" #endif /** * check_capabilities - Make sure we can log in to this server * @param idata Server data * @retval 0 Success * @retval -1 Failure */ static int check_capabilities(struct ImapData *idata) { if (imap_exec(idata, "CAPABILITY", 0) != 0) { imap_error("check_capabilities", idata->buf); return -1; } if (!(mutt_bit_isset(idata->capabilities, IMAP4) || mutt_bit_isset(idata->capabilities, IMAP4REV1))) { mutt_error( _("This IMAP server is ancient. NeoMutt does not work with it.")); return -1; } return 0; } /** * get_flags - Make a simple list out of a FLAGS response * @param hflags List to store flags * @param s String containing flags * @retval ptr End of the flags * @retval ptr NULL Failure * * return stream following FLAGS response */ static char *get_flags(struct ListHead *hflags, char *s) { /* sanity-check string */ if (mutt_str_strncasecmp("FLAGS", s, 5) != 0) { mutt_debug(1, "not a FLAGS response: %s\n", s); return NULL; } s += 5; SKIPWS(s); if (*s != '(') { mutt_debug(1, "bogus FLAGS response: %s\n", s); return NULL; } /* update caller's flags handle */ while (*s && *s != ')') { s++; SKIPWS(s); const char *flag_word = s; while (*s && (*s != ')') && !ISSPACE(*s)) s++; const char ctmp = *s; *s = '\0'; if (*flag_word) mutt_list_insert_tail(hflags, mutt_str_strdup(flag_word)); *s = ctmp; } /* note bad flags response */ if (*s != ')') { mutt_debug(1, "Unterminated FLAGS response: %s\n", s); mutt_list_free(hflags); return NULL; } s++; return s; } /** * set_flag - append str to flags if we currently have permission according to aclbit * @param[in] idata Server data * @param[in] aclbit Permissions, e.g. #MUTT_ACL_WRITE * @param[in] flag Does the email have the flag set? * @param[in] str Server flag name * @param[out] flags Buffer for server command * @param[in] flsize Length of buffer */ static void set_flag(struct ImapData *idata, int aclbit, int flag, const char *str, char *flags, size_t flsize) { if (mutt_bit_isset(idata->ctx->rights, aclbit)) if (flag && imap_has_flag(&idata->flags, str)) mutt_str_strcat(flags, flsize, str); } /** * make_msg_set - Make a message set * @param[in] idata Server data * @param[in] buf Buffer to store message set * @param[in] flag Flags to match, e.g. #MUTT_DELETED * @param[in] changed Matched messages that have been altered * @param[in] invert Flag matches should be inverted * @param[out] pos Cursor used for multiple calls to this function * @retval num Messages in the set * * @note Headers must be in SORT_ORDER. See imap_exec_msgset() for args. * Pos is an opaque pointer a la strtok(). It should be 0 at first call. */ static int make_msg_set(struct ImapData *idata, struct Buffer *buf, int flag, bool changed, bool invert, int *pos) { int count = 0; /* number of messages in message set */ unsigned int setstart = 0; /* start of current message range */ int n; bool started = false; struct Header **hdrs = idata->ctx->hdrs; for (n = *pos; n < idata->ctx->msgcount && buf->dptr - buf->data < IMAP_MAX_CMDLEN; n++) { bool match = false; /* whether current message matches flag condition */ /* don't include pending expunged messages */ if (hdrs[n]->active) { switch (flag) { case MUTT_DELETED: if (hdrs[n]->deleted != HEADER_DATA(hdrs[n])->deleted) match = invert ^ hdrs[n]->deleted; break; case MUTT_FLAG: if (hdrs[n]->flagged != HEADER_DATA(hdrs[n])->flagged) match = invert ^ hdrs[n]->flagged; break; case MUTT_OLD: if (hdrs[n]->old != HEADER_DATA(hdrs[n])->old) match = invert ^ hdrs[n]->old; break; case MUTT_READ: if (hdrs[n]->read != HEADER_DATA(hdrs[n])->read) match = invert ^ hdrs[n]->read; break; case MUTT_REPLIED: if (hdrs[n]->replied != HEADER_DATA(hdrs[n])->replied) match = invert ^ hdrs[n]->replied; break; case MUTT_TAG: if (hdrs[n]->tagged) match = true; break; case MUTT_TRASH: if (hdrs[n]->deleted && !hdrs[n]->purge) match = true; break; } } if (match && (!changed || hdrs[n]->changed)) { count++; if (setstart == 0) { setstart = HEADER_DATA(hdrs[n])->uid; if (!started) { mutt_buffer_printf(buf, "%u", HEADER_DATA(hdrs[n])->uid); started = true; } else mutt_buffer_printf(buf, ",%u", HEADER_DATA(hdrs[n])->uid); } /* tie up if the last message also matches */ else if (n == idata->ctx->msgcount - 1) mutt_buffer_printf(buf, ":%u", HEADER_DATA(hdrs[n])->uid); } /* End current set if message doesn't match or we've reached the end * of the mailbox via inactive messages following the last match. */ else if (setstart && (hdrs[n]->active || n == idata->ctx->msgcount - 1)) { if (HEADER_DATA(hdrs[n - 1])->uid > setstart) mutt_buffer_printf(buf, ":%u", HEADER_DATA(hdrs[n - 1])->uid); setstart = 0; } } *pos = n; return count; } /** * compare_flags_for_copy - Compare local flags against the server * @param h Header of email * @retval true Flags have changed * @retval false Flags match cached server flags * * The comparison of flags EXCLUDES the deleted flag. */ static bool compare_flags_for_copy(struct Header *h) { struct ImapHeaderData *hd = (struct ImapHeaderData *) h->data; if (h->read != hd->read) return true; if (h->old != hd->old) return true; if (h->flagged != hd->flagged) return true; if (h->replied != hd->replied) return true; return false; } /** * sync_helper - Sync flag changes to the server * @param idata Server data * @param right ACL, e.g. #MUTT_ACL_DELETE * @param flag Mutt flag, e.g. MUTT_DELETED * @param name Name of server flag * @retval >=0 Success, number of messages * @retval -1 Failure */ static int sync_helper(struct ImapData *idata, int right, int flag, const char *name) { int count = 0; int rc; char buf[LONG_STRING]; if (!idata->ctx) return -1; if (!mutt_bit_isset(idata->ctx->rights, right)) return 0; if (right == MUTT_ACL_WRITE && !imap_has_flag(&idata->flags, name)) return 0; snprintf(buf, sizeof(buf), "+FLAGS.SILENT (%s)", name); rc = imap_exec_msgset(idata, "UID STORE", buf, flag, 1, 0); if (rc < 0) return rc; count += rc; buf[0] = '-'; rc = imap_exec_msgset(idata, "UID STORE", buf, flag, 1, 1); if (rc < 0) return rc; count += rc; return count; } /** * get_mailbox - Split mailbox URI * @param path Mailbox URI * @param hidata Server data * @param buf Buffer to store mailbox name * @param blen Length of buffer * @retval 0 Success * @retval -1 Failure * * Split up a mailbox URI. The connection info is stored in the ImapData and * the mailbox name is stored in buf. */ static int get_mailbox(const char *path, struct ImapData **hidata, char *buf, size_t blen) { struct ImapMbox mx; if (imap_parse_path(path, &mx)) { mutt_debug(1, "Error parsing %s\n", path); return -1; } if (!(*hidata = imap_conn_find(&(mx.account), ImapPassive ? MUTT_IMAP_CONN_NONEW : 0)) || (*hidata)->state < IMAP_AUTHENTICATED) { FREE(&mx.mbox); return -1; } imap_fix_path(*hidata, mx.mbox, buf, blen); if (!*buf) mutt_str_strfcpy(buf, "INBOX", blen); FREE(&mx.mbox); return 0; } /** * do_search - Perform a search of messages * @param search List of pattern to match * @param allpats Must all patterns match? * @retval num Number of patterns search that should be done server-side * * Count the number of patterns that can be done by the server (are full-text). */ static int do_search(const struct Pattern *search, int allpats) { int rc = 0; const struct Pattern *pat = NULL; for (pat = search; pat; pat = pat->next) { switch (pat->op) { case MUTT_BODY: case MUTT_HEADER: case MUTT_WHOLE_MSG: if (pat->stringmatch) rc++; break; case MUTT_SERVERSEARCH: rc++; break; default: if (pat->child && do_search(pat->child, 1)) rc++; } if (!allpats) break; } return rc; } /** * compile_search - Convert NeoMutt pattern to IMAP search * @param ctx Context * @param pat Pattern to convert * @param buf Buffer for result * @retval 0 Success * @retval -1 Failure * * Convert neomutt Pattern to IMAP SEARCH command containing only elements * that require full-text search (neomutt already has what it needs for most * match types, and does a better job (eg server doesn't support regexes). */ static int compile_search(struct Context *ctx, const struct Pattern *pat, struct Buffer *buf) { if (do_search(pat, 0) == 0) return 0; if (pat->not) mutt_buffer_addstr(buf, "NOT "); if (pat->child) { int clauses; clauses = do_search(pat->child, 1); if (clauses > 0) { const struct Pattern *clause = pat->child; mutt_buffer_addch(buf, '('); while (clauses) { if (do_search(clause, 0)) { if (pat->op == MUTT_OR && clauses > 1) mutt_buffer_addstr(buf, "OR "); clauses--; if (compile_search(ctx, clause, buf) < 0) return -1; if (clauses) mutt_buffer_addch(buf, ' '); } clause = clause->next; } mutt_buffer_addch(buf, ')'); } } else { char term[STRING]; char *delim = NULL; switch (pat->op) { case MUTT_HEADER: mutt_buffer_addstr(buf, "HEADER "); /* extract header name */ delim = strchr(pat->p.str, ':'); if (!delim) { mutt_error(_("Header search without header name: %s"), pat->p.str); return -1; } *delim = '\0'; imap_quote_string(term, sizeof(term), pat->p.str, false); mutt_buffer_addstr(buf, term); mutt_buffer_addch(buf, ' '); /* and field */ *delim = ':'; delim++; SKIPWS(delim); imap_quote_string(term, sizeof(term), delim, false); mutt_buffer_addstr(buf, term); break; case MUTT_BODY: mutt_buffer_addstr(buf, "BODY "); imap_quote_string(term, sizeof(term), pat->p.str, false); mutt_buffer_addstr(buf, term); break; case MUTT_WHOLE_MSG: mutt_buffer_addstr(buf, "TEXT "); imap_quote_string(term, sizeof(term), pat->p.str, false); mutt_buffer_addstr(buf, term); break; case MUTT_SERVERSEARCH: { struct ImapData *idata = ctx->data; if (!mutt_bit_isset(idata->capabilities, X_GM_EXT1)) { mutt_error(_("Server-side custom search not supported: %s"), pat->p.str); return -1; } } mutt_buffer_addstr(buf, "X-GM-RAW "); imap_quote_string(term, sizeof(term), pat->p.str, false); mutt_buffer_addstr(buf, term); break; } } return 0; } /** * longest_common_prefix - Find longest prefix common to two strings * @param dest Destination buffer * @param src Source buffer * @param start Starting offset into string * @param dlen Destination buffer length * @retval num Length of the common string * * Trim dest to the length of the longest prefix it shares with src. */ static size_t longest_common_prefix(char *dest, const char *src, size_t start, size_t dlen) { size_t pos = start; while (pos < dlen && dest[pos] && dest[pos] == src[pos]) pos++; dest[pos] = '\0'; return pos; } /** * complete_hosts - Look for completion matches for mailboxes * @param buf Partial mailbox name to complete * @param buflen Length of buffer * @retval 0 Success * @retval -1 Failure * * look for IMAP URLs to complete from defined mailboxes. Could be extended to * complete over open connections and account/folder hooks too. */ static int complete_hosts(char *buf, size_t buflen) { struct Buffy *mailbox = NULL; struct Connection *conn = NULL; int rc = -1; size_t matchlen; matchlen = mutt_str_strlen(buf); for (mailbox = Incoming; mailbox; mailbox = mailbox->next) { if (mutt_str_strncmp(buf, mailbox->path, matchlen) == 0) { if (rc) { mutt_str_strfcpy(buf, mailbox->path, buflen); rc = 0; } else longest_common_prefix(buf, mailbox->path, matchlen, buflen); } } TAILQ_FOREACH(conn, mutt_socket_head(), entries) { struct Url url; char urlstr[LONG_STRING]; if (conn->account.type != MUTT_ACCT_TYPE_IMAP) continue; mutt_account_tourl(&conn->account, &url); /* FIXME: how to handle multiple users on the same host? */ url.user = NULL; url.path = NULL; url_tostring(&url, urlstr, sizeof(urlstr), 0); if (mutt_str_strncmp(buf, urlstr, matchlen) == 0) { if (rc) { mutt_str_strfcpy(buf, urlstr, buflen); rc = 0; } else longest_common_prefix(buf, urlstr, matchlen, buflen); } } return rc; } /** * imap_access - Check permissions on an IMAP mailbox * @param path Mailbox path * @retval 0 Success * @retval <0 Failure * * TODO: ACL checks. Right now we assume if it exists we can mess with it. */ int imap_access(const char *path) { struct ImapData *idata = NULL; struct ImapMbox mx; char buf[LONG_STRING]; char mailbox[LONG_STRING]; char mbox[LONG_STRING]; int rc; if (imap_parse_path(path, &mx)) return -1; idata = imap_conn_find(&mx.account, ImapPassive ? MUTT_IMAP_CONN_NONEW : 0); if (!idata) { FREE(&mx.mbox); return -1; } imap_fix_path(idata, mx.mbox, mailbox, sizeof(mailbox)); if (!*mailbox) mutt_str_strfcpy(mailbox, "INBOX", sizeof(mailbox)); /* we may already be in the folder we're checking */ if (mutt_str_strcmp(idata->mailbox, mx.mbox) == 0) { FREE(&mx.mbox); return 0; } FREE(&mx.mbox); if (imap_mboxcache_get(idata, mailbox, 0)) { mutt_debug(3, "found %s in cache\n", mailbox); return 0; } imap_munge_mbox_name(idata, mbox, sizeof(mbox), mailbox); if (mutt_bit_isset(idata->capabilities, IMAP4REV1)) snprintf(buf, sizeof(buf), "STATUS %s (UIDVALIDITY)", mbox); else if (mutt_bit_isset(idata->capabilities, STATUS)) snprintf(buf, sizeof(buf), "STATUS %s (UID-VALIDITY)", mbox); else { mutt_debug(2, "STATUS not supported?\n"); return -1; } rc = imap_exec(idata, buf, IMAP_CMD_FAIL_OK); if (rc < 0) { mutt_debug(1, "Can't check STATUS of %s\n", mbox); return rc; } return 0; } /** * imap_create_mailbox - Create a new mailbox * @param idata Server data * @param mailbox Mailbox to create * @retval 0 Success * @retval -1 Failure */ int imap_create_mailbox(struct ImapData *idata, char *mailbox) { char buf[LONG_STRING], mbox[LONG_STRING]; imap_munge_mbox_name(idata, mbox, sizeof(mbox), mailbox); snprintf(buf, sizeof(buf), "CREATE %s", mbox); if (imap_exec(idata, buf, 0) != 0) { mutt_error(_("CREATE failed: %s"), imap_cmd_trailer(idata)); return -1; } return 0; } /** * imap_rename_mailbox - Rename a mailbox * @param idata Server data * @param mx Existing mailbox * @param newname New name for mailbox * @retval 0 Success * @retval -1 Failure */ int imap_rename_mailbox(struct ImapData *idata, struct ImapMbox *mx, const char *newname) { char oldmbox[LONG_STRING]; char newmbox[LONG_STRING]; char buf[LONG_STRING]; imap_munge_mbox_name(idata, oldmbox, sizeof(oldmbox), mx->mbox); imap_munge_mbox_name(idata, newmbox, sizeof(newmbox), newname); snprintf(buf, sizeof(buf), "RENAME %s %s", oldmbox, newmbox); if (imap_exec(idata, buf, 0) != 0) return -1; return 0; } /** * imap_delete_mailbox - Delete a mailbox * @param ctx Context * @param mx Mailbox to delete * @retval 0 Success * @retval -1 Failure */ int imap_delete_mailbox(struct Context *ctx, struct ImapMbox *mx) { char buf[PATH_MAX], mbox[PATH_MAX]; struct ImapData *idata = NULL; if (!ctx || !ctx->data) { idata = imap_conn_find(&mx->account, ImapPassive ? MUTT_IMAP_CONN_NONEW : 0); if (!idata) { FREE(&mx->mbox); return -1; } } else { idata = ctx->data; } imap_munge_mbox_name(idata, mbox, sizeof(mbox), mx->mbox); snprintf(buf, sizeof(buf), "DELETE %s", mbox); if (imap_exec(idata, buf, 0) != 0) return -1; return 0; } /** * imap_logout_all - close all open connections * * Quick and dirty until we can make sure we've got all the context we need. */ void imap_logout_all(void) { struct ConnectionList *head = mutt_socket_head(); struct Connection *np, *tmp; TAILQ_FOREACH_SAFE(np, head, entries, tmp) { if (np->account.type == MUTT_ACCT_TYPE_IMAP && np->fd >= 0) { TAILQ_REMOVE(head, np, entries); mutt_message(_("Closing connection to %s..."), np->account.host); imap_logout((struct ImapData **) (void *) &np->data); mutt_clear_error(); mutt_socket_free(np); } } } /** * imap_read_literal - Read bytes bytes from server into file * @param fp File handle for email file * @param idata Server data * @param bytes Number of bytes to read * @param pbar Progress bar * @retval 0 Success * @retval -1 Failure * * Not explicitly buffered, relies on FILE buffering. * * @note Strips `\r` from `\r\n`. * Apparently even literals use `\r\n`-terminated strings ?! */ int imap_read_literal(FILE *fp, struct ImapData *idata, unsigned long bytes, struct Progress *pbar) { char c; bool r = false; struct Buffer *buf = NULL; if (DebugLevel >= IMAP_LOG_LTRL) buf = mutt_buffer_alloc(bytes + 10); mutt_debug(2, "reading %ld bytes\n", bytes); for (unsigned long pos = 0; pos < bytes; pos++) { if (mutt_socket_readchar(idata->conn, &c) != 1) { mutt_debug(1, "error during read, %ld bytes read\n", pos); idata->status = IMAP_FATAL; mutt_buffer_free(&buf); return -1; } if (r && c != '\n') fputc('\r', fp); if (c == '\r') { r = true; continue; } else r = false; fputc(c, fp); if (pbar && !(pos % 1024)) mutt_progress_update(pbar, pos, -1); if (DebugLevel >= IMAP_LOG_LTRL) mutt_buffer_addch(buf, c); } if (DebugLevel >= IMAP_LOG_LTRL) { mutt_debug(IMAP_LOG_LTRL, "\n%s", buf->data); mutt_buffer_free(&buf); } return 0; } /** * imap_expunge_mailbox - Purge messages from the server * @param idata Server data * * Purge IMAP portion of expunged messages from the context. Must not be done * while something has a handle on any headers (eg inside pager or editor). * That is, check IMAP_REOPEN_ALLOW. */ void imap_expunge_mailbox(struct ImapData *idata) { struct Header *h = NULL; int cacheno; short old_sort; #ifdef USE_HCACHE idata->hcache = imap_hcache_open(idata, NULL); #endif old_sort = Sort; Sort = SORT_ORDER; mutt_sort_headers(idata->ctx, 0); for (int i = 0; i < idata->ctx->msgcount; i++) { h = idata->ctx->hdrs[i]; if (h->index == INT_MAX) { mutt_debug(2, "Expunging message UID %u.\n", HEADER_DATA(h)->uid); h->active = false; idata->ctx->size -= h->content->length; imap_cache_del(idata, h); #ifdef USE_HCACHE imap_hcache_del(idata, HEADER_DATA(h)->uid); #endif /* free cached body from disk, if necessary */ cacheno = HEADER_DATA(h)->uid % IMAP_CACHE_LEN; if (idata->cache[cacheno].uid == HEADER_DATA(h)->uid && idata->cache[cacheno].path) { unlink(idata->cache[cacheno].path); FREE(&idata->cache[cacheno].path); } mutt_hash_int_delete(idata->uid_hash, HEADER_DATA(h)->uid, h); imap_free_header_data((struct ImapHeaderData **) &h->data); } else { h->index = i; /* NeoMutt has several places where it turns off h->active as a * hack. For example to avoid FLAG updates, or to exclude from * imap_exec_msgset. * * Unfortunately, when a reopen is allowed and the IMAP_EXPUNGE_PENDING * flag becomes set (e.g. a flag update to a modified header), * this function will be called by imap_cmd_finish(). * * The mx_update_tables() will free and remove these "inactive" headers, * despite that an EXPUNGE was not received for them. * This would result in memory leaks and segfaults due to dangling * pointers in the msn_index and uid_hash. * * So this is another hack to work around the hacks. We don't want to * remove the messages, so make sure active is on. */ h->active = true; } } #ifdef USE_HCACHE imap_hcache_close(idata); #endif /* We may be called on to expunge at any time. We can't rely on the caller * to always know to rethread */ mx_update_tables(idata->ctx, false); Sort = old_sort; mutt_sort_headers(idata->ctx, 1); } /** * imap_conn_find - Find an open IMAP connection * @param account Account to search * @param flags Flags, e.g. #MUTT_IMAP_CONN_NONEW * @retval ptr Matching connection * @retval NULL Failure * * Find an open IMAP connection matching account, or open a new one if none can * be found. */ struct ImapData *imap_conn_find(const struct Account *account, int flags) { struct Connection *conn = NULL; struct Account *creds = NULL; struct ImapData *idata = NULL; bool new = false; while ((conn = mutt_conn_find(conn, account))) { if (!creds) creds = &conn->account; else memcpy(&conn->account, creds, sizeof(struct Account)); idata = conn->data; if (flags & MUTT_IMAP_CONN_NONEW) { if (!idata) { /* This should only happen if we've come to the end of the list */ mutt_socket_free(conn); return NULL; } else if (idata->state < IMAP_AUTHENTICATED) continue; } if (flags & MUTT_IMAP_CONN_NOSELECT && idata && idata->state >= IMAP_SELECTED) continue; if (idata && idata->status == IMAP_FATAL) continue; break; } if (!conn) return NULL; /* this happens when the initial connection fails */ if (!idata) { /* The current connection is a new connection */ idata = imap_new_idata(); if (!idata) { mutt_socket_free(conn); return NULL; } conn->data = idata; idata->conn = conn; new = true; } if (idata->state == IMAP_DISCONNECTED) imap_open_connection(idata); if (idata->state == IMAP_CONNECTED) { if (imap_authenticate(idata) == IMAP_AUTH_SUCCESS) { idata->state = IMAP_AUTHENTICATED; FREE(&idata->capstr); new = true; if (idata->conn->ssf) mutt_debug(2, "Communication encrypted at %d bits\n", idata->conn->ssf); } else mutt_account_unsetpass(&idata->conn->account); } if (new && idata->state == IMAP_AUTHENTICATED) { /* capabilities may have changed */ imap_exec(idata, "CAPABILITY", IMAP_CMD_QUEUE); /* enable RFC6855, if the server supports that */ if (mutt_bit_isset(idata->capabilities, ENABLE)) imap_exec(idata, "ENABLE UTF8=ACCEPT", IMAP_CMD_QUEUE); /* get root delimiter, '/' as default */ idata->delim = '/'; imap_exec(idata, "LIST \"\" \"\"", IMAP_CMD_QUEUE); /* we may need the root delimiter before we open a mailbox */ imap_exec(idata, NULL, IMAP_CMD_FAIL_OK); } return idata; } /** * imap_open_connection - Open an IMAP connection * @param idata Server data * @retval 0 Success * @retval -1 Failure */ int imap_open_connection(struct ImapData *idata) { char buf[LONG_STRING]; if (mutt_socket_open(idata->conn) < 0) return -1; idata->state = IMAP_CONNECTED; if (imap_cmd_step(idata) != IMAP_CMD_OK) { imap_close_connection(idata); return -1; } if (mutt_str_strncasecmp("* OK", idata->buf, 4) == 0) { if ((mutt_str_strncasecmp("* OK [CAPABILITY", idata->buf, 16) != 0) && check_capabilities(idata)) { goto bail; } #ifdef USE_SSL /* Attempt STARTTLS if available and desired. */ if (!idata->conn->ssf && (SslForceTls || mutt_bit_isset(idata->capabilities, STARTTLS))) { int rc; if (SslForceTls) rc = MUTT_YES; else if ((rc = query_quadoption(SslStarttls, _("Secure connection with TLS?"))) == MUTT_ABORT) { goto err_close_conn; } if (rc == MUTT_YES) { rc = imap_exec(idata, "STARTTLS", IMAP_CMD_FAIL_OK); if (rc == -1) goto bail; if (rc != -2) { if (mutt_ssl_starttls(idata->conn)) { mutt_error(_("Could not negotiate TLS connection")); goto err_close_conn; } else { /* RFC2595 demands we recheck CAPABILITY after TLS completes. */ if (imap_exec(idata, "CAPABILITY", 0)) goto bail; } } } } if (SslForceTls && !idata->conn->ssf) { mutt_error(_("Encrypted connection unavailable")); goto err_close_conn; } #endif } else if (mutt_str_strncasecmp("* PREAUTH", idata->buf, 9) == 0) { idata->state = IMAP_AUTHENTICATED; if (check_capabilities(idata) != 0) goto bail; FREE(&idata->capstr); } else { imap_error("imap_open_connection()", buf); goto bail; } return 0; #ifdef USE_SSL err_close_conn: imap_close_connection(idata); #endif bail: FREE(&idata->capstr); return -1; } /** * imap_close_connection - Close an IMAP connection * @param idata Server data */ void imap_close_connection(struct ImapData *idata) { if (idata->state != IMAP_DISCONNECTED) { mutt_socket_close(idata->conn); idata->state = IMAP_DISCONNECTED; } idata->seqno = idata->nextcmd = idata->lastcmd = idata->status = false; memset(idata->cmds, 0, sizeof(struct ImapCommand) * idata->cmdslots); } /** * imap_logout - Gracefully log out of server * @param idata Server data */ void imap_logout(struct ImapData **idata) { /* we set status here to let imap_handle_untagged know we _expect_ to * receive a bye response (so it doesn't freak out and close the conn) */ (*idata)->status = IMAP_BYE; imap_cmd_start(*idata, "LOGOUT"); if (ImapPollTimeout <= 0 || mutt_socket_poll((*idata)->conn, ImapPollTimeout) != 0) { while (imap_cmd_step(*idata) == IMAP_CMD_CONTINUE) ; } mutt_socket_close((*idata)->conn); imap_free_idata(idata); } /** * imap_has_flag - Does the flag exist in the list * @param flag_list List of server flags * @param flag Flag to find * @retval true Flag exists * * Do a caseless comparison of the flag against a flag list, return true if * found or flag list has '\*'. */ bool imap_has_flag(struct ListHead *flag_list, const char *flag) { if (STAILQ_EMPTY(flag_list)) return false; struct ListNode *np; STAILQ_FOREACH(np, flag_list, entries) { if (mutt_str_strncasecmp(np->data, flag, strlen(np->data)) == 0) return true; if (mutt_str_strncmp(np->data, "\\*", strlen(np->data)) == 0) return true; } return false; } /** * imap_exec_msgset - Prepare commands for all messages matching conditions * @param idata ImapData containing context containing header set * @param pre prefix commands * @param post postfix commands * @param flag flag type on which to filter, e.g. MUTT_REPLIED * @param changed include only changed messages in message set * @param invert invert sense of flag, eg MUTT_READ matches unread messages * @retval num Matched messages * @retval -1 Failure * * pre/post: commands are of the form "%s %s %s %s", tag, pre, message set, post * Prepares commands for all messages matching conditions * (must be flushed with imap_exec) */ int imap_exec_msgset(struct ImapData *idata, const char *pre, const char *post, int flag, int changed, int invert) { struct Header **hdrs = NULL; short oldsort; int pos; int rc; int count = 0; struct Buffer *cmd = mutt_buffer_new(); /* We make a copy of the headers just in case resorting doesn't give exactly the original order (duplicate messages?), because other parts of the ctx are tied to the header order. This may be overkill. */ oldsort = Sort; if (Sort != SORT_ORDER) { hdrs = idata->ctx->hdrs; idata->ctx->hdrs = mutt_mem_malloc(idata->ctx->msgcount * sizeof(struct Header *)); memcpy(idata->ctx->hdrs, hdrs, idata->ctx->msgcount * sizeof(struct Header *)); Sort = SORT_ORDER; qsort(idata->ctx->hdrs, idata->ctx->msgcount, sizeof(struct Header *), mutt_get_sort_func(SORT_ORDER)); } pos = 0; do { cmd->dptr = cmd->data; mutt_buffer_printf(cmd, "%s ", pre); rc = make_msg_set(idata, cmd, flag, changed, invert, &pos); if (rc > 0) { mutt_buffer_printf(cmd, " %s", post); if (imap_exec(idata, cmd->data, IMAP_CMD_QUEUE)) { rc = -1; goto out; } count += rc; } } while (rc > 0); rc = count; out: mutt_buffer_free(&cmd); if (oldsort != Sort) { Sort = oldsort; FREE(&idata->ctx->hdrs); idata->ctx->hdrs = hdrs; } return rc; } /** * imap_sync_message_for_copy - Update server to reflect the flags of a single message * @param[in] idata Server data * @param[in] hdr Header of the email * @param[in] cmd Buffer for the command string * @param[out] err_continue Did the user force a continue? * @retval 0 Success * @retval -1 Failure * * Update the IMAP server to reflect the flags for a single message before * performing a "UID COPY". * * @note This does not sync the "deleted" flag state, because it is not * desirable to propagate that flag into the copy. */ int imap_sync_message_for_copy(struct ImapData *idata, struct Header *hdr, struct Buffer *cmd, int *err_continue) { char flags[LONG_STRING]; char *tags; char uid[11]; if (!compare_flags_for_copy(hdr)) { if (hdr->deleted == HEADER_DATA(hdr)->deleted) hdr->changed = false; return 0; } snprintf(uid, sizeof(uid), "%u", HEADER_DATA(hdr)->uid); cmd->dptr = cmd->data; mutt_buffer_addstr(cmd, "UID STORE "); mutt_buffer_addstr(cmd, uid); flags[0] = '\0'; set_flag(idata, MUTT_ACL_SEEN, hdr->read, "\\Seen ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, hdr->old, "Old ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, hdr->flagged, "\\Flagged ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, hdr->replied, "\\Answered ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_DELETE, HEADER_DATA(hdr)->deleted, "\\Deleted ", flags, sizeof(flags)); if (mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE)) { /* restore system flags */ if (HEADER_DATA(hdr)->flags_system) mutt_str_strcat(flags, sizeof(flags), HEADER_DATA(hdr)->flags_system); /* set custom flags */ tags = driver_tags_get_with_hidden(&hdr->tags); if (tags) { mutt_str_strcat(flags, sizeof(flags), tags); FREE(&tags); } } mutt_str_remove_trailing_ws(flags); /* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to * explicitly revoke all system flags (if we have permission) */ if (!*flags) { set_flag(idata, MUTT_ACL_SEEN, 1, "\\Seen ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, 1, "Old ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, 1, "\\Flagged ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, 1, "\\Answered ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_DELETE, !HEADER_DATA(hdr)->deleted, "\\Deleted ", flags, sizeof(flags)); /* erase custom flags */ if (mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE) && HEADER_DATA(hdr)->flags_remote) mutt_str_strcat(flags, sizeof(flags), HEADER_DATA(hdr)->flags_remote); mutt_str_remove_trailing_ws(flags); mutt_buffer_addstr(cmd, " -FLAGS.SILENT ("); } else mutt_buffer_addstr(cmd, " FLAGS.SILENT ("); mutt_buffer_addstr(cmd, flags); mutt_buffer_addstr(cmd, ")"); /* dumb hack for bad UW-IMAP 4.7 servers spurious FLAGS updates */ hdr->active = false; /* after all this it's still possible to have no flags, if you * have no ACL rights */ if (*flags && (imap_exec(idata, cmd->data, 0) != 0) && err_continue && (*err_continue != MUTT_YES)) { *err_continue = imap_continue("imap_sync_message: STORE failed", idata->buf); if (*err_continue != MUTT_YES) { hdr->active = true; return -1; } } /* server have now the updated flags */ FREE(&HEADER_DATA(hdr)->flags_remote); HEADER_DATA(hdr)->flags_remote = driver_tags_get_with_hidden(&hdr->tags); hdr->active = true; if (hdr->deleted == HEADER_DATA(hdr)->deleted) hdr->changed = false; return 0; } /** * imap_check_mailbox - use the NOOP or IDLE command to poll for new mail * @param ctx Context * @param force Don't wait * @retval #MUTT_REOPENED mailbox has been externally modified * @retval #MUTT_NEW_MAIL new mail has arrived * @retval 0 no change * @retval -1 error */ int imap_check_mailbox(struct Context *ctx, int force) { return imap_check(ctx->data, force); } /** * imap_check - Check for new mail * @param idata Server data * @param force Force a refresh * @retval >0 Success, e.g. #MUTT_REOPENED * @retval -1 Failure */ int imap_check(struct ImapData *idata, int force) { /* overload keyboard timeout to avoid many mailbox checks in a row. * Most users don't like having to wait exactly when they press a key. */ int result = 0; /* try IDLE first, unless force is set */ if (!force && ImapIdle && mutt_bit_isset(idata->capabilities, IDLE) && (idata->state != IMAP_IDLE || time(NULL) >= idata->lastread + ImapKeepalive)) { if (imap_cmd_idle(idata) < 0) return -1; } if (idata->state == IMAP_IDLE) { while ((result = mutt_socket_poll(idata->conn, 0)) > 0) { if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE) { mutt_debug(1, "Error reading IDLE response\n"); return -1; } } if (result < 0) { mutt_debug(1, "Poll failed, disabling IDLE\n"); mutt_bit_unset(idata->capabilities, IDLE); } } if ((force || (idata->state != IMAP_IDLE && time(NULL) >= idata->lastread + Timeout)) && imap_exec(idata, "NOOP", IMAP_CMD_POLL) != 0) { return -1; } /* We call this even when we haven't run NOOP in case we have pending * changes to process, since we can reopen here. */ imap_cmd_finish(idata); if (idata->check_status & IMAP_EXPUNGE_PENDING) result = MUTT_REOPENED; else if (idata->check_status & IMAP_NEWMAIL_PENDING) result = MUTT_NEW_MAIL; else if (idata->check_status & IMAP_FLAGS_PENDING) result = MUTT_FLAGS; idata->check_status = 0; return result; } /** * imap_buffy_check - Check for new mail in subscribed folders * @param check_stats Check for message stats too * @retval num Number of mailboxes with new mail * @retval 0 Failure * * Given a list of mailboxes rather than called once for each so that it can * batch the commands and save on round trips. */ int imap_buffy_check(int check_stats) { struct ImapData *idata = NULL; struct ImapData *lastdata = NULL; struct Buffy *mailbox = NULL; char name[LONG_STRING]; char command[LONG_STRING]; char munged[LONG_STRING]; int buffies = 0; for (mailbox = Incoming; mailbox; mailbox = mailbox->next) { /* Init newly-added mailboxes */ if (!mailbox->magic) { if (mx_is_imap(mailbox->path)) mailbox->magic = MUTT_IMAP; } if (mailbox->magic != MUTT_IMAP) continue; if (get_mailbox(mailbox->path, &idata, name, sizeof(name)) < 0) { mailbox->new = false; continue; } /* Don't issue STATUS on the selected mailbox, it will be NOOPed or * IDLEd elsewhere. * idata->mailbox may be NULL for connections other than the current * mailbox's, and shouldn't expand to INBOX in that case. #3216. */ if (idata->mailbox && (imap_mxcmp(name, idata->mailbox) == 0)) { mailbox->new = false; continue; } if (!mutt_bit_isset(idata->capabilities, IMAP4REV1) && !mutt_bit_isset(idata->capabilities, STATUS)) { mutt_debug(2, "Server doesn't support STATUS\n"); continue; } if (lastdata && idata != lastdata) { /* Send commands to previous server. Sorting the buffy list * may prevent some infelicitous interleavings */ if (imap_exec(lastdata, NULL, IMAP_CMD_FAIL_OK | IMAP_CMD_POLL) == -1) mutt_debug(1, "#1 Error polling mailboxes\n"); lastdata = NULL; } if (!lastdata) lastdata = idata; imap_munge_mbox_name(idata, munged, sizeof(munged), name); if (check_stats) { snprintf(command, sizeof(command), "STATUS %s (UIDNEXT UIDVALIDITY UNSEEN RECENT MESSAGES)", munged); } else { snprintf(command, sizeof(command), "STATUS %s (UIDNEXT UIDVALIDITY UNSEEN RECENT)", munged); } if (imap_exec(idata, command, IMAP_CMD_QUEUE | IMAP_CMD_POLL) < 0) { mutt_debug(1, "Error queueing command\n"); return 0; } } if (lastdata && (imap_exec(lastdata, NULL, IMAP_CMD_FAIL_OK | IMAP_CMD_POLL) == -1)) { mutt_debug(1, "#2 Error polling mailboxes\n"); return 0; } /* collect results */ for (mailbox = Incoming; mailbox; mailbox = mailbox->next) { if (mailbox->magic == MUTT_IMAP && mailbox->new) buffies++; } return buffies; } /** * imap_status - Get the status of a mailbox * @param path Path of mailbox * @param queue true if the command should be queued for the next call * @retval -1 Error * @retval >=0 Count of messages in mailbox * * If queue is true, the command will be sent now and be expected to have been * run on the next call (for pipelining the postponed count). */ int imap_status(char *path, int queue) { static int queued = 0; struct ImapData *idata = NULL; char buf[LONG_STRING]; char mbox[LONG_STRING]; struct ImapStatus *status = NULL; if (get_mailbox(path, &idata, buf, sizeof(buf)) < 0) return -1; /* We are in the folder we're polling - just return the mailbox count. * * Note that imap_mxcmp() converts NULL to "INBOX", so we need to * make sure the idata really is open to a folder. */ if (idata->ctx && !imap_mxcmp(buf, idata->mailbox)) return idata->ctx->msgcount; else if (mutt_bit_isset(idata->capabilities, IMAP4REV1) || mutt_bit_isset(idata->capabilities, STATUS)) { imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf); snprintf(buf, sizeof(buf), "STATUS %s (%s)", mbox, "MESSAGES"); imap_unmunge_mbox_name(idata, mbox); } else { /* Server does not support STATUS, and this is not the current mailbox. * There is no lightweight way to check recent arrivals */ return -1; } if (queue) { imap_exec(idata, buf, IMAP_CMD_QUEUE); queued = 1; return 0; } else if (!queued) imap_exec(idata, buf, 0); queued = 0; status = imap_mboxcache_get(idata, mbox, 0); if (status) return status->messages; return 0; } /** * imap_mboxcache_get - Open an hcache for a mailbox * @param idata Server data * @param mbox Mailbox to cache * @param create Should it be created if it doesn't exist? * @retval ptr Stats of cached mailbox * @retval ptr Stats of new cache entry * @retval NULL Not in cache and create is false * * return cached mailbox stats or NULL if create is 0 */ struct ImapStatus *imap_mboxcache_get(struct ImapData *idata, const char *mbox, bool create) { struct ImapStatus *status = NULL; #ifdef USE_HCACHE header_cache_t *hc = NULL; void *uidvalidity = NULL; void *uidnext = NULL; #endif struct ListNode *np; STAILQ_FOREACH(np, &idata->mboxcache, entries) { status = (struct ImapStatus *) np->data; if (imap_mxcmp(mbox, status->name) == 0) return status; } status = NULL; /* lame */ if (create) { struct ImapStatus *scache = mutt_mem_calloc(1, sizeof(struct ImapStatus)); scache->name = (char *) mbox; mutt_list_insert_tail(&idata->mboxcache, (char *) scache); status = imap_mboxcache_get(idata, mbox, 0); status->name = mutt_str_strdup(mbox); } #ifdef USE_HCACHE hc = imap_hcache_open(idata, mbox); if (hc) { uidvalidity = mutt_hcache_fetch_raw(hc, "/UIDVALIDITY", 12); uidnext = mutt_hcache_fetch_raw(hc, "/UIDNEXT", 8); if (uidvalidity) { if (!status) { mutt_hcache_free(hc, &uidvalidity); mutt_hcache_free(hc, &uidnext); mutt_hcache_close(hc); return imap_mboxcache_get(idata, mbox, 1); } status->uidvalidity = *(unsigned int *) uidvalidity; status->uidnext = uidnext ? *(unsigned int *) uidnext : 0; mutt_debug(3, "hcache uidvalidity %u, uidnext %u\n", status->uidvalidity, status->uidnext); } mutt_hcache_free(hc, &uidvalidity); mutt_hcache_free(hc, &uidnext); mutt_hcache_close(hc); } #endif return status; } /** * imap_mboxcache_free - Free the cached ImapStatus * @param idata Server data */ void imap_mboxcache_free(struct ImapData *idata) { struct ImapStatus *status = NULL; struct ListNode *np; STAILQ_FOREACH(np, &idata->mboxcache, entries) { status = (struct ImapStatus *) np->data; FREE(&status->name); } mutt_list_free(&idata->mboxcache); } /** * imap_search - Find a matching mailbox * @param ctx Context * @param pat Pattern to match * @retval 0 Success * @retval -1 Failure */ int imap_search(struct Context *ctx, const struct Pattern *pat) { struct Buffer buf; struct ImapData *idata = ctx->data; for (int i = 0; i < ctx->msgcount; i++) ctx->hdrs[i]->matched = false; if (do_search(pat, 1) == 0) return 0; mutt_buffer_init(&buf); mutt_buffer_addstr(&buf, "UID SEARCH "); if (compile_search(ctx, pat, &buf) < 0) { FREE(&buf.data); return -1; } if (imap_exec(idata, buf.data, 0) < 0) { FREE(&buf.data); return -1; } FREE(&buf.data); return 0; } /** * imap_subscribe - Subscribe to a mailbox * @param path Mailbox path * @param subscribe True: subscribe, false: unsubscribe * @retval 0 Success * @retval -1 Failure */ int imap_subscribe(char *path, bool subscribe) { struct ImapData *idata = NULL; char buf[LONG_STRING]; char mbox[LONG_STRING]; char errstr[STRING]; struct Buffer err, token; struct ImapMbox mx; if (!mx_is_imap(path) || imap_parse_path(path, &mx) || !mx.mbox) { mutt_error(_("Bad mailbox name")); return -1; } idata = imap_conn_find(&(mx.account), 0); if (!idata) goto fail; imap_fix_path(idata, mx.mbox, buf, sizeof(buf)); if (!*buf) mutt_str_strfcpy(buf, "INBOX", sizeof(buf)); if (ImapCheckSubscribed) { mutt_buffer_init(&token); mutt_buffer_init(&err); err.data = errstr; err.dsize = sizeof(errstr); snprintf(mbox, sizeof(mbox), "%smailboxes \"%s\"", subscribe ? "" : "un", path); if (mutt_parse_rc_line(mbox, &token, &err)) mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr); FREE(&token.data); } if (subscribe) mutt_message(_("Subscribing to %s..."), buf); else mutt_message(_("Unsubscribing from %s..."), buf); imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf); snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox); if (imap_exec(idata, buf, 0) < 0) goto fail; imap_unmunge_mbox_name(idata, mx.mbox); if (subscribe) mutt_message(_("Subscribed to %s"), mx.mbox); else mutt_message(_("Unsubscribed from %s"), mx.mbox); FREE(&mx.mbox); return 0; fail: FREE(&mx.mbox); return -1; } /** * imap_complete - Try to complete an IMAP folder path * @param buf Buffer for result * @param buflen Length of buffer * @param path Partial mailbox name to complete * @retval 0 Success * @retval -1 Failure * * Given a partial IMAP folder path, return a string which adds as much to the * path as is unique */ int imap_complete(char *buf, size_t buflen, char *path) { struct ImapData *idata = NULL; char list[LONG_STRING]; char tmp[LONG_STRING]; struct ImapList listresp; char completion[LONG_STRING]; int clen; size_t matchlen = 0; int completions = 0; struct ImapMbox mx; int rc; if (imap_parse_path(path, &mx)) { mutt_str_strfcpy(buf, path, buflen); return complete_hosts(buf, buflen); } /* don't open a new socket just for completion. Instead complete over * known mailboxes/hooks/etc */ idata = imap_conn_find(&(mx.account), MUTT_IMAP_CONN_NONEW); if (!idata) { FREE(&mx.mbox); mutt_str_strfcpy(buf, path, buflen); return complete_hosts(buf, buflen); } /* reformat path for IMAP list, and append wildcard */ /* don't use INBOX in place of "" */ if (mx.mbox && mx.mbox[0]) imap_fix_path(idata, mx.mbox, list, sizeof(list)); else list[0] = '\0'; /* fire off command */ snprintf(tmp, sizeof(tmp), "%s \"\" \"%s%%\"", ImapListSubscribed ? "LSUB" : "LIST", list); imap_cmd_start(idata, tmp); /* and see what the results are */ mutt_str_strfcpy(completion, NONULL(mx.mbox), sizeof(completion)); idata->cmdtype = IMAP_CT_LIST; idata->cmddata = &listresp; do { listresp.name = NULL; rc = imap_cmd_step(idata); if (rc == IMAP_CMD_CONTINUE && listresp.name) { /* if the folder isn't selectable, append delimiter to force browse * to enter it on second tab. */ if (listresp.noselect) { clen = strlen(listresp.name); listresp.name[clen++] = listresp.delim; listresp.name[clen] = '\0'; } /* copy in first word */ if (!completions) { mutt_str_strfcpy(completion, listresp.name, sizeof(completion)); matchlen = strlen(completion); completions++; continue; } matchlen = longest_common_prefix(completion, listresp.name, 0, matchlen); completions++; } } while (rc == IMAP_CMD_CONTINUE); idata->cmddata = NULL; if (completions) { /* reformat output */ imap_qualify_path(buf, buflen, &mx, completion); mutt_pretty_mailbox(buf, buflen); FREE(&mx.mbox); return 0; } return -1; } /** * imap_fast_trash - Use server COPY command to copy deleted messages to trash * @param ctx Context * @param dest Mailbox to move to * @retval -1 Error * @retval 0 Success * @retval 1 Non-fatal error - try fetch/append */ int imap_fast_trash(struct Context *ctx, char *dest) { char mbox[LONG_STRING]; char mmbox[LONG_STRING]; char prompt[LONG_STRING]; int rc; struct ImapMbox mx; bool triedcreate = false; struct Buffer *sync_cmd = NULL; int err_continue = MUTT_NO; struct ImapData *idata = ctx->data; if (imap_parse_path(dest, &mx)) { mutt_debug(1, "bad destination %s\n", dest); return -1; } /* check that the save-to folder is in the same account */ if (mutt_account_match(&(idata->conn->account), &(mx.account)) == 0) { mutt_debug(3, "%s not same server as %s\n", dest, ctx->path); return 1; } imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox)); if (!*mbox) mutt_str_strfcpy(mbox, "INBOX", sizeof(mbox)); imap_munge_mbox_name(idata, mmbox, sizeof(mmbox), mbox); sync_cmd = mutt_buffer_new(); for (int i = 0; i < ctx->msgcount; i++) { if (ctx->hdrs[i]->active && ctx->hdrs[i]->changed && ctx->hdrs[i]->deleted && !ctx->hdrs[i]->purge) { rc = imap_sync_message_for_copy(idata, ctx->hdrs[i], sync_cmd, &err_continue); if (rc < 0) { mutt_debug(1, "could not sync\n"); goto out; } } } /* loop in case of TRYCREATE */ do { rc = imap_exec_msgset(idata, "UID COPY", mmbox, MUTT_TRASH, 0, 0); if (!rc) { mutt_debug(1, "No messages to trash\n"); rc = -1; goto out; } else if (rc < 0) { mutt_debug(1, "could not queue copy\n"); goto out; } else { mutt_message(ngettext("Copying %d message to %s...", "Copying %d messages to %s...", rc), rc, mbox); } /* let's get it on */ rc = imap_exec(idata, NULL, IMAP_CMD_FAIL_OK); if (rc == -2) { if (triedcreate) { mutt_debug(1, "Already tried to create mailbox %s\n", mbox); break; } /* bail out if command failed for reasons other than nonexistent target */ if (mutt_str_strncasecmp(imap_get_qualifier(idata->buf), "[TRYCREATE]", 11) != 0) break; mutt_debug(3, "server suggests TRYCREATE\n"); snprintf(prompt, sizeof(prompt), _("Create %s?"), mbox); if (Confirmcreate && mutt_yesorno(prompt, 1) != MUTT_YES) { mutt_clear_error(); goto out; } if (imap_create_mailbox(idata, mbox) < 0) break; triedcreate = true; } } while (rc == -2); if (rc != 0) { imap_error("imap_fast_trash", idata->buf); goto out; } rc = 0; out: mutt_buffer_free(&sync_cmd); FREE(&mx.mbox); return (rc < 0) ? -1 : rc; } /** * imap_mbox_open - Implements MxOps::mbox_open() */ static int imap_mbox_open(struct Context *ctx) { struct ImapData *idata = NULL; struct ImapStatus *status = NULL; char buf[PATH_MAX]; char bufout[PATH_MAX]; int count = 0; struct ImapMbox mx, pmx; int rc; if (imap_parse_path(ctx->path, &mx)) { mutt_error(_("%s is an invalid IMAP path"), ctx->path); return -1; } /* we require a connection which isn't currently in IMAP_SELECTED state */ idata = imap_conn_find(&(mx.account), MUTT_IMAP_CONN_NOSELECT); if (!idata) goto fail_noidata; if (idata->state < IMAP_AUTHENTICATED) goto fail; /* once again the context is new */ ctx->data = idata; /* Clean up path and replace the one in the ctx */ imap_fix_path(idata, mx.mbox, buf, sizeof(buf)); if (!*buf) mutt_str_strfcpy(buf, "INBOX", sizeof(buf)); FREE(&(idata->mailbox)); idata->mailbox = mutt_str_strdup(buf); imap_qualify_path(buf, sizeof(buf), &mx, idata->mailbox); FREE(&(ctx->path)); FREE(&(ctx->realpath)); ctx->path = mutt_str_strdup(buf); ctx->realpath = mutt_str_strdup(ctx->path); idata->ctx = ctx; /* clear mailbox status */ idata->status = false; memset(idata->ctx->rights, 0, sizeof(idata->ctx->rights)); idata->new_mail_count = 0; idata->max_msn = 0; mutt_message(_("Selecting %s..."), idata->mailbox); imap_munge_mbox_name(idata, buf, sizeof(buf), idata->mailbox); /* pipeline ACL test */ if (mutt_bit_isset(idata->capabilities, ACL)) { snprintf(bufout, sizeof(bufout), "MYRIGHTS %s", buf); imap_exec(idata, bufout, IMAP_CMD_QUEUE); } /* assume we have all rights if ACL is unavailable */ else { mutt_bit_set(idata->ctx->rights, MUTT_ACL_LOOKUP); mutt_bit_set(idata->ctx->rights, MUTT_ACL_READ); mutt_bit_set(idata->ctx->rights, MUTT_ACL_SEEN); mutt_bit_set(idata->ctx->rights, MUTT_ACL_WRITE); mutt_bit_set(idata->ctx->rights, MUTT_ACL_INSERT); mutt_bit_set(idata->ctx->rights, MUTT_ACL_POST); mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE); mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE); } /* pipeline the postponed count if possible */ pmx.mbox = NULL; if (mx_is_imap(Postponed) && !imap_parse_path(Postponed, &pmx) && mutt_account_match(&pmx.account, &mx.account)) { imap_status(Postponed, 1); } FREE(&pmx.mbox); if (ImapCheckSubscribed) imap_exec(idata, "LSUB \"\" \"*\"", IMAP_CMD_QUEUE); snprintf(bufout, sizeof(bufout), "%s %s", ctx->readonly ? "EXAMINE" : "SELECT", buf); idata->state = IMAP_SELECTED; imap_cmd_start(idata, bufout); status = imap_mboxcache_get(idata, idata->mailbox, 1); do { char *pc = NULL; rc = imap_cmd_step(idata); if (rc != IMAP_CMD_CONTINUE) break; pc = idata->buf + 2; /* Obtain list of available flags here, may be overridden by a * PERMANENTFLAGS tag in the OK response */ if (mutt_str_strncasecmp("FLAGS", pc, 5) == 0) { /* don't override PERMANENTFLAGS */ if (STAILQ_EMPTY(&idata->flags)) { mutt_debug(3, "Getting mailbox FLAGS\n"); pc = get_flags(&idata->flags, pc); if (!pc) goto fail; } } /* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */ else if (mutt_str_strncasecmp("OK [PERMANENTFLAGS", pc, 18) == 0) { mutt_debug(3, "Getting mailbox PERMANENTFLAGS\n"); /* safe to call on NULL */ mutt_list_free(&idata->flags); /* skip "OK [PERMANENT" so syntax is the same as FLAGS */ pc += 13; pc = get_flags(&(idata->flags), pc); if (!pc) goto fail; } /* save UIDVALIDITY for the header cache */ else if (mutt_str_strncasecmp("OK [UIDVALIDITY", pc, 14) == 0) { mutt_debug(3, "Getting mailbox UIDVALIDITY\n"); pc += 3; pc = imap_next_word(pc); if (mutt_str_atoui(pc, &idata->uid_validity) < 0) goto fail; status->uidvalidity = idata->uid_validity; } else if (mutt_str_strncasecmp("OK [UIDNEXT", pc, 11) == 0) { mutt_debug(3, "Getting mailbox UIDNEXT\n"); pc += 3; pc = imap_next_word(pc); if (mutt_str_atoui(pc, &idata->uidnext) < 0) goto fail; status->uidnext = idata->uidnext; } else { pc = imap_next_word(pc); if (mutt_str_strncasecmp("EXISTS", pc, 6) == 0) { count = idata->new_mail_count; idata->new_mail_count = 0; } } } while (rc == IMAP_CMD_CONTINUE); if (rc == IMAP_CMD_NO) { char *s = imap_next_word(idata->buf); /* skip seq */ s = imap_next_word(s); /* Skip response */ mutt_error("%s", s); goto fail; } if (rc != IMAP_CMD_OK) goto fail; /* check for READ-ONLY notification */ if ((mutt_str_strncasecmp(imap_get_qualifier(idata->buf), "[READ-ONLY]", 11) == 0) && !mutt_bit_isset(idata->capabilities, ACL)) { mutt_debug(2, "Mailbox is read-only.\n"); ctx->readonly = true; } /* dump the mailbox flags we've found */ if (DebugLevel > 2) { if (STAILQ_EMPTY(&idata->flags)) mutt_debug(3, "No folder flags found\n"); else { struct ListNode *np; struct Buffer flag_buffer; mutt_buffer_init(&flag_buffer); mutt_buffer_printf(&flag_buffer, "Mailbox flags: "); STAILQ_FOREACH(np, &idata->flags, entries) { mutt_buffer_printf(&flag_buffer, "[%s] ", np->data); } mutt_debug(3, "%s\n", flag_buffer.data); FREE(&flag_buffer.data); } } if (!(mutt_bit_isset(idata->ctx->rights, MUTT_ACL_DELETE) || mutt_bit_isset(idata->ctx->rights, MUTT_ACL_SEEN) || mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE) || mutt_bit_isset(idata->ctx->rights, MUTT_ACL_INSERT))) { ctx->readonly = true; } ctx->hdrmax = count; ctx->hdrs = mutt_mem_calloc(count, sizeof(struct Header *)); ctx->v2r = mutt_mem_calloc(count, sizeof(int)); ctx->msgcount = 0; if (count && (imap_read_headers(idata, 1, count) < 0)) { mutt_error(_("Error opening mailbox")); goto fail; } mutt_debug(2, "msgcount is %d\n", ctx->msgcount); FREE(&mx.mbox); return 0; fail: if (idata->state == IMAP_SELECTED) idata->state = IMAP_AUTHENTICATED; fail_noidata: FREE(&mx.mbox); return -1; } /** * imap_mbox_open_append - Implements MxOps::mbox_open_append() */ static int imap_mbox_open_append(struct Context *ctx, int flags) { struct ImapData *idata = NULL; char mailbox[PATH_MAX]; struct ImapMbox mx; int rc; if (imap_parse_path(ctx->path, &mx)) return -1; /* in APPEND mode, we appear to hijack an existing IMAP connection - * ctx is brand new and mostly empty */ idata = imap_conn_find(&(mx.account), 0); if (!idata) { FREE(&mx.mbox); return -1; } ctx->data = idata; imap_fix_path(idata, mx.mbox, mailbox, sizeof(mailbox)); if (!*mailbox) mutt_str_strfcpy(mailbox, "INBOX", sizeof(mailbox)); FREE(&mx.mbox); rc = imap_access(ctx->path); if (rc == 0) return 0; if (rc == -1) return -1; char buf[PATH_MAX + 64]; snprintf(buf, sizeof(buf), _("Create %s?"), mailbox); if (Confirmcreate && mutt_yesorno(buf, 1) != MUTT_YES) return -1; if (imap_create_mailbox(idata, mailbox) < 0) return -1; return 0; } /** * imap_mbox_close - Implements MxOps::mbox_close() * @retval 0 Always */ static int imap_mbox_close(struct Context *ctx) { struct ImapData *idata = ctx->data; /* Check to see if the mailbox is actually open */ if (!idata) return 0; /* imap_mbox_open_append() borrows the struct ImapData temporarily, * just for the connection, but does not set idata->ctx to the * open-append ctx. * * So when these are equal, it means we are actually closing the * mailbox and should clean up idata. Otherwise, we don't want to * touch idata - it's still being used. */ if (ctx == idata->ctx) { if (idata->status != IMAP_FATAL && idata->state >= IMAP_SELECTED) { /* mx_mbox_close won't sync if there are no deleted messages * and the mailbox is unchanged, so we may have to close here */ if (!ctx->deleted) imap_exec(idata, "CLOSE", IMAP_CMD_QUEUE); idata->state = IMAP_AUTHENTICATED; } idata->reopen &= IMAP_REOPEN_ALLOW; FREE(&(idata->mailbox)); mutt_list_free(&idata->flags); idata->ctx = NULL; mutt_hash_destroy(&idata->uid_hash); FREE(&idata->msn_index); idata->msn_index_size = 0; idata->max_msn = 0; for (int i = 0; i < IMAP_CACHE_LEN; i++) { if (idata->cache[i].path) { unlink(idata->cache[i].path); FREE(&idata->cache[i].path); } } mutt_bcache_close(&idata->bcache); } /* free IMAP part of headers */ for (int i = 0; i < ctx->msgcount; i++) { /* mailbox may not have fully loaded */ if (ctx->hdrs[i] && ctx->hdrs[i]->data) imap_free_header_data((struct ImapHeaderData **) &(ctx->hdrs[i]->data)); } return 0; } /** * imap_msg_open_new - Implements MxOps::msg_open_new() */ static int imap_msg_open_new(struct Context *ctx, struct Message *msg, struct Header *hdr) { char tmp[PATH_MAX]; mutt_mktemp(tmp, sizeof(tmp)); msg->fp = mutt_file_fopen(tmp, "w"); if (!msg->fp) { mutt_perror(tmp); return -1; } msg->path = mutt_str_strdup(tmp); return 0; } /** * imap_mbox_check - Implements MxOps::mbox_check() * @param ctx Context * @param index_hint Remember our place in the index * @retval >0 Success, e.g. #MUTT_REOPENED * @retval -1 Failure */ static int imap_mbox_check(struct Context *ctx, int *index_hint) { int rc; (void) index_hint; imap_allow_reopen(ctx); rc = imap_check(ctx->data, 0); imap_disallow_reopen(ctx); return rc; } /** * imap_sync_mailbox - Sync all the changes to the server * @param ctx Context * @param expunge 0 or 1 - do expunge? * @retval 0 Success * @retval -1 Error */ int imap_sync_mailbox(struct Context *ctx, int expunge) { struct Context *appendctx = NULL; struct Header *h = NULL; struct Header **hdrs = NULL; int oldsort; int rc; struct ImapData *idata = ctx->data; if (idata->state < IMAP_SELECTED) { mutt_debug(2, "no mailbox selected\n"); return -1; } /* This function is only called when the calling code expects the context * to be changed. */ imap_allow_reopen(ctx); rc = imap_check(idata, 0); if (rc != 0) return rc; /* if we are expunging anyway, we can do deleted messages very quickly... */ if (expunge && mutt_bit_isset(ctx->rights, MUTT_ACL_DELETE)) { rc = imap_exec_msgset(idata, "UID STORE", "+FLAGS.SILENT (\\Deleted)", MUTT_DELETED, 1, 0); if (rc < 0) { mutt_error(_("Expunge failed")); goto out; } if (rc > 0) { /* mark these messages as unchanged so second pass ignores them. Done * here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */ for (int i = 0; i < ctx->msgcount; i++) if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->changed) ctx->hdrs[i]->active = false; mutt_message(ngettext("Marking %d message deleted...", "Marking %d messages deleted...", rc), rc); } } #ifdef USE_HCACHE idata->hcache = imap_hcache_open(idata, NULL); #endif /* save messages with real (non-flag) changes */ for (int i = 0; i < ctx->msgcount; i++) { h = ctx->hdrs[i]; if (h->deleted) { imap_cache_del(idata, h); #ifdef USE_HCACHE imap_hcache_del(idata, HEADER_DATA(h)->uid); #endif } if (h->active && h->changed) { #ifdef USE_HCACHE imap_hcache_put(idata, h); #endif /* if the message has been rethreaded or attachments have been deleted * we delete the message and reupload it. * This works better if we're expunging, of course. */ if ((h->env && (h->env->refs_changed || h->env->irt_changed)) || h->attach_del || h->xlabel_changed) { /* L10N: The plural is choosen by the last %d, i.e. the total number */ mutt_message(ngettext("Saving changed message... [%d/%d]", "Saving changed messages... [%d/%d]", ctx->msgcount), i + 1, ctx->msgcount); if (!appendctx) appendctx = mx_mbox_open(ctx->path, MUTT_APPEND | MUTT_QUIET, NULL); if (!appendctx) mutt_debug(1, "Error opening mailbox in append mode\n"); else mutt_save_message_ctx(h, 1, 0, 0, appendctx); h->xlabel_changed = false; } } } #ifdef USE_HCACHE imap_hcache_close(idata); #endif /* presort here to avoid doing 10 resorts in imap_exec_msgset */ oldsort = Sort; if (Sort != SORT_ORDER) { hdrs = ctx->hdrs; ctx->hdrs = mutt_mem_malloc(ctx->msgcount * sizeof(struct Header *)); memcpy(ctx->hdrs, hdrs, ctx->msgcount * sizeof(struct Header *)); Sort = SORT_ORDER; qsort(ctx->hdrs, ctx->msgcount, sizeof(struct Header *), mutt_get_sort_func(SORT_ORDER)); } rc = sync_helper(idata, MUTT_ACL_DELETE, MUTT_DELETED, "\\Deleted"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_WRITE, MUTT_FLAG, "\\Flagged"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_WRITE, MUTT_OLD, "Old"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_SEEN, MUTT_READ, "\\Seen"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_WRITE, MUTT_REPLIED, "\\Answered"); if (oldsort != Sort) { Sort = oldsort; FREE(&ctx->hdrs); ctx->hdrs = hdrs; } /* Flush the queued flags if any were changed in sync_helper. */ if (rc > 0) if (imap_exec(idata, NULL, 0) != IMAP_CMD_OK) rc = -1; if (rc < 0) { if (ctx->closing) { if (mutt_yesorno(_("Error saving flags. Close anyway?"), 0) == MUTT_YES) { rc = 0; idata->state = IMAP_AUTHENTICATED; goto out; } } else mutt_error(_("Error saving flags")); rc = -1; goto out; } /* Update local record of server state to reflect the synchronization just * completed. imap_read_headers always overwrites hcache-origin flags, so * there is no need to mutate the hcache after flag-only changes. */ for (int i = 0; i < ctx->msgcount; i++) { HEADER_DATA(ctx->hdrs[i])->deleted = ctx->hdrs[i]->deleted; HEADER_DATA(ctx->hdrs[i])->flagged = ctx->hdrs[i]->flagged; HEADER_DATA(ctx->hdrs[i])->old = ctx->hdrs[i]->old; HEADER_DATA(ctx->hdrs[i])->read = ctx->hdrs[i]->read; HEADER_DATA(ctx->hdrs[i])->replied = ctx->hdrs[i]->replied; ctx->hdrs[i]->changed = false; } ctx->changed = false; /* We must send an EXPUNGE command if we're not closing. */ if (expunge && !(ctx->closing) && mutt_bit_isset(ctx->rights, MUTT_ACL_DELETE)) { mutt_message(_("Expunging messages from server...")); /* Set expunge bit so we don't get spurious reopened messages */ idata->reopen |= IMAP_EXPUNGE_EXPECTED; if (imap_exec(idata, "EXPUNGE", 0) != 0) { idata->reopen &= ~IMAP_EXPUNGE_EXPECTED; imap_error(_("imap_sync_mailbox: EXPUNGE failed"), idata->buf); rc = -1; goto out; } idata->reopen &= ~IMAP_EXPUNGE_EXPECTED; } if (expunge && ctx->closing) { imap_exec(idata, "CLOSE", IMAP_CMD_QUEUE); idata->state = IMAP_AUTHENTICATED; } if (MessageCacheClean) imap_cache_clean(idata); rc = 0; out: if (appendctx) { mx_fastclose_mailbox(appendctx); FREE(&appendctx); } return rc; } /** * imap_tags_edit - Implements MxOps::tags_edit() */ static int imap_tags_edit(struct Context *ctx, const char *tags, char *buf, size_t buflen) { char *new = NULL; char *checker = NULL; struct ImapData *idata = (struct ImapData *) ctx->data; /* Check for \* flags capability */ if (!imap_has_flag(&idata->flags, NULL)) { mutt_error(_("IMAP server doesn't support custom flags")); return -1; } *buf = '\0'; if (tags) strncpy(buf, tags, buflen); if (mutt_get_field("Tags: ", buf, buflen, 0) != 0) return -1; /* each keyword must be atom defined by rfc822 as: * * atom = 1*<any CHAR except specials, SPACE and CTLs> * CHAR = ( 0.-127. ) * specials = "(" / ")" / "<" / ">" / "@" * / "," / ";" / ":" / "\" / <"> * / "." / "[" / "]" * SPACE = ( 32. ) * CTLS = ( 0.-31., 127.) * * And must be separated by one space. */ new = buf; checker = buf; SKIPWS(checker); while (*checker != '\0') { if (*checker < 32 || *checker >= 127 || // We allow space because it's the separator *checker == 40 || // ( *checker == 41 || // ) *checker == 60 || // < *checker == 62 || // > *checker == 64 || // @ *checker == 44 || // , *checker == 59 || // ; *checker == 58 || // : *checker == 92 || // backslash *checker == 34 || // " *checker == 46 || // . *checker == 91 || // [ *checker == 93) // ] { mutt_error(_("Invalid IMAP flags")); return 0; } /* Skip duplicate space */ while (*checker == ' ' && *(checker + 1) == ' ') checker++; /* copy char to new and go the next one */ *new ++ = *checker++; } *new = '\0'; new = buf; /* rewind */ mutt_str_remove_trailing_ws(new); if (mutt_str_strcmp(tags, buf) == 0) return 0; return 1; } /** * imap_tags_commit - Implements MxOps::tags_commit() * * This method update the server flags on the server by * removing the last know custom flags of a header * and adds the local flags * * If everything success we push the local flags to the * last know custom flags (flags_remote). * * Also this method check that each flags is support by the server * first and remove unsupported one. */ static int imap_tags_commit(struct Context *ctx, struct Header *hdr, char *buf) { struct Buffer *cmd = NULL; char uid[11]; struct ImapData *idata = ctx->data; if (*buf == '\0') buf = NULL; if (!mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE)) return 0; snprintf(uid, sizeof(uid), "%u", HEADER_DATA(hdr)->uid); /* Remove old custom flags */ if (HEADER_DATA(hdr)->flags_remote) { cmd = mutt_buffer_new(); if (!cmd) { mutt_debug(1, "unable to allocate buffer\n"); return -1; } cmd->dptr = cmd->data; mutt_buffer_addstr(cmd, "UID STORE "); mutt_buffer_addstr(cmd, uid); mutt_buffer_addstr(cmd, " -FLAGS.SILENT ("); mutt_buffer_addstr(cmd, HEADER_DATA(hdr)->flags_remote); mutt_buffer_addstr(cmd, ")"); /* Should we return here, or we are fine and we could * continue to add new flags * */ if (imap_exec(idata, cmd->data, 0) != 0) { mutt_buffer_free(&cmd); return -1; } mutt_buffer_free(&cmd); } /* Add new custom flags */ if (buf) { cmd = mutt_buffer_new(); if (!cmd) { mutt_debug(1, "fail to remove old flags\n"); return -1; } cmd->dptr = cmd->data; mutt_buffer_addstr(cmd, "UID STORE "); mutt_buffer_addstr(cmd, uid); mutt_buffer_addstr(cmd, " +FLAGS.SILENT ("); mutt_buffer_addstr(cmd, buf); mutt_buffer_addstr(cmd, ")"); if (imap_exec(idata, cmd->data, 0) != 0) { mutt_debug(1, "fail to add new flags\n"); mutt_buffer_free(&cmd); return -1; } mutt_buffer_free(&cmd); } /* We are good sync them */ mutt_debug(1, "NEW TAGS: %d\n", buf); driver_tags_replace(&hdr->tags, buf); FREE(&HEADER_DATA(hdr)->flags_remote); HEADER_DATA(hdr)->flags_remote = driver_tags_get_with_hidden(&hdr->tags); return 0; } // clang-format off /** * struct mx_imap_ops - Mailbox callback functions for IMAP mailboxes */ struct MxOps mx_imap_ops = { .mbox_open = imap_mbox_open, .mbox_open_append = imap_mbox_open_append, .mbox_check = imap_mbox_check, .mbox_sync = NULL, /* imap syncing is handled by imap_sync_mailbox */ .mbox_close = imap_mbox_close, .msg_open = imap_msg_open, .msg_open_new = imap_msg_open_new, .msg_commit = imap_msg_commit, .msg_close = imap_msg_close, .tags_edit = imap_tags_edit, .tags_commit = imap_tags_commit, }; // clang-format on
./CrossVul/dataset_final_sorted/CWE-77/c/good_251_2
crossvul-cpp_data_bad_251_1
/** * @file * Send/receive commands to/from an IMAP server * * @authors * Copyright (C) 1996-1998,2010,2012 Michael R. Elkins <me@mutt.org> * Copyright (C) 1996-1999 Brandon Long <blong@fiction.net> * Copyright (C) 1999-2009,2011 Brendan Cully <brendan@kublai.com> * * @copyright * 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, see <http://www.gnu.org/licenses/>. */ /** * @page imap_command Send/receive commands to/from an IMAP server * * Send/receive commands to/from an IMAP server */ #include "config.h" #include <ctype.h> #include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "imap_private.h" #include "mutt/mutt.h" #include "conn/conn.h" #include "buffy.h" #include "context.h" #include "globals.h" #include "header.h" #include "imap/imap.h" #include "mailbox.h" #include "message.h" #include "mutt_account.h" #include "mutt_menu.h" #include "mutt_socket.h" #include "mx.h" #include "options.h" #include "protos.h" #include "url.h" #define IMAP_CMD_BUFSIZE 512 /** * Capabilities - Server capabilities strings that we understand * * @note This must be kept in the same order as ImapCaps. * * @note Gmail documents one string but use another, so we support both. */ static const char *const Capabilities[] = { "IMAP4", "IMAP4rev1", "STATUS", "ACL", "NAMESPACE", "AUTH=CRAM-MD5", "AUTH=GSSAPI", "AUTH=ANONYMOUS", "STARTTLS", "LOGINDISABLED", "IDLE", "SASL-IR", "ENABLE", "X-GM-EXT-1", "X-GM-EXT1", NULL, }; /** * cmd_queue_full - Is the IMAP command queue full? * @param idata Server data * @retval true Queue is full */ static bool cmd_queue_full(struct ImapData *idata) { if ((idata->nextcmd + 1) % idata->cmdslots == idata->lastcmd) return true; return false; } /** * cmd_new - Create and queue a new command control block * @param idata IMAP data * @retval NULL if the pipeline is full * @retval ptr New command */ static struct ImapCommand *cmd_new(struct ImapData *idata) { struct ImapCommand *cmd = NULL; if (cmd_queue_full(idata)) { mutt_debug(3, "IMAP command queue full\n"); return NULL; } cmd = idata->cmds + idata->nextcmd; idata->nextcmd = (idata->nextcmd + 1) % idata->cmdslots; snprintf(cmd->seq, sizeof(cmd->seq), "a%04u", idata->seqno++); if (idata->seqno > 9999) idata->seqno = 0; cmd->state = IMAP_CMD_NEW; return cmd; } /** * cmd_queue - Add a IMAP command to the queue * @param idata Server data * @param cmdstr Command string * @param flags Server flags, e.g. #IMAP_CMD_POLL * @retval 0 Success * @retval <0 Failure, e.g. #IMAP_CMD_BAD * * If the queue is full, attempts to drain it. */ static int cmd_queue(struct ImapData *idata, const char *cmdstr, int flags) { if (cmd_queue_full(idata)) { mutt_debug(3, "Draining IMAP command pipeline\n"); const int rc = imap_exec(idata, NULL, IMAP_CMD_FAIL_OK | (flags & IMAP_CMD_POLL)); if (rc < 0 && rc != -2) return rc; } struct ImapCommand *cmd = cmd_new(idata); if (!cmd) return IMAP_CMD_BAD; if (mutt_buffer_printf(idata->cmdbuf, "%s %s\r\n", cmd->seq, cmdstr) < 0) return IMAP_CMD_BAD; return 0; } /** * cmd_handle_fatal - When ImapData is in fatal state, do what we can * @param idata Server data */ static void cmd_handle_fatal(struct ImapData *idata) { idata->status = IMAP_FATAL; if ((idata->state >= IMAP_SELECTED) && (idata->reopen & IMAP_REOPEN_ALLOW)) { mx_fastclose_mailbox(idata->ctx); mutt_socket_close(idata->conn); mutt_error(_("Mailbox %s@%s closed"), idata->conn->account.login, idata->conn->account.host); idata->state = IMAP_DISCONNECTED; } imap_close_connection(idata); if (!idata->recovering) { idata->recovering = true; if (imap_conn_find(&idata->conn->account, 0)) mutt_clear_error(); idata->recovering = false; } } /** * cmd_start - Start a new IMAP command * @param idata Server data * @param cmdstr Command string * @param flags Command flags, e.g. #IMAP_CMD_QUEUE * @retval 0 Success * @retval <0 Failure, e.g. #IMAP_CMD_BAD */ static int cmd_start(struct ImapData *idata, const char *cmdstr, int flags) { int rc; if (idata->status == IMAP_FATAL) { cmd_handle_fatal(idata); return -1; } if (cmdstr && ((rc = cmd_queue(idata, cmdstr, flags)) < 0)) return rc; if (flags & IMAP_CMD_QUEUE) return 0; if (idata->cmdbuf->dptr == idata->cmdbuf->data) return IMAP_CMD_BAD; rc = mutt_socket_send_d(idata->conn, idata->cmdbuf->data, (flags & IMAP_CMD_PASS) ? IMAP_LOG_PASS : IMAP_LOG_CMD); idata->cmdbuf->dptr = idata->cmdbuf->data; /* unidle when command queue is flushed */ if (idata->state == IMAP_IDLE) idata->state = IMAP_SELECTED; return (rc < 0) ? IMAP_CMD_BAD : 0; } /** * cmd_status - parse response line for tagged OK/NO/BAD * @param s Status string from server * @retval 0 Success * @retval <0 Failure, e.g. #IMAP_CMD_BAD */ static int cmd_status(const char *s) { s = imap_next_word((char *) s); if (mutt_str_strncasecmp("OK", s, 2) == 0) return IMAP_CMD_OK; if (mutt_str_strncasecmp("NO", s, 2) == 0) return IMAP_CMD_NO; return IMAP_CMD_BAD; } /** * cmd_parse_expunge - Parse expunge command * @param idata Server data * @param s String containing MSN of message to expunge * * cmd_parse_expunge: mark headers with new sequence ID and mark idata to be * reopened at our earliest convenience */ static void cmd_parse_expunge(struct ImapData *idata, const char *s) { unsigned int exp_msn; struct Header *h = NULL; mutt_debug(2, "Handling EXPUNGE\n"); if (mutt_str_atoui(s, &exp_msn) < 0 || exp_msn < 1 || exp_msn > idata->max_msn) return; h = idata->msn_index[exp_msn - 1]; if (h) { /* imap_expunge_mailbox() will rewrite h->index. * It needs to resort using SORT_ORDER anyway, so setting to INT_MAX * makes the code simpler and possibly more efficient. */ h->index = INT_MAX; HEADER_DATA(h)->msn = 0; } /* decrement seqno of those above. */ for (unsigned int cur = exp_msn; cur < idata->max_msn; cur++) { h = idata->msn_index[cur]; if (h) HEADER_DATA(h)->msn--; idata->msn_index[cur - 1] = h; } idata->msn_index[idata->max_msn - 1] = NULL; idata->max_msn--; idata->reopen |= IMAP_EXPUNGE_PENDING; } /** * cmd_parse_fetch - Load fetch response into ImapData * @param idata Server data * @param s String containing MSN of message to fetch * * Currently only handles unanticipated FETCH responses, and only FLAGS data. * We get these if another client has changed flags for a mailbox we've * selected. Of course, a lot of code here duplicates code in message.c. */ static void cmd_parse_fetch(struct ImapData *idata, char *s) { unsigned int msn, uid; struct Header *h = NULL; int server_changes = 0; mutt_debug(3, "Handling FETCH\n"); if (mutt_str_atoui(s, &msn) < 0 || msn < 1 || msn > idata->max_msn) { mutt_debug(3, "#1 FETCH response ignored for this message\n"); return; } h = idata->msn_index[msn - 1]; if (!h || !h->active) { mutt_debug(3, "#2 FETCH response ignored for this message\n"); return; } mutt_debug(2, "Message UID %u updated\n", HEADER_DATA(h)->uid); /* skip FETCH */ s = imap_next_word(s); s = imap_next_word(s); if (*s != '(') { mutt_debug(1, "Malformed FETCH response\n"); return; } s++; while (*s) { SKIPWS(s); if (mutt_str_strncasecmp("FLAGS", s, 5) == 0) { imap_set_flags(idata, h, s, &server_changes); if (server_changes) { /* If server flags could conflict with neomutt's flags, reopen the mailbox. */ if (h->changed) idata->reopen |= IMAP_EXPUNGE_PENDING; else idata->check_status = IMAP_FLAGS_PENDING; } return; } else if (mutt_str_strncasecmp("UID", s, 3) == 0) { s += 3; SKIPWS(s); if (mutt_str_atoui(s, &uid) < 0) { mutt_debug(2, "Illegal UID. Skipping update.\n"); return; } if (uid != HEADER_DATA(h)->uid) { mutt_debug(2, "FETCH UID vs MSN mismatch. Skipping update.\n"); return; } s = imap_next_word(s); } else if (*s == ')') s++; /* end of request */ else if (*s) { mutt_debug(2, "Only handle FLAGS updates\n"); return; } } } /** * cmd_parse_capability - set capability bits according to CAPABILITY response * @param idata Server data * @param s Command string with capabilities */ static void cmd_parse_capability(struct ImapData *idata, char *s) { mutt_debug(3, "Handling CAPABILITY\n"); s = imap_next_word(s); char *bracket = strchr(s, ']'); if (bracket) *bracket = '\0'; FREE(&idata->capstr); idata->capstr = mutt_str_strdup(s); memset(idata->capabilities, 0, sizeof(idata->capabilities)); while (*s) { for (int i = 0; i < CAPMAX; i++) { if (mutt_str_word_casecmp(Capabilities[i], s) == 0) { mutt_bit_set(idata->capabilities, i); mutt_debug(4, " Found capability \"%s\": %d\n", Capabilities[i], i); break; } } s = imap_next_word(s); } } /** * cmd_parse_list - Parse a server LIST command (list mailboxes) * @param idata Server data * @param s Command string with folder list */ static void cmd_parse_list(struct ImapData *idata, char *s) { struct ImapList *list = NULL; struct ImapList lb; char delimbuf[5]; /* worst case: "\\"\0 */ unsigned int litlen; if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST) list = (struct ImapList *) idata->cmddata; else list = &lb; memset(list, 0, sizeof(struct ImapList)); /* flags */ s = imap_next_word(s); if (*s != '(') { mutt_debug(1, "Bad LIST response\n"); return; } s++; while (*s) { if (mutt_str_strncasecmp(s, "\\NoSelect", 9) == 0) list->noselect = true; else if (mutt_str_strncasecmp(s, "\\NoInferiors", 12) == 0) list->noinferiors = true; /* See draft-gahrns-imap-child-mailbox-?? */ else if (mutt_str_strncasecmp(s, "\\HasNoChildren", 14) == 0) list->noinferiors = true; s = imap_next_word(s); if (*(s - 2) == ')') break; } /* Delimiter */ if (mutt_str_strncasecmp(s, "NIL", 3) != 0) { delimbuf[0] = '\0'; mutt_str_strcat(delimbuf, 5, s); imap_unquote_string(delimbuf); list->delim = delimbuf[0]; } /* Name */ s = imap_next_word(s); /* Notes often responds with literals here. We need a real tokenizer. */ if (imap_get_literal_count(s, &litlen) == 0) { if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE) { idata->status = IMAP_FATAL; return; } list->name = idata->buf; } else { imap_unmunge_mbox_name(idata, s); list->name = s; } if (list->name[0] == '\0') { idata->delim = list->delim; mutt_debug(3, "Root delimiter: %c\n", idata->delim); } } /** * cmd_parse_lsub - Parse a server LSUB (list subscribed mailboxes) * @param idata Server data * @param s Command string with folder list */ static void cmd_parse_lsub(struct ImapData *idata, char *s) { char buf[STRING]; char errstr[STRING]; struct Buffer err, token; struct Url url; struct ImapList list; if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST) { /* caller will handle response itself */ cmd_parse_list(idata, s); return; } if (!ImapCheckSubscribed) return; idata->cmdtype = IMAP_CT_LIST; idata->cmddata = &list; cmd_parse_list(idata, s); idata->cmddata = NULL; /* noselect is for a gmail quirk (#3445) */ if (!list.name || list.noselect) return; mutt_debug(3, "Subscribing to %s\n", list.name); mutt_str_strfcpy(buf, "mailboxes \"", sizeof(buf)); mutt_account_tourl(&idata->conn->account, &url); /* escape \ and " */ imap_quote_string(errstr, sizeof(errstr), list.name); url.path = errstr + 1; url.path[strlen(url.path) - 1] = '\0'; if (mutt_str_strcmp(url.user, ImapUser) == 0) url.user = NULL; url_tostring(&url, buf + 11, sizeof(buf) - 11, 0); mutt_str_strcat(buf, sizeof(buf), "\""); mutt_buffer_init(&token); mutt_buffer_init(&err); err.data = errstr; err.dsize = sizeof(errstr); if (mutt_parse_rc_line(buf, &token, &err)) mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr); FREE(&token.data); } /** * cmd_parse_myrights - Set rights bits according to MYRIGHTS response * @param idata Server data * @param s Command string with rights info */ static void cmd_parse_myrights(struct ImapData *idata, const char *s) { mutt_debug(2, "Handling MYRIGHTS\n"); s = imap_next_word((char *) s); s = imap_next_word((char *) s); /* zero out current rights set */ memset(idata->ctx->rights, 0, sizeof(idata->ctx->rights)); while (*s && !isspace((unsigned char) *s)) { switch (*s) { case 'a': mutt_bit_set(idata->ctx->rights, MUTT_ACL_ADMIN); break; case 'e': mutt_bit_set(idata->ctx->rights, MUTT_ACL_EXPUNGE); break; case 'i': mutt_bit_set(idata->ctx->rights, MUTT_ACL_INSERT); break; case 'k': mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE); break; case 'l': mutt_bit_set(idata->ctx->rights, MUTT_ACL_LOOKUP); break; case 'p': mutt_bit_set(idata->ctx->rights, MUTT_ACL_POST); break; case 'r': mutt_bit_set(idata->ctx->rights, MUTT_ACL_READ); break; case 's': mutt_bit_set(idata->ctx->rights, MUTT_ACL_SEEN); break; case 't': mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE); break; case 'w': mutt_bit_set(idata->ctx->rights, MUTT_ACL_WRITE); break; case 'x': mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELMX); break; /* obsolete rights */ case 'c': mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE); mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELMX); break; case 'd': mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE); mutt_bit_set(idata->ctx->rights, MUTT_ACL_EXPUNGE); break; default: mutt_debug(1, "Unknown right: %c\n", *s); } s++; } } /** * cmd_parse_search - store SEARCH response for later use * @param idata Server data * @param s Command string with search results */ static void cmd_parse_search(struct ImapData *idata, const char *s) { unsigned int uid; struct Header *h = NULL; mutt_debug(2, "Handling SEARCH\n"); while ((s = imap_next_word((char *) s)) && *s != '\0') { if (mutt_str_atoui(s, &uid) < 0) continue; h = (struct Header *) mutt_hash_int_find(idata->uid_hash, uid); if (h) h->matched = true; } } /** * cmd_parse_status - Parse status from server * @param idata Server data * @param s Command string with status info * * first cut: just do buffy update. Later we may wish to cache all mailbox * information, even that not desired by buffy */ static void cmd_parse_status(struct ImapData *idata, char *s) { char *value = NULL; struct Buffy *inc = NULL; struct ImapMbox mx; struct ImapStatus *status = NULL; unsigned int olduv, oldun; unsigned int litlen; short new = 0; short new_msg_count = 0; char *mailbox = imap_next_word(s); /* We need a real tokenizer. */ if (imap_get_literal_count(mailbox, &litlen) == 0) { if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE) { idata->status = IMAP_FATAL; return; } mailbox = idata->buf; s = mailbox + litlen; *s = '\0'; s++; SKIPWS(s); } else { s = imap_next_word(mailbox); *(s - 1) = '\0'; imap_unmunge_mbox_name(idata, mailbox); } status = imap_mboxcache_get(idata, mailbox, 1); olduv = status->uidvalidity; oldun = status->uidnext; if (*s++ != '(') { mutt_debug(1, "Error parsing STATUS\n"); return; } while (*s && *s != ')') { value = imap_next_word(s); errno = 0; const unsigned long ulcount = strtoul(value, &value, 10); if (((errno == ERANGE) && (ulcount == ULONG_MAX)) || ((unsigned int) ulcount != ulcount)) { mutt_debug(1, "Error parsing STATUS number\n"); return; } const unsigned int count = (unsigned int) ulcount; if (mutt_str_strncmp("MESSAGES", s, 8) == 0) { status->messages = count; new_msg_count = 1; } else if (mutt_str_strncmp("RECENT", s, 6) == 0) status->recent = count; else if (mutt_str_strncmp("UIDNEXT", s, 7) == 0) status->uidnext = count; else if (mutt_str_strncmp("UIDVALIDITY", s, 11) == 0) status->uidvalidity = count; else if (mutt_str_strncmp("UNSEEN", s, 6) == 0) status->unseen = count; s = value; if (*s && *s != ')') s = imap_next_word(s); } mutt_debug(3, "%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n", status->name, status->uidvalidity, status->uidnext, status->messages, status->recent, status->unseen); /* caller is prepared to handle the result herself */ if (idata->cmddata && idata->cmdtype == IMAP_CT_STATUS) { memcpy(idata->cmddata, status, sizeof(struct ImapStatus)); return; } mutt_debug(3, "Running default STATUS handler\n"); /* should perhaps move this code back to imap_buffy_check */ for (inc = Incoming; inc; inc = inc->next) { if (inc->magic != MUTT_IMAP) continue; if (imap_parse_path(inc->path, &mx) < 0) { mutt_debug(1, "Error parsing mailbox %s, skipping\n", inc->path); continue; } if (imap_account_match(&idata->conn->account, &mx.account)) { if (mx.mbox) { value = mutt_str_strdup(mx.mbox); imap_fix_path(idata, mx.mbox, value, mutt_str_strlen(value) + 1); FREE(&mx.mbox); } else value = mutt_str_strdup("INBOX"); if (value && (imap_mxcmp(mailbox, value) == 0)) { mutt_debug(3, "Found %s in buffy list (OV: %u ON: %u U: %d)\n", mailbox, olduv, oldun, status->unseen); if (MailCheckRecent) { if (olduv && olduv == status->uidvalidity) { if (oldun < status->uidnext) new = (status->unseen > 0); } else if (!olduv && !oldun) { /* first check per session, use recent. might need a flag for this. */ new = (status->recent > 0); } else new = (status->unseen > 0); } else new = (status->unseen > 0); #ifdef USE_SIDEBAR if ((inc->new != new) || (inc->msg_count != status->messages) || (inc->msg_unread != status->unseen)) { mutt_menu_set_current_redraw(REDRAW_SIDEBAR); } #endif inc->new = new; if (new_msg_count) inc->msg_count = status->messages; inc->msg_unread = status->unseen; if (inc->new) { /* force back to keep detecting new mail until the mailbox is opened */ status->uidnext = oldun; } FREE(&value); return; } FREE(&value); } FREE(&mx.mbox); } } /** * cmd_parse_enabled - Record what the server has enabled * @param idata Server data * @param s Command string containing acceptable encodings */ static void cmd_parse_enabled(struct ImapData *idata, const char *s) { mutt_debug(2, "Handling ENABLED\n"); while ((s = imap_next_word((char *) s)) && *s != '\0') { if ((mutt_str_strncasecmp(s, "UTF8=ACCEPT", 11) == 0) || (mutt_str_strncasecmp(s, "UTF8=ONLY", 9) == 0)) { idata->unicode = 1; } } } /** * cmd_handle_untagged - fallback parser for otherwise unhandled messages * @param idata Server data * @retval 0 Success * @retval -1 Failure */ static int cmd_handle_untagged(struct ImapData *idata) { unsigned int count = 0; char *s = imap_next_word(idata->buf); char *pn = imap_next_word(s); if ((idata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s)) { pn = s; s = imap_next_word(s); /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the * connection, so update that one. */ if (mutt_str_strncasecmp("EXISTS", s, 6) == 0) { mutt_debug(2, "Handling EXISTS\n"); /* new mail arrived */ if (mutt_str_atoui(pn, &count) < 0) { mutt_debug(1, "Malformed EXISTS: '%s'\n", pn); } if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn) { /* Notes 6.0.3 has a tendency to report fewer messages exist than * it should. */ mutt_debug(1, "Message count is out of sync\n"); return 0; } /* at least the InterChange server sends EXISTS messages freely, * even when there is no new mail */ else if (count == idata->max_msn) mutt_debug(3, "superfluous EXISTS message.\n"); else { if (!(idata->reopen & IMAP_EXPUNGE_PENDING)) { mutt_debug(2, "New mail in %s - %d messages total.\n", idata->mailbox, count); idata->reopen |= IMAP_NEWMAIL_PENDING; } idata->new_mail_count = count; } } /* pn vs. s: need initial seqno */ else if (mutt_str_strncasecmp("EXPUNGE", s, 7) == 0) cmd_parse_expunge(idata, pn); else if (mutt_str_strncasecmp("FETCH", s, 5) == 0) cmd_parse_fetch(idata, pn); } else if (mutt_str_strncasecmp("CAPABILITY", s, 10) == 0) cmd_parse_capability(idata, s); else if (mutt_str_strncasecmp("OK [CAPABILITY", s, 14) == 0) cmd_parse_capability(idata, pn); else if (mutt_str_strncasecmp("OK [CAPABILITY", pn, 14) == 0) cmd_parse_capability(idata, imap_next_word(pn)); else if (mutt_str_strncasecmp("LIST", s, 4) == 0) cmd_parse_list(idata, s); else if (mutt_str_strncasecmp("LSUB", s, 4) == 0) cmd_parse_lsub(idata, s); else if (mutt_str_strncasecmp("MYRIGHTS", s, 8) == 0) cmd_parse_myrights(idata, s); else if (mutt_str_strncasecmp("SEARCH", s, 6) == 0) cmd_parse_search(idata, s); else if (mutt_str_strncasecmp("STATUS", s, 6) == 0) cmd_parse_status(idata, s); else if (mutt_str_strncasecmp("ENABLED", s, 7) == 0) cmd_parse_enabled(idata, s); else if (mutt_str_strncasecmp("BYE", s, 3) == 0) { mutt_debug(2, "Handling BYE\n"); /* check if we're logging out */ if (idata->status == IMAP_BYE) return 0; /* server shut down our connection */ s += 3; SKIPWS(s); mutt_error("%s", s); cmd_handle_fatal(idata); return -1; } else if (ImapServernoise && (mutt_str_strncasecmp("NO", s, 2) == 0)) { mutt_debug(2, "Handling untagged NO\n"); /* Display the warning message from the server */ mutt_error("%s", s + 3); } return 0; } /** * imap_cmd_start - Given an IMAP command, send it to the server * @param idata Server data * @param cmdstr Command string to send * @retval 0 Success * @retval <0 Failure, e.g. #IMAP_CMD_BAD * * If cmdstr is NULL, sends queued commands. */ int imap_cmd_start(struct ImapData *idata, const char *cmdstr) { return cmd_start(idata, cmdstr, 0); } /** * imap_cmd_step - Reads server responses from an IMAP command * @param idata Server data * @retval 0 Success * @retval <0 Failure, e.g. #IMAP_CMD_BAD * * detects tagged completion response, handles untagged messages, can read * arbitrarily large strings (using malloc, so don't make it _too_ large!). */ int imap_cmd_step(struct ImapData *idata) { size_t len = 0; int c; int rc; int stillrunning = 0; struct ImapCommand *cmd = NULL; if (idata->status == IMAP_FATAL) { cmd_handle_fatal(idata); return IMAP_CMD_BAD; } /* read into buffer, expanding buffer as necessary until we have a full * line */ do { if (len == idata->blen) { mutt_mem_realloc(&idata->buf, idata->blen + IMAP_CMD_BUFSIZE); idata->blen = idata->blen + IMAP_CMD_BUFSIZE; mutt_debug(3, "grew buffer to %u bytes\n", idata->blen); } /* back up over '\0' */ if (len) len--; c = mutt_socket_readln(idata->buf + len, idata->blen - len, idata->conn); if (c <= 0) { mutt_debug(1, "Error reading server response.\n"); cmd_handle_fatal(idata); return IMAP_CMD_BAD; } len += c; } /* if we've read all the way to the end of the buffer, we haven't read a * full line (mutt_socket_readln strips the \r, so we always have at least * one character free when we've read a full line) */ while (len == idata->blen); /* don't let one large string make cmd->buf hog memory forever */ if ((idata->blen > IMAP_CMD_BUFSIZE) && (len <= IMAP_CMD_BUFSIZE)) { mutt_mem_realloc(&idata->buf, IMAP_CMD_BUFSIZE); idata->blen = IMAP_CMD_BUFSIZE; mutt_debug(3, "shrank buffer to %u bytes\n", idata->blen); } idata->lastread = time(NULL); /* handle untagged messages. The caller still gets its shot afterwards. */ if (((mutt_str_strncmp(idata->buf, "* ", 2) == 0) || (mutt_str_strncmp(imap_next_word(idata->buf), "OK [", 4) == 0)) && cmd_handle_untagged(idata)) { return IMAP_CMD_BAD; } /* server demands a continuation response from us */ if (idata->buf[0] == '+') return IMAP_CMD_RESPOND; /* Look for tagged command completions. * * Some response handlers can end up recursively calling * imap_cmd_step() and end up handling all tagged command * completions. * (e.g. FETCH->set_flag->set_header_color->~h pattern match.) * * Other callers don't even create an idata->cmds entry. * * For both these cases, we default to returning OK */ rc = IMAP_CMD_OK; c = idata->lastcmd; do { cmd = &idata->cmds[c]; if (cmd->state == IMAP_CMD_NEW) { if (mutt_str_strncmp(idata->buf, cmd->seq, SEQLEN) == 0) { if (!stillrunning) { /* first command in queue has finished - move queue pointer up */ idata->lastcmd = (idata->lastcmd + 1) % idata->cmdslots; } cmd->state = cmd_status(idata->buf); /* bogus - we don't know which command result to return here. Caller * should provide a tag. */ rc = cmd->state; } else stillrunning++; } c = (c + 1) % idata->cmdslots; } while (c != idata->nextcmd); if (stillrunning) rc = IMAP_CMD_CONTINUE; else { mutt_debug(3, "IMAP queue drained\n"); imap_cmd_finish(idata); } return rc; } /** * imap_code - Was the command successful * @param s IMAP command status * @retval 1 Command result was OK * @retval 0 If NO or BAD */ bool imap_code(const char *s) { return (cmd_status(s) == IMAP_CMD_OK); } /** * imap_cmd_trailer - Extra information after tagged command response if any * @param idata Server data * @retval ptr Extra command information (pointer into idata->buf) * @retval "" Error (static string) */ const char *imap_cmd_trailer(struct ImapData *idata) { static const char *notrailer = ""; const char *s = idata->buf; if (!s) { mutt_debug(2, "not a tagged response\n"); return notrailer; } s = imap_next_word((char *) s); if (!s || ((mutt_str_strncasecmp(s, "OK", 2) != 0) && (mutt_str_strncasecmp(s, "NO", 2) != 0) && (mutt_str_strncasecmp(s, "BAD", 3) != 0))) { mutt_debug(2, "not a command completion: %s\n", idata->buf); return notrailer; } s = imap_next_word((char *) s); if (!s) return notrailer; return s; } /** * imap_exec - Execute a command and wait for the response from the server * @param idata IMAP data * @param cmdstr Command to execute * @param flags Flags (see below) * @retval 0 Success * @retval -1 Failure * @retval -2 OK Failure * * Also, handle untagged responses. * * Flags: * * IMAP_CMD_FAIL_OK: the calling procedure can handle failure. * This is used for checking for a mailbox on append and login * * IMAP_CMD_PASS: command contains a password. Suppress logging. * * IMAP_CMD_QUEUE: only queue command, do not execute. * * IMAP_CMD_POLL: poll the socket for a response before running imap_cmd_step. */ int imap_exec(struct ImapData *idata, const char *cmdstr, int flags) { int rc; rc = cmd_start(idata, cmdstr, flags); if (rc < 0) { cmd_handle_fatal(idata); return -1; } if (flags & IMAP_CMD_QUEUE) return 0; if ((flags & IMAP_CMD_POLL) && (ImapPollTimeout > 0) && (mutt_socket_poll(idata->conn, ImapPollTimeout)) == 0) { mutt_error(_("Connection to %s timed out"), idata->conn->account.host); cmd_handle_fatal(idata); return -1; } /* Allow interruptions, particularly useful if there are network problems. */ mutt_sig_allow_interrupt(1); do rc = imap_cmd_step(idata); while (rc == IMAP_CMD_CONTINUE); mutt_sig_allow_interrupt(0); if (rc == IMAP_CMD_NO && (flags & IMAP_CMD_FAIL_OK)) return -2; if (rc != IMAP_CMD_OK) { if ((flags & IMAP_CMD_FAIL_OK) && idata->status != IMAP_FATAL) return -2; mutt_debug(1, "command failed: %s\n", idata->buf); return -1; } return 0; } /** * imap_cmd_finish - Attempt to perform cleanup * @param idata Server data * * Attempts to perform cleanup (eg fetch new mail if detected, do expunge). * Called automatically by imap_cmd_step(), but may be called at any time. * Called by imap_check_mailbox() just before the index is refreshed, for * instance. */ void imap_cmd_finish(struct ImapData *idata) { if (idata->status == IMAP_FATAL) { cmd_handle_fatal(idata); return; } if (!(idata->state >= IMAP_SELECTED) || idata->ctx->closing) return; if (idata->reopen & IMAP_REOPEN_ALLOW) { unsigned int count = idata->new_mail_count; if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && (idata->reopen & IMAP_NEWMAIL_PENDING) && count > idata->max_msn) { /* read new mail messages */ mutt_debug(2, "Fetching new mail\n"); /* check_status: curs_main uses imap_check_mailbox to detect * whether the index needs updating */ idata->check_status = IMAP_NEWMAIL_PENDING; imap_read_headers(idata, idata->max_msn + 1, count); } else if (idata->reopen & IMAP_EXPUNGE_PENDING) { mutt_debug(2, "Expunging mailbox\n"); imap_expunge_mailbox(idata); /* Detect whether we've gotten unexpected EXPUNGE messages */ if ((idata->reopen & IMAP_EXPUNGE_PENDING) && !(idata->reopen & IMAP_EXPUNGE_EXPECTED)) idata->check_status = IMAP_EXPUNGE_PENDING; idata->reopen &= ~(IMAP_EXPUNGE_PENDING | IMAP_NEWMAIL_PENDING | IMAP_EXPUNGE_EXPECTED); } } idata->status = false; } /** * imap_cmd_idle - Enter the IDLE state * @param idata Server data * @retval 0 Success * @retval <0 Failure, e.g. #IMAP_CMD_BAD */ int imap_cmd_idle(struct ImapData *idata) { int rc; if (cmd_start(idata, "IDLE", IMAP_CMD_POLL) < 0) { cmd_handle_fatal(idata); return -1; } if ((ImapPollTimeout > 0) && (mutt_socket_poll(idata->conn, ImapPollTimeout)) == 0) { mutt_error(_("Connection to %s timed out"), idata->conn->account.host); cmd_handle_fatal(idata); return -1; } do rc = imap_cmd_step(idata); while (rc == IMAP_CMD_CONTINUE); if (rc == IMAP_CMD_RESPOND) { /* successfully entered IDLE state */ idata->state = IMAP_IDLE; /* queue automatic exit when next command is issued */ mutt_buffer_printf(idata->cmdbuf, "DONE\r\n"); rc = IMAP_CMD_OK; } if (rc != IMAP_CMD_OK) { mutt_debug(1, "error starting IDLE\n"); return -1; } return 0; }
./CrossVul/dataset_final_sorted/CWE-77/c/bad_251_1
crossvul-cpp_data_good_251_0
/** * @file * IMAP login authentication method * * @authors * Copyright (C) 1999-2001,2005,2009 Brendan Cully <brendan@kublai.com> * * @copyright * 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, see <http://www.gnu.org/licenses/>. */ /** * @page imap_auth_login IMAP login authentication method * * IMAP login authentication method */ #include "config.h" #include <stdio.h> #include "imap_private.h" #include "mutt/mutt.h" #include "conn/conn.h" #include "mutt.h" #include "auth.h" #include "globals.h" #include "mutt_account.h" #include "mutt_logging.h" #include "mutt_socket.h" #include "options.h" #include "protos.h" /** * imap_auth_login - Plain LOGIN support * @param idata Server data * @param method Name of this authentication method * @retval enum Result, e.g. #IMAP_AUTH_SUCCESS */ enum ImapAuthRes imap_auth_login(struct ImapData *idata, const char *method) { char q_user[SHORT_STRING], q_pass[SHORT_STRING]; char buf[STRING]; int rc; if (mutt_bit_isset(idata->capabilities, LOGINDISABLED)) { mutt_message(_("LOGIN disabled on this server.")); return IMAP_AUTH_UNAVAIL; } if (mutt_account_getuser(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; if (mutt_account_getpass(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; mutt_message(_("Logging in...")); imap_quote_string(q_user, sizeof(q_user), idata->conn->account.user, false); imap_quote_string(q_pass, sizeof(q_pass), idata->conn->account.pass, false); /* don't print the password unless we're at the ungodly debugging level * of 5 or higher */ if (DebugLevel < IMAP_LOG_PASS) mutt_debug(2, "Sending LOGIN command for %s...\n", idata->conn->account.user); snprintf(buf, sizeof(buf), "LOGIN %s %s", q_user, q_pass); rc = imap_exec(idata, buf, IMAP_CMD_FAIL_OK | IMAP_CMD_PASS); if (!rc) { mutt_clear_error(); /* clear "Logging in...". fixes #3524 */ return IMAP_AUTH_SUCCESS; } mutt_error(_("Login failed.")); return IMAP_AUTH_FAILURE; }
./CrossVul/dataset_final_sorted/CWE-77/c/good_251_0
crossvul-cpp_data_bad_2351_3
/* * blkid.c - User command-line interface for libblkid * * Copyright (C) 2001 Andreas Dilger * * %Begin-Header% * This file may be redistributed under the terms of the * GNU Lesser General Public License. * %End-Header% */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #ifdef HAVE_GETOPT_H #include <getopt.h> #else extern int getopt(int argc, char * const argv[], const char *optstring); extern char *optarg; extern int optind; #endif #define OUTPUT_VALUE_ONLY (1 << 1) #define OUTPUT_DEVICE_ONLY (1 << 2) #define OUTPUT_PRETTY_LIST (1 << 3) /* deprecated */ #define OUTPUT_UDEV_LIST (1 << 4) /* deprecated */ #define OUTPUT_EXPORT_LIST (1 << 5) #define LOWPROBE_TOPOLOGY (1 << 1) #define LOWPROBE_SUPERBLOCKS (1 << 2) #define BLKID_EXIT_NOTFOUND 2 /* token or device not found */ #define BLKID_EXIT_OTHER 4 /* bad usage or other error */ #define BLKID_EXIT_AMBIVAL 8 /* ambivalent low-level probing detected */ #include <blkid.h> #include "ismounted.h" #define STRTOXX_EXIT_CODE BLKID_EXIT_OTHER /* strtoxx_or_err() */ #include "strutils.h" #define OPTUTILS_EXIT_CODE BLKID_EXIT_OTHER /* exclusive_option() */ #include "optutils.h" #include "closestream.h" #include "ttyutils.h" #include "xalloc.h" int raw_chars; static void print_version(FILE *out) { fprintf(out, "%s from %s (libblkid %s, %s)\n", program_invocation_short_name, PACKAGE_STRING, LIBBLKID_VERSION, LIBBLKID_DATE); } static void usage(int error) { FILE *out = error ? stderr : stdout; print_version(out); fprintf(out, "Usage:\n" " %1$s -L <label> | -U <uuid>\n\n" " %1$s [-c <file>] [-ghlLv] [-o <format>] [-s <tag>] \n" " [-t <token>] [<dev> ...]\n\n" " %1$s -p [-s <tag>] [-O <offset>] [-S <size>] \n" " [-o <format>] <dev> ...\n\n" " %1$s -i [-s <tag>] [-o <format>] <dev> ...\n\n" "Options:\n" " -c <file> read from <file> instead of reading from the default\n" " cache file (-c /dev/null means no cache)\n" " -d don't encode non-printing characters\n" " -h print this usage message and exit\n" " -g garbage collect the blkid cache\n" " -o <format> output format; can be one of:\n" " value, device, export or full; (default: full)\n" " -k list all known filesystems/RAIDs and exit\n" " -s <tag> show specified tag(s) (default show all tags)\n" " -t <token> find device with a specific token (NAME=value pair)\n" " -l look up only first device with token specified by -t\n" " -L <label> convert LABEL to device name\n" " -U <uuid> convert UUID to device name\n" " -V print version and exit\n" " <dev> specify device(s) to probe (default: all devices)\n\n" "Low-level probing options:\n" " -p low-level superblocks probing (bypass cache)\n" " -i gather information about I/O limits\n" " -S <size> overwrite device size\n" " -O <offset> probe at the given offset\n" " -u <list> filter by \"usage\" (e.g. -u filesystem,raid)\n" " -n <list> filter by filesystem type (e.g. -n vfat,ext3)\n" "\n", program_invocation_short_name); exit(error); } /* * This function does "safe" printing. It will convert non-printable * ASCII characters using '^' and M- notation. * * If 'esc' is defined then escape all chars from esc by \. */ static void safe_print(const char *cp, int len, const char *esc) { unsigned char ch; if (len < 0) len = strlen(cp); while (len--) { ch = *cp++; if (!raw_chars) { if (ch >= 128) { fputs("M-", stdout); ch -= 128; } if ((ch < 32) || (ch == 0x7f)) { fputc('^', stdout); ch ^= 0x40; /* ^@, ^A, ^B; ^? for DEL */ } else if (esc && strchr(esc, ch)) fputc('\\', stdout); } fputc(ch, stdout); } } static int pretty_print_word(const char *str, int max_len, int left_len, int overflow_nl) { int len = strlen(str) + left_len; int ret = 0; fputs(str, stdout); if (overflow_nl && len > max_len) { fputc('\n', stdout); len = 0; } else if (len > max_len) ret = len - max_len; do fputc(' ', stdout); while (len++ < max_len); return ret; } static void pretty_print_line(const char *device, const char *fs_type, const char *label, const char *mtpt, const char *uuid) { static int device_len = 10, fs_type_len = 7; static int label_len = 8, mtpt_len = 14; static int term_width = -1; int len, w; if (term_width < 0) { term_width = get_terminal_width(); if (term_width <= 0) term_width = 80; } if (term_width > 80) { term_width -= 80; w = term_width / 10; if (w > 8) w = 8; term_width -= 2*w; label_len += w; fs_type_len += w; w = term_width/2; device_len += w; mtpt_len +=w; } len = pretty_print_word(device, device_len, 0, 1); len = pretty_print_word(fs_type, fs_type_len, len, 0); len = pretty_print_word(label, label_len, len, 0); pretty_print_word(mtpt, mtpt_len, len, 0); fputs(uuid, stdout); fputc('\n', stdout); } static void pretty_print_dev(blkid_dev dev) { blkid_tag_iterate iter; const char *type, *value, *devname; const char *uuid = "", *fs_type = "", *label = ""; int len, mount_flags; char mtpt[80]; int retval; if (dev == NULL) { pretty_print_line("device", "fs_type", "label", "mount point", "UUID"); for (len=get_terminal_width()-1; len > 0; len--) fputc('-', stdout); fputc('\n', stdout); return; } devname = blkid_dev_devname(dev); if (access(devname, F_OK)) return; /* Get the uuid, label, type */ iter = blkid_tag_iterate_begin(dev); while (blkid_tag_next(iter, &type, &value) == 0) { if (!strcmp(type, "UUID")) uuid = value; if (!strcmp(type, "TYPE")) fs_type = value; if (!strcmp(type, "LABEL")) label = value; } blkid_tag_iterate_end(iter); /* Get the mount point */ mtpt[0] = 0; retval = check_mount_point(devname, &mount_flags, mtpt, sizeof(mtpt)); if (retval == 0) { if (mount_flags & MF_MOUNTED) { if (!mtpt[0]) strcpy(mtpt, "(mounted, mtpt unknown)"); } else if (mount_flags & MF_BUSY) strcpy(mtpt, "(in use)"); else strcpy(mtpt, "(not mounted)"); } pretty_print_line(devname, fs_type, label, mtpt, uuid); } static void print_udev_format(const char *name, const char *value) { char enc[265], safe[256]; size_t namelen = strlen(name); *safe = *enc = '\0'; if (!strcmp(name, "TYPE") || !strcmp(name, "VERSION")) { blkid_encode_string(value, enc, sizeof(enc)); printf("ID_FS_%s=%s\n", name, enc); } else if (!strcmp(name, "UUID") || !strcmp(name, "LABEL") || !strcmp(name, "UUID_SUB")) { blkid_safe_string(value, safe, sizeof(safe)); printf("ID_FS_%s=%s\n", name, safe); blkid_encode_string(value, enc, sizeof(enc)); printf("ID_FS_%s_ENC=%s\n", name, enc); } else if (!strcmp(name, "PTUUID")) { printf("ID_PART_TABLE_UUID=%s\n", value); } else if (!strcmp(name, "PTTYPE")) { printf("ID_PART_TABLE_TYPE=%s\n", value); } else if (!strcmp(name, "PART_ENTRY_NAME") || !strcmp(name, "PART_ENTRY_TYPE")) { blkid_encode_string(value, enc, sizeof(enc)); printf("ID_%s=%s\n", name, enc); } else if (!strncmp(name, "PART_ENTRY_", 11)) printf("ID_%s=%s\n", name, value); else if (namelen >= 15 && ( !strcmp(name + (namelen - 12), "_SECTOR_SIZE") || !strcmp(name + (namelen - 8), "_IO_SIZE") || !strcmp(name, "ALIGNMENT_OFFSET"))) printf("ID_IOLIMIT_%s=%s\n", name, value); else printf("ID_FS_%s=%s\n", name, value); } static int has_item(char *ary[], const char *item) { char **p; for (p = ary; *p != NULL; p++) if (!strcmp(item, *p)) return 1; return 0; } static void print_value(int output, int num, const char *devname, const char *value, const char *name, size_t valsz) { if (output & OUTPUT_VALUE_ONLY) { fputs(value, stdout); fputc('\n', stdout); } else if (output & OUTPUT_UDEV_LIST) { print_udev_format(name, value); } else if (output & OUTPUT_EXPORT_LIST) { if (num == 1 && devname) printf("DEVNAME=%s\n", devname); fputs(name, stdout); fputs("=", stdout); safe_print(value, valsz, NULL); fputs("\n", stdout); } else { if (num == 1 && devname) printf("%s:", devname); fputs(" ", stdout); fputs(name, stdout); fputs("=\"", stdout); safe_print(value, valsz, "\""); fputs("\"", stdout); } } static void print_tags(blkid_dev dev, char *show[], int output) { blkid_tag_iterate iter; const char *type, *value, *devname; int num = 1; static int first = 1; if (!dev) return; if (output & OUTPUT_PRETTY_LIST) { pretty_print_dev(dev); return; } devname = blkid_dev_devname(dev); if (output & OUTPUT_DEVICE_ONLY) { printf("%s\n", devname); return; } iter = blkid_tag_iterate_begin(dev); while (blkid_tag_next(iter, &type, &value) == 0) { if (show[0] && !has_item(show, type)) continue; if (num == 1 && !first && (output & (OUTPUT_UDEV_LIST | OUTPUT_EXPORT_LIST))) /* add extra line between output from more devices */ fputc('\n', stdout); print_value(output, num++, devname, value, type, strlen(value)); } blkid_tag_iterate_end(iter); if (num > 1) { if (!(output & (OUTPUT_VALUE_ONLY | OUTPUT_UDEV_LIST | OUTPUT_EXPORT_LIST))) printf("\n"); first = 0; } } static int append_str(char **res, size_t *sz, const char *a, const char *b) { char *str = *res; size_t asz = a ? strlen(a) : 0; size_t bsz = b ? strlen(b) : 0; size_t len = *sz + asz + bsz; if (!len) return -1; *res = str = xrealloc(str, len + 1); str += *sz; if (a) { memcpy(str, a, asz); str += asz; } if (b) { memcpy(str, b, bsz); str += bsz; } *str = '\0'; *sz = len; return 0; } /* * Compose and print ID_FS_AMBIVALENT for udev */ static int print_udev_ambivalent(blkid_probe pr) { char *val = NULL; size_t valsz = 0; int count = 0, rc = -1; while (!blkid_do_probe(pr)) { const char *usage_txt = NULL, *type = NULL, *version = NULL; char enc[256]; blkid_probe_lookup_value(pr, "USAGE", &usage_txt, NULL); blkid_probe_lookup_value(pr, "TYPE", &type, NULL); blkid_probe_lookup_value(pr, "VERSION", &version, NULL); if (!usage_txt || !type) continue; blkid_encode_string(usage_txt, enc, sizeof(enc)); if (append_str(&val, &valsz, enc, ":")) goto done; blkid_encode_string(type, enc, sizeof(enc)); if (append_str(&val, &valsz, enc, version ? ":" : " ")) goto done; if (version) { blkid_encode_string(version, enc, sizeof(enc)); if (append_str(&val, &valsz, enc, " ")) goto done; } count++; } if (count > 1) { *(val + valsz - 1) = '\0'; /* rem tailing whitespace */ printf("ID_FS_AMBIVALENT=%s\n", val); rc = 0; } done: free(val); return rc; } static int lowprobe_superblocks(blkid_probe pr) { struct stat st; int rc, fd = blkid_probe_get_fd(pr); if (fd < 0 || fstat(fd, &st)) return -1; blkid_probe_enable_partitions(pr, 1); if (!S_ISCHR(st.st_mode) && blkid_probe_get_size(pr) <= 1024 * 1440 && blkid_probe_is_wholedisk(pr)) { /* * check if the small disk is partitioned, if yes then * don't probe for filesystems. */ blkid_probe_enable_superblocks(pr, 0); rc = blkid_do_fullprobe(pr); if (rc < 0) return rc; /* -1 = error, 1 = nothing, 0 = succes */ if (blkid_probe_lookup_value(pr, "PTTYPE", NULL, NULL) == 0) return 0; /* partition table detected */ } blkid_probe_set_partitions_flags(pr, BLKID_PARTS_ENTRY_DETAILS); blkid_probe_enable_superblocks(pr, 1); return blkid_do_safeprobe(pr); } static int lowprobe_topology(blkid_probe pr) { /* enable topology probing only */ blkid_probe_enable_topology(pr, 1); blkid_probe_enable_superblocks(pr, 0); blkid_probe_enable_partitions(pr, 0); return blkid_do_fullprobe(pr); } static int lowprobe_device(blkid_probe pr, const char *devname, int chain, char *show[], int output, blkid_loff_t offset, blkid_loff_t size) { const char *data; const char *name; int nvals = 0, n, num = 1; size_t len; int fd; int rc = 0; static int first = 1; fd = open(devname, O_RDONLY|O_CLOEXEC); if (fd < 0) { fprintf(stderr, "error: %s: %m\n", devname); return BLKID_EXIT_NOTFOUND; } if (blkid_probe_set_device(pr, fd, offset, size)) goto done; if (chain & LOWPROBE_TOPOLOGY) rc = lowprobe_topology(pr); if (rc >= 0 && (chain & LOWPROBE_SUPERBLOCKS)) rc = lowprobe_superblocks(pr); if (rc < 0) goto done; if (!rc) nvals = blkid_probe_numof_values(pr); if (nvals && !(chain & LOWPROBE_TOPOLOGY) && !(output & OUTPUT_UDEV_LIST) && !blkid_probe_has_value(pr, "TYPE") && !blkid_probe_has_value(pr, "PTTYPE")) /* * Ignore probing result if there is not any filesystem or * partition table on the device and udev output is not * requested. * * The udev db stores information about partitions, so * PART_ENTRY_* values are alway important. */ nvals = 0; if (nvals && !first && output & (OUTPUT_UDEV_LIST | OUTPUT_EXPORT_LIST)) /* add extra line between output from devices */ fputc('\n', stdout); if (nvals && (output & OUTPUT_DEVICE_ONLY)) { printf("%s\n", devname); goto done; } for (n = 0; n < nvals; n++) { if (blkid_probe_get_value(pr, n, &name, &data, &len)) continue; if (show[0] && !has_item(show, name)) continue; len = strnlen((char *) data, len); print_value(output, num++, devname, (char *) data, name, len); } if (first) first = 0; if (nvals >= 1 && !(output & (OUTPUT_VALUE_ONLY | OUTPUT_UDEV_LIST | OUTPUT_EXPORT_LIST))) printf("\n"); done: if (rc == -2) { if (output & OUTPUT_UDEV_LIST) print_udev_ambivalent(pr); else fprintf(stderr, "%s: ambivalent result (probably more " "filesystems on the device, use wipefs(8) " "to see more details)\n", devname); } close(fd); if (rc == -2) return BLKID_EXIT_AMBIVAL; /* ambivalent probing result */ if (!nvals) return BLKID_EXIT_NOTFOUND; /* nothing detected */ return 0; /* success */ } /* converts comma separated list to BLKID_USAGE_* mask */ static int list_to_usage(const char *list, int *flag) { int mask = 0; const char *word = NULL, *p = list; if (p && strncmp(p, "no", 2) == 0) { *flag = BLKID_FLTR_NOTIN; p += 2; } if (!p || !*p) goto err; while(p) { word = p; p = strchr(p, ','); if (p) p++; if (!strncmp(word, "filesystem", 10)) mask |= BLKID_USAGE_FILESYSTEM; else if (!strncmp(word, "raid", 4)) mask |= BLKID_USAGE_RAID; else if (!strncmp(word, "crypto", 6)) mask |= BLKID_USAGE_CRYPTO; else if (!strncmp(word, "other", 5)) mask |= BLKID_USAGE_OTHER; else goto err; } return mask; err: *flag = 0; fprintf(stderr, "unknown keyword in -u <list> argument: '%s'\n", word ? word : list); exit(BLKID_EXIT_OTHER); } /* converts comma separated list to types[] */ static char **list_to_types(const char *list, int *flag) { int i; const char *p = list; char **res = NULL; if (p && strncmp(p, "no", 2) == 0) { *flag = BLKID_FLTR_NOTIN; p += 2; } if (!p || !*p) { fprintf(stderr, "error: -u <list> argument is empty\n"); goto err; } for (i = 1; p && (p = strchr(p, ',')); i++, p++); res = xcalloc(i + 1, sizeof(char *)); p = *flag & BLKID_FLTR_NOTIN ? list + 2 : list; i = 0; while(p) { const char *word = p; p = strchr(p, ','); res[i++] = p ? xstrndup(word, p - word) : xstrdup(word); if (p) p++; } res[i] = NULL; return res; err: *flag = 0; free(res); exit(BLKID_EXIT_OTHER); } static void free_types_list(char *list[]) { char **n; if (!list) return; for (n = list; *n; n++) free(*n); free(list); } int main(int argc, char **argv) { blkid_cache cache = NULL; char **devices = NULL; char *show[128] = { NULL, }; char *search_type = NULL, *search_value = NULL; char *read = NULL; int fltr_usage = 0; char **fltr_type = NULL; int fltr_flag = BLKID_FLTR_ONLYIN; unsigned int numdev = 0, numtag = 0; int version = 0; int err = BLKID_EXIT_OTHER; unsigned int i; int output_format = 0; int lookup = 0, gc = 0, lowprobe = 0, eval = 0; int c; uintmax_t offset = 0, size = 0; static const ul_excl_t excl[] = { /* rows and cols in in ASCII order */ { 'n','u' }, { 0 } }; int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT; show[0] = NULL; atexit(close_stdout); while ((c = getopt (argc, argv, "c:df:ghilL:n:ko:O:ps:S:t:u:U:w:Vv")) != EOF) { err_exclusive_options(c, NULL, excl, excl_st); switch (c) { case 'c': if (optarg && !*optarg) read = NULL; else read = optarg; break; case 'd': raw_chars = 1; break; case 'L': eval++; search_value = xstrdup(optarg); search_type = xstrdup("LABEL"); break; case 'n': fltr_type = list_to_types(optarg, &fltr_flag); break; case 'u': fltr_usage = list_to_usage(optarg, &fltr_flag); break; case 'U': eval++; search_value = xstrdup(optarg); search_type = xstrdup("UUID"); break; case 'i': lowprobe |= LOWPROBE_TOPOLOGY; break; case 'l': lookup++; break; case 'g': gc = 1; break; case 'k': { size_t idx = 0; const char *name = NULL; while (blkid_superblocks_get_name(idx++, &name, NULL) == 0) printf("%s\n", name); exit(EXIT_SUCCESS); } case 'o': if (!strcmp(optarg, "value")) output_format = OUTPUT_VALUE_ONLY; else if (!strcmp(optarg, "device")) output_format = OUTPUT_DEVICE_ONLY; else if (!strcmp(optarg, "list")) output_format = OUTPUT_PRETTY_LIST; /* deprecated */ else if (!strcmp(optarg, "udev")) output_format = OUTPUT_UDEV_LIST; else if (!strcmp(optarg, "export")) output_format = OUTPUT_EXPORT_LIST; else if (!strcmp(optarg, "full")) output_format = 0; else { fprintf(stderr, "Invalid output format %s. " "Choose from value,\n\t" "device, list, udev or full\n", optarg); exit(BLKID_EXIT_OTHER); } break; case 'O': offset = strtosize_or_err(optarg, "invalid offset argument"); break; case 'p': lowprobe |= LOWPROBE_SUPERBLOCKS; break; case 's': if (numtag + 1 >= sizeof(show) / sizeof(*show)) { fprintf(stderr, "Too many tags specified\n"); usage(err); } show[numtag++] = optarg; show[numtag] = NULL; break; case 'S': size = strtosize_or_err(optarg, "invalid size argument"); break; case 't': if (search_type) { fprintf(stderr, "Can only search for " "one NAME=value pair\n"); usage(err); } if (blkid_parse_tag_string(optarg, &search_type, &search_value)) { fprintf(stderr, "-t needs NAME=value pair\n"); usage(err); } break; case 'V': case 'v': version = 1; break; case 'w': /* ignore - backward compatibility */ break; case 'h': err = 0; /* fallthrough */ default: usage(err); } } /* The rest of the args are device names */ if (optind < argc) { devices = xcalloc(argc - optind, sizeof(char *)); while (optind < argc) devices[numdev++] = argv[optind++]; } if (version) { print_version(stdout); goto exit; } /* convert LABEL/UUID lookup to evaluate request */ if (lookup && output_format == OUTPUT_DEVICE_ONLY && search_type && (!strcmp(search_type, "LABEL") || !strcmp(search_type, "UUID"))) { eval++; lookup = 0; } if (!lowprobe && !eval && blkid_get_cache(&cache, read) < 0) goto exit; if (gc) { blkid_gc_cache(cache); err = 0; goto exit; } err = BLKID_EXIT_NOTFOUND; if (eval == 0 && (output_format & OUTPUT_PRETTY_LIST)) { if (lowprobe) { fprintf(stderr, "The low-level probing mode does not " "support 'list' output format\n"); exit(BLKID_EXIT_OTHER); } pretty_print_dev(NULL); } if (lowprobe) { /* * Low-level API */ blkid_probe pr; if (!numdev) { fprintf(stderr, "The low-level probing mode " "requires a device\n"); exit(BLKID_EXIT_OTHER); } /* automatically enable 'export' format for I/O Limits */ if (!output_format && (lowprobe & LOWPROBE_TOPOLOGY)) output_format = OUTPUT_EXPORT_LIST; pr = blkid_new_probe(); if (!pr) goto exit; if (lowprobe & LOWPROBE_SUPERBLOCKS) { blkid_probe_set_superblocks_flags(pr, BLKID_SUBLKS_LABEL | BLKID_SUBLKS_UUID | BLKID_SUBLKS_TYPE | BLKID_SUBLKS_SECTYPE | BLKID_SUBLKS_USAGE | BLKID_SUBLKS_VERSION); if (fltr_usage && blkid_probe_filter_superblocks_usage( pr, fltr_flag, fltr_usage)) goto exit; else if (fltr_type && blkid_probe_filter_superblocks_type( pr, fltr_flag, fltr_type)) goto exit; } for (i = 0; i < numdev; i++) { err = lowprobe_device(pr, devices[i], lowprobe, show, output_format, (blkid_loff_t) offset, (blkid_loff_t) size); if (err) break; } blkid_free_probe(pr); } else if (eval) { /* * Evaluate API */ char *res = blkid_evaluate_tag(search_type, search_value, NULL); if (res) { err = 0; printf("%s\n", res); } } else if (lookup) { /* * Classic (cache based) API */ blkid_dev dev; if (!search_type) { fprintf(stderr, "The lookup option requires a " "search type specified using -t\n"); exit(BLKID_EXIT_OTHER); } /* Load any additional devices not in the cache */ for (i = 0; i < numdev; i++) blkid_get_dev(cache, devices[i], BLKID_DEV_NORMAL); if ((dev = blkid_find_dev_with_tag(cache, search_type, search_value))) { print_tags(dev, show, output_format); err = 0; } /* If we didn't specify a single device, show all available devices */ } else if (!numdev) { blkid_dev_iterate iter; blkid_dev dev; blkid_probe_all(cache); iter = blkid_dev_iterate_begin(cache); blkid_dev_set_search(iter, search_type, search_value); while (blkid_dev_next(iter, &dev) == 0) { dev = blkid_verify(cache, dev); if (!dev) continue; print_tags(dev, show, output_format); err = 0; } blkid_dev_iterate_end(iter); /* Add all specified devices to cache (optionally display tags) */ } else for (i = 0; i < numdev; i++) { blkid_dev dev = blkid_get_dev(cache, devices[i], BLKID_DEV_NORMAL); if (dev) { if (search_type && !blkid_dev_has_tag(dev, search_type, search_value)) continue; print_tags(dev, show, output_format); err = 0; } } exit: free(search_type); free(search_value); free_types_list(fltr_type); if (!lowprobe && !eval) blkid_put_cache(cache); free(devices); return err; }
./CrossVul/dataset_final_sorted/CWE-77/c/bad_2351_3
crossvul-cpp_data_bad_251_4
/** * @file * IMAP helper functions * * @authors * Copyright (C) 1996-1998,2010,2012-2013 Michael R. Elkins <me@mutt.org> * Copyright (C) 1996-1999 Brandon Long <blong@fiction.net> * Copyright (C) 1999-2009,2012 Brendan Cully <brendan@kublai.com> * * @copyright * 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, see <http://www.gnu.org/licenses/>. */ /** * @page imap_util IMAP helper functions * * IMAP helper functions */ #include "config.h" #include <ctype.h> #include <errno.h> #include <netdb.h> #include <netinet/in.h> #include <signal.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include "imap_private.h" #include "mutt/mutt.h" #include "conn/conn.h" #include "bcache.h" #include "context.h" #include "globals.h" #include "header.h" #include "imap/imap.h" #include "mailbox.h" #include "message.h" #include "mutt_account.h" #include "mutt_socket.h" #include "mx.h" #include "options.h" #include "protos.h" #include "url.h" #ifdef USE_HCACHE #include "hcache/hcache.h" #endif /** * imap_expand_path - Canonicalise an IMAP path * @param path Buffer containing path * @param len Buffer length * @retval 0 Success * @retval -1 Error * * IMAP implementation of mutt_expand_path. Rewrite an IMAP path in canonical * and absolute form. The buffer is rewritten in place with the canonical IMAP * path. * * Function can fail if imap_parse_path() or url_tostring() fail, * of if the buffer isn't large enough. */ int imap_expand_path(char *path, size_t len) { struct ImapMbox mx; struct ImapData *idata = NULL; struct Url url; char fixedpath[LONG_STRING]; int rc; if (imap_parse_path(path, &mx) < 0) return -1; idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW); mutt_account_tourl(&mx.account, &url); imap_fix_path(idata, mx.mbox, fixedpath, sizeof(fixedpath)); url.path = fixedpath; rc = url_tostring(&url, path, len, U_DECODE_PASSWD); FREE(&mx.mbox); return rc; } /** * imap_get_parent - Get an IMAP folder's parent * @param output Buffer for the result * @param mbox Mailbox whose parent is to be determined * @param olen Length of the buffer * @param delim Path delimiter */ void imap_get_parent(char *output, const char *mbox, size_t olen, char delim) { int n; /* Make a copy of the mailbox name, but only if the pointers are different */ if (mbox != output) mutt_str_strfcpy(output, mbox, olen); n = mutt_str_strlen(output); /* Let's go backwards until the next delimiter * * If output[n] is a '/', the first n-- will allow us * to ignore it. If it isn't, then output looks like * "/aaaaa/bbbb". There is at least one "b", so we can't skip * the "/" after the 'a's. * * If output == '/', then n-- => n == 0, so the loop ends * immediately */ for (n--; n >= 0 && output[n] != delim; n--) ; /* We stopped before the beginning. There is a trailing * slash. */ if (n > 0) { /* Strip the trailing delimiter. */ output[n] = '\0'; } else { output[0] = (n == 0) ? delim : '\0'; } } /** * imap_get_parent_path - Get the path of the parent folder * @param output Buffer for the result * @param path Mailbox whose parent is to be determined * @param olen Length of the buffer * * Provided an imap path, returns in output the parent directory if * existent. Else returns the same path. */ void imap_get_parent_path(char *output, const char *path, size_t olen) { struct ImapMbox mx; struct ImapData *idata = NULL; char mbox[LONG_STRING] = ""; if (imap_parse_path(path, &mx) < 0) { mutt_str_strfcpy(output, path, olen); return; } idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW); if (!idata) { mutt_str_strfcpy(output, path, olen); return; } /* Stores a fixed path in mbox */ imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox)); /* Gets the parent mbox in mbox */ imap_get_parent(mbox, mbox, sizeof(mbox), idata->delim); /* Returns a fully qualified IMAP url */ imap_qualify_path(output, olen, &mx, mbox); FREE(&mx.mbox); } /** * imap_clean_path - Cleans an IMAP path using imap_fix_path * @param path Path to be cleaned * @param plen Length of the buffer * * Does it in place. */ void imap_clean_path(char *path, size_t plen) { struct ImapMbox mx; struct ImapData *idata = NULL; char mbox[LONG_STRING] = ""; if (imap_parse_path(path, &mx) < 0) return; idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW); if (!idata) return; /* Stores a fixed path in mbox */ imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox)); /* Returns a fully qualified IMAP url */ imap_qualify_path(path, plen, &mx, mbox); } #ifdef USE_HCACHE /** * imap_hcache_namer - Generate a filename for the header cache * @param path Path for the header cache file * @param dest Buffer for result * @param dlen Length of buffer * @retval num Chars written to dest */ static int imap_hcache_namer(const char *path, char *dest, size_t dlen) { return snprintf(dest, dlen, "%s.hcache", path); } /** * imap_hcache_open - Open a header cache * @param idata Server data * @param path Path to the header cache * @retval ptr HeaderCache * @retval NULL Failure */ header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path) { struct ImapMbox mx; struct Url url; char cachepath[PATH_MAX]; char mbox[PATH_MAX]; if (path) imap_cachepath(idata, path, mbox, sizeof(mbox)); else { if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0) return NULL; imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox)); FREE(&mx.mbox); } mutt_account_tourl(&idata->conn->account, &url); url.path = mbox; url_tostring(&url, cachepath, sizeof(cachepath), U_PATH); return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer); } /** * imap_hcache_close - Close the header cache * @param idata Server data */ void imap_hcache_close(struct ImapData *idata) { if (!idata->hcache) return; mutt_hcache_close(idata->hcache); idata->hcache = NULL; } /** * imap_hcache_get - Get a header cache entry by its UID * @param idata Server data * @param uid UID to find * @retval ptr Email Header * @retval NULL Failure */ struct Header *imap_hcache_get(struct ImapData *idata, unsigned int uid) { char key[16]; void *uv = NULL; struct Header *h = NULL; if (!idata->hcache) return NULL; sprintf(key, "/%u", uid); uv = mutt_hcache_fetch(idata->hcache, key, imap_hcache_keylen(key)); if (uv) { if (*(unsigned int *) uv == idata->uid_validity) h = mutt_hcache_restore(uv); else mutt_debug(3, "hcache uidvalidity mismatch: %u\n", *(unsigned int *) uv); mutt_hcache_free(idata->hcache, &uv); } return h; } /** * imap_hcache_put - Add an entry to the header cache * @param idata Server data * @param h Email Header * @retval 0 Success * @retval -1 Failure */ int imap_hcache_put(struct ImapData *idata, struct Header *h) { char key[16]; if (!idata->hcache) return -1; sprintf(key, "/%u", HEADER_DATA(h)->uid); return mutt_hcache_store(idata->hcache, key, imap_hcache_keylen(key), h, idata->uid_validity); } /** * imap_hcache_del - Delete an item from the header cache * @param idata Server data * @param uid UID of entry to delete * @retval 0 Success * @retval -1 Failure */ int imap_hcache_del(struct ImapData *idata, unsigned int uid) { char key[16]; if (!idata->hcache) return -1; sprintf(key, "/%u", uid); return mutt_hcache_delete(idata->hcache, key, imap_hcache_keylen(key)); } #endif /** * imap_parse_path - Parse an IMAP mailbox name into name,host,port * @param path Mailbox path to parse * @param mx An IMAP mailbox * @retval 0 Success * @retval -1 Failure * * Given an IMAP mailbox name, return host, port and a path IMAP servers will * recognize. mx.mbox is malloc'd, caller must free it */ int imap_parse_path(const char *path, struct ImapMbox *mx) { static unsigned short ImapPort = 0; static unsigned short ImapsPort = 0; struct servent *service = NULL; struct Url url; char *c = NULL; if (!ImapPort) { service = getservbyname("imap", "tcp"); if (service) ImapPort = ntohs(service->s_port); else ImapPort = IMAP_PORT; mutt_debug(3, "Using default IMAP port %d\n", ImapPort); } if (!ImapsPort) { service = getservbyname("imaps", "tcp"); if (service) ImapsPort = ntohs(service->s_port); else ImapsPort = IMAP_SSL_PORT; mutt_debug(3, "Using default IMAPS port %d\n", ImapsPort); } /* Defaults */ memset(&mx->account, 0, sizeof(mx->account)); mx->account.port = ImapPort; mx->account.type = MUTT_ACCT_TYPE_IMAP; c = mutt_str_strdup(path); url_parse(&url, c); if (url.scheme == U_IMAP || url.scheme == U_IMAPS) { if (mutt_account_fromurl(&mx->account, &url) < 0 || !*mx->account.host) { url_free(&url); FREE(&c); return -1; } mx->mbox = mutt_str_strdup(url.path); if (url.scheme == U_IMAPS) mx->account.flags |= MUTT_ACCT_SSL; url_free(&url); FREE(&c); } /* old PINE-compatibility code */ else { url_free(&url); FREE(&c); char tmp[128]; if (sscanf(path, "{%127[^}]}", tmp) != 1) return -1; c = strchr(path, '}'); if (!c) return -1; else { /* walk past closing '}' */ mx->mbox = mutt_str_strdup(c + 1); } c = strrchr(tmp, '@'); if (c) { *c = '\0'; mutt_str_strfcpy(mx->account.user, tmp, sizeof(mx->account.user)); mutt_str_strfcpy(tmp, c + 1, sizeof(tmp)); mx->account.flags |= MUTT_ACCT_USER; } const int n = sscanf(tmp, "%127[^:/]%127s", mx->account.host, tmp); if (n < 1) { mutt_debug(1, "NULL host in %s\n", path); FREE(&mx->mbox); return -1; } if (n > 1) { if (sscanf(tmp, ":%hu%127s", &(mx->account.port), tmp) >= 1) mx->account.flags |= MUTT_ACCT_PORT; if (sscanf(tmp, "/%s", tmp) == 1) { if (mutt_str_strncmp(tmp, "ssl", 3) == 0) mx->account.flags |= MUTT_ACCT_SSL; else { mutt_debug(1, "Unknown connection type in %s\n", path); FREE(&mx->mbox); return -1; } } } } if ((mx->account.flags & MUTT_ACCT_SSL) && !(mx->account.flags & MUTT_ACCT_PORT)) mx->account.port = ImapsPort; return 0; } /** * imap_mxcmp - Compare mailbox names, giving priority to INBOX * @param mx1 First mailbox name * @param mx2 Second mailbox name * @retval <0 First mailbox precedes Second mailbox * @retval 0 Mailboxes are the same * @retval >0 Second mailbox precedes First mailbox * * Like a normal sort function except that "INBOX" will be sorted to the * beginning of the list. */ int imap_mxcmp(const char *mx1, const char *mx2) { char *b1 = NULL; char *b2 = NULL; int rc; if (!mx1 || !*mx1) mx1 = "INBOX"; if (!mx2 || !*mx2) mx2 = "INBOX"; if ((mutt_str_strcasecmp(mx1, "INBOX") == 0) && (mutt_str_strcasecmp(mx2, "INBOX") == 0)) { return 0; } b1 = mutt_mem_malloc(strlen(mx1) + 1); b2 = mutt_mem_malloc(strlen(mx2) + 1); imap_fix_path(NULL, mx1, b1, strlen(mx1) + 1); imap_fix_path(NULL, mx2, b2, strlen(mx2) + 1); rc = mutt_str_strcmp(b1, b2); FREE(&b1); FREE(&b2); return rc; } /** * imap_pretty_mailbox - Prettify an IMAP mailbox name * @param path Mailbox name to be tidied * * Called by mutt_pretty_mailbox() to make IMAP paths look nice. */ void imap_pretty_mailbox(char *path) { struct ImapMbox home, target; struct Url url; char *delim = NULL; int tlen; int hlen = 0; bool home_match = false; if (imap_parse_path(path, &target) < 0) return; tlen = mutt_str_strlen(target.mbox); /* check whether we can do '=' substitution */ if (mx_is_imap(Folder) && !imap_parse_path(Folder, &home)) { hlen = mutt_str_strlen(home.mbox); if (tlen && mutt_account_match(&home.account, &target.account) && (mutt_str_strncmp(home.mbox, target.mbox, hlen) == 0)) { if (hlen == 0) home_match = true; else if (ImapDelimChars) { for (delim = ImapDelimChars; *delim != '\0'; delim++) if (target.mbox[hlen] == *delim) home_match = true; } } FREE(&home.mbox); } /* do the '=' substitution */ if (home_match) { *path++ = '='; /* copy remaining path, skipping delimiter */ if (hlen == 0) hlen = -1; memcpy(path, target.mbox + hlen + 1, tlen - hlen - 1); path[tlen - hlen - 1] = '\0'; } else { mutt_account_tourl(&target.account, &url); url.path = target.mbox; /* FIXME: That hard-coded constant is bogus. But we need the actual * size of the buffer from mutt_pretty_mailbox. And these pretty * operations usually shrink the result. Still... */ url_tostring(&url, path, 1024, 0); } FREE(&target.mbox); } /** * imap_continue - display a message and ask the user if they want to go on * @param msg Location of the error * @param resp Message for user * @retval num Result: #MUTT_YES, #MUTT_NO, #MUTT_ABORT */ int imap_continue(const char *msg, const char *resp) { imap_error(msg, resp); return mutt_yesorno(_("Continue?"), 0); } /** * imap_error - show an error and abort * @param where Location of the error * @param msg Message for user */ void imap_error(const char *where, const char *msg) { mutt_error("%s [%s]\n", where, msg); } /** * imap_new_idata - Allocate and initialise a new ImapData structure * @retval NULL Failure (no mem) * @retval ptr New ImapData */ struct ImapData *imap_new_idata(void) { struct ImapData *idata = mutt_mem_calloc(1, sizeof(struct ImapData)); idata->cmdbuf = mutt_buffer_new(); idata->cmdslots = ImapPipelineDepth + 2; idata->cmds = mutt_mem_calloc(idata->cmdslots, sizeof(*idata->cmds)); STAILQ_INIT(&idata->flags); STAILQ_INIT(&idata->mboxcache); return idata; } /** * imap_free_idata - Release and clear storage in an ImapData structure * @param idata Server data */ void imap_free_idata(struct ImapData **idata) { if (!idata) return; FREE(&(*idata)->capstr); mutt_list_free(&(*idata)->flags); imap_mboxcache_free(*idata); mutt_buffer_free(&(*idata)->cmdbuf); FREE(&(*idata)->buf); mutt_bcache_close(&(*idata)->bcache); FREE(&(*idata)->cmds); FREE(idata); } /** * imap_fix_path - Fix up the imap path * @param idata Server data * @param mailbox Mailbox path * @param path Buffer for the result * @param plen Length of buffer * @retval ptr Fixed-up path * * This is necessary because the rest of neomutt assumes a hierarchy delimiter of * '/', which is not necessarily true in IMAP. Additionally, the filesystem * converts multiple hierarchy delimiters into a single one, ie "///" is equal * to "/". IMAP servers are not required to do this. * Moreover, IMAP servers may dislike the path ending with the delimiter. */ char *imap_fix_path(struct ImapData *idata, const char *mailbox, char *path, size_t plen) { int i = 0; char delim = '\0'; if (idata) delim = idata->delim; while (mailbox && *mailbox && i < plen - 1) { if ((ImapDelimChars && strchr(ImapDelimChars, *mailbox)) || (delim && *mailbox == delim)) { /* use connection delimiter if known. Otherwise use user delimiter */ if (!idata) delim = *mailbox; while (*mailbox && ((ImapDelimChars && strchr(ImapDelimChars, *mailbox)) || (delim && *mailbox == delim))) { mailbox++; } path[i] = delim; } else { path[i] = *mailbox; mailbox++; } i++; } if (i && path[--i] != delim) i++; path[i] = '\0'; return path; } /** * imap_cachepath - Generate a cache path for a mailbox * @param idata Server data * @param mailbox Mailbox name * @param dest Buffer to store cache path * @param dlen Length of buffer */ void imap_cachepath(struct ImapData *idata, const char *mailbox, char *dest, size_t dlen) { char *s = NULL; const char *p = mailbox; for (s = dest; p && *p && dlen; dlen--) { if (*p == idata->delim) { *s = '/'; /* simple way to avoid collisions with UIDs */ if (*(p + 1) >= '0' && *(p + 1) <= '9') { if (--dlen) *++s = '_'; } } else *s = *p; p++; s++; } *s = '\0'; } /** * imap_get_literal_count - write number of bytes in an IMAP literal into bytes * @param[in] buf Number as a string * @param[out] bytes Resulting number * @retval 0 Success * @retval -1 Failure */ int imap_get_literal_count(const char *buf, unsigned int *bytes) { char *pc = NULL; char *pn = NULL; if (!buf || !(pc = strchr(buf, '{'))) return -1; pc++; pn = pc; while (isdigit((unsigned char) *pc)) pc++; *pc = '\0'; if (mutt_str_atoui(pn, bytes) < 0) return -1; return 0; } /** * imap_get_qualifier - Get the qualifier from a tagged response * @param buf Command string to process * @retval ptr Start of the qualifier * * In a tagged response, skip tag and status for the qualifier message. * Used by imap_copy_message for TRYCREATE */ char *imap_get_qualifier(char *buf) { char *s = buf; /* skip tag */ s = imap_next_word(s); /* skip OK/NO/BAD response */ s = imap_next_word(s); return s; } /** * imap_next_word - Find where the next IMAP word begins * @param s Command string to process * @retval ptr Next IMAP word */ char *imap_next_word(char *s) { int quoted = 0; while (*s) { if (*s == '\\') { s++; if (*s) s++; continue; } if (*s == '\"') quoted = quoted ? 0 : 1; if (!quoted && ISSPACE(*s)) break; s++; } SKIPWS(s); return s; } /** * imap_qualify_path - Make an absolute IMAP folder target * @param dest Buffer for the result * @param len Length of buffer * @param mx Imap mailbox * @param path Path relative to the mailbox * * given ImapMbox and relative path. */ void imap_qualify_path(char *dest, size_t len, struct ImapMbox *mx, char *path) { struct Url url; mutt_account_tourl(&mx->account, &url); url.path = path; url_tostring(&url, dest, len, 0); } /** * imap_quote_string - quote string according to IMAP rules * @param dest Buffer for the result * @param dlen Length of the buffer * @param src String to be quoted * * Surround string with quotes, escape " and \ with backslash */ void imap_quote_string(char *dest, size_t dlen, const char *src) { static const char quote[] = "\"\\"; char *pt = dest; const char *s = src; *pt++ = '"'; /* save room for trailing quote-char */ dlen -= 2; for (; *s && dlen; s++) { if (strchr(quote, *s)) { dlen -= 2; if (dlen == 0) break; *pt++ = '\\'; *pt++ = *s; } else { *pt++ = *s; dlen--; } } *pt++ = '"'; *pt = '\0'; } /** * imap_unquote_string - equally stupid unquoting routine * @param s String to be unquoted */ void imap_unquote_string(char *s) { char *d = s; if (*s == '\"') s++; else return; while (*s) { if (*s == '\"') { *d = '\0'; return; } if (*s == '\\') { s++; } if (*s) { *d = *s; d++; s++; } } *d = '\0'; } /** * imap_munge_mbox_name - Quote awkward characters in a mailbox name * @param idata Server data * @param dest Buffer to store safe mailbox name * @param dlen Length of buffer * @param src Mailbox name */ void imap_munge_mbox_name(struct ImapData *idata, char *dest, size_t dlen, const char *src) { char *buf = mutt_str_strdup(src); imap_utf_encode(idata, &buf); imap_quote_string(dest, dlen, buf); FREE(&buf); } /** * imap_unmunge_mbox_name - Remove quoting from a mailbox name * @param idata Server data * @param s Mailbox name * * The string will be altered in-place. */ void imap_unmunge_mbox_name(struct ImapData *idata, char *s) { imap_unquote_string(s); char *buf = mutt_str_strdup(s); if (buf) { imap_utf_decode(idata, &buf); strncpy(s, buf, strlen(s)); } FREE(&buf); } /** * imap_keepalive - poll the current folder to keep the connection alive */ void imap_keepalive(void) { struct Connection *conn = NULL; struct ImapData *idata = NULL; time_t now = time(NULL); TAILQ_FOREACH(conn, mutt_socket_head(), entries) { if (conn->account.type == MUTT_ACCT_TYPE_IMAP) { idata = conn->data; if (idata->state >= IMAP_AUTHENTICATED && now >= idata->lastread + ImapKeepalive) { imap_check(idata, 1); } } } } /** * imap_wait_keepalive - Wait for a process to change state * @param pid Process ID to listen to * @retval num 'wstatus' from waitpid() */ int imap_wait_keepalive(pid_t pid) { struct sigaction oldalrm; struct sigaction act; sigset_t oldmask; int rc; bool imap_passive = ImapPassive; ImapPassive = true; OptKeepQuiet = true; sigprocmask(SIG_SETMASK, NULL, &oldmask); sigemptyset(&act.sa_mask); act.sa_handler = mutt_sig_empty_handler; #ifdef SA_INTERRUPT act.sa_flags = SA_INTERRUPT; #else act.sa_flags = 0; #endif sigaction(SIGALRM, &act, &oldalrm); alarm(ImapKeepalive); while (waitpid(pid, &rc, 0) < 0 && errno == EINTR) { alarm(0); /* cancel a possibly pending alarm */ imap_keepalive(); alarm(ImapKeepalive); } alarm(0); /* cancel a possibly pending alarm */ sigaction(SIGALRM, &oldalrm, NULL); sigprocmask(SIG_SETMASK, &oldmask, NULL); OptKeepQuiet = false; if (!imap_passive) ImapPassive = false; return rc; } /** * imap_allow_reopen - Allow re-opening a folder upon expunge * @param ctx Context */ void imap_allow_reopen(struct Context *ctx) { struct ImapData *idata = NULL; if (!ctx || !ctx->data || ctx->magic != MUTT_IMAP) return; idata = ctx->data; if (idata->ctx == ctx) idata->reopen |= IMAP_REOPEN_ALLOW; } /** * imap_disallow_reopen - Disallow re-opening a folder upon expunge * @param ctx Context */ void imap_disallow_reopen(struct Context *ctx) { struct ImapData *idata = NULL; if (!ctx || !ctx->data || ctx->magic != MUTT_IMAP) return; idata = ctx->data; if (idata->ctx == ctx) idata->reopen &= ~IMAP_REOPEN_ALLOW; } /** * imap_account_match - Compare two Accounts * @param a1 First Account * @param a2 Second Account * @retval true Accounts match */ int imap_account_match(const struct Account *a1, const struct Account *a2) { struct ImapData *a1_idata = imap_conn_find(a1, MUTT_IMAP_CONN_NONEW); struct ImapData *a2_idata = imap_conn_find(a2, MUTT_IMAP_CONN_NONEW); const struct Account *a1_canon = a1_idata == NULL ? a1 : &a1_idata->conn->account; const struct Account *a2_canon = a2_idata == NULL ? a2 : &a2_idata->conn->account; return mutt_account_match(a1_canon, a2_canon); }
./CrossVul/dataset_final_sorted/CWE-77/c/bad_251_4
crossvul-cpp_data_good_838_0
/* HIDP implementation for Linux Bluetooth stack (BlueZ). Copyright (C) 2003-2004 Marcel Holtmann <marcel@holtmann.org> 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/export.h> #include <linux/file.h> #include "hidp.h" static struct bt_sock_list hidp_sk_list = { .lock = __RW_LOCK_UNLOCKED(hidp_sk_list.lock) }; static int hidp_sock_release(struct socket *sock) { struct sock *sk = sock->sk; BT_DBG("sock %p sk %p", sock, sk); if (!sk) return 0; bt_sock_unlink(&hidp_sk_list, sk); sock_orphan(sk); sock_put(sk); return 0; } static int do_hidp_sock_ioctl(struct socket *sock, unsigned int cmd, void __user *argp) { struct hidp_connadd_req ca; struct hidp_conndel_req cd; struct hidp_connlist_req cl; struct hidp_conninfo ci; struct socket *csock; struct socket *isock; int err; BT_DBG("cmd %x arg %p", cmd, argp); switch (cmd) { case HIDPCONNADD: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&ca, argp, sizeof(ca))) return -EFAULT; csock = sockfd_lookup(ca.ctrl_sock, &err); if (!csock) return err; isock = sockfd_lookup(ca.intr_sock, &err); if (!isock) { sockfd_put(csock); return err; } ca.name[sizeof(ca.name)-1] = 0; err = hidp_connection_add(&ca, csock, isock); if (!err && copy_to_user(argp, &ca, sizeof(ca))) err = -EFAULT; sockfd_put(csock); sockfd_put(isock); return err; case HIDPCONNDEL: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&cd, argp, sizeof(cd))) return -EFAULT; return hidp_connection_del(&cd); case HIDPGETCONNLIST: if (copy_from_user(&cl, argp, sizeof(cl))) return -EFAULT; if (cl.cnum <= 0) return -EINVAL; err = hidp_get_connlist(&cl); if (!err && copy_to_user(argp, &cl, sizeof(cl))) return -EFAULT; return err; case HIDPGETCONNINFO: if (copy_from_user(&ci, argp, sizeof(ci))) return -EFAULT; err = hidp_get_conninfo(&ci); if (!err && copy_to_user(argp, &ci, sizeof(ci))) return -EFAULT; return err; } return -EINVAL; } static int hidp_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { return do_hidp_sock_ioctl(sock, cmd, (void __user *)arg); } #ifdef CONFIG_COMPAT struct compat_hidp_connadd_req { int ctrl_sock; /* Connected control socket */ int intr_sock; /* Connected interrupt socket */ __u16 parser; __u16 rd_size; compat_uptr_t rd_data; __u8 country; __u8 subclass; __u16 vendor; __u16 product; __u16 version; __u32 flags; __u32 idle_to; char name[128]; }; static int hidp_sock_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { void __user *argp = compat_ptr(arg); int err; if (cmd == HIDPGETCONNLIST) { struct hidp_connlist_req cl; u32 __user *p = argp; u32 uci; if (get_user(cl.cnum, p) || get_user(uci, p + 1)) return -EFAULT; cl.ci = compat_ptr(uci); if (cl.cnum <= 0) return -EINVAL; err = hidp_get_connlist(&cl); if (!err && put_user(cl.cnum, p)) err = -EFAULT; return err; } else if (cmd == HIDPCONNADD) { struct compat_hidp_connadd_req ca32; struct hidp_connadd_req ca; struct socket *csock; struct socket *isock; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&ca32, (void __user *) arg, sizeof(ca32))) return -EFAULT; ca.ctrl_sock = ca32.ctrl_sock; ca.intr_sock = ca32.intr_sock; ca.parser = ca32.parser; ca.rd_size = ca32.rd_size; ca.rd_data = compat_ptr(ca32.rd_data); ca.country = ca32.country; ca.subclass = ca32.subclass; ca.vendor = ca32.vendor; ca.product = ca32.product; ca.version = ca32.version; ca.flags = ca32.flags; ca.idle_to = ca32.idle_to; memcpy(ca.name, ca32.name, 128); csock = sockfd_lookup(ca.ctrl_sock, &err); if (!csock) return err; isock = sockfd_lookup(ca.intr_sock, &err); if (!isock) { sockfd_put(csock); return err; } err = hidp_connection_add(&ca, csock, isock); if (!err && copy_to_user(argp, &ca32, sizeof(ca32))) err = -EFAULT; sockfd_put(csock); sockfd_put(isock); return err; } return hidp_sock_ioctl(sock, cmd, arg); } #endif static const struct proto_ops hidp_sock_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .release = hidp_sock_release, .ioctl = hidp_sock_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = hidp_sock_compat_ioctl, #endif .bind = sock_no_bind, .getname = sock_no_getname, .sendmsg = sock_no_sendmsg, .recvmsg = sock_no_recvmsg, .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 hidp_proto = { .name = "HIDP", .owner = THIS_MODULE, .obj_size = sizeof(struct bt_sock) }; static int hidp_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, &hidp_proto, kern); if (!sk) return -ENOMEM; sock_init_data(sock, sk); sock->ops = &hidp_sock_ops; sock->state = SS_UNCONNECTED; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = protocol; sk->sk_state = BT_OPEN; bt_sock_link(&hidp_sk_list, sk); return 0; } static const struct net_proto_family hidp_sock_family_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .create = hidp_sock_create }; int __init hidp_init_sockets(void) { int err; err = proto_register(&hidp_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_HIDP, &hidp_sock_family_ops); if (err < 0) { BT_ERR("Can't register HIDP socket"); goto error; } err = bt_procfs_init(&init_net, "hidp", &hidp_sk_list, NULL); if (err < 0) { BT_ERR("Failed to create HIDP proc file"); bt_sock_unregister(BTPROTO_HIDP); goto error; } BT_INFO("HIDP socket layer initialized"); return 0; error: proto_unregister(&hidp_proto); return err; } void __exit hidp_cleanup_sockets(void) { bt_procfs_cleanup(&init_net, "hidp"); bt_sock_unregister(BTPROTO_HIDP); proto_unregister(&hidp_proto); }
./CrossVul/dataset_final_sorted/CWE-77/c/good_838_0
crossvul-cpp_data_bad_248_0
/** * @file * IMAP network mailbox * * @authors * Copyright (C) 1996-1998,2012 Michael R. Elkins <me@mutt.org> * Copyright (C) 1996-1999 Brandon Long <blong@fiction.net> * Copyright (C) 1999-2009,2012,2017 Brendan Cully <brendan@kublai.com> * * @copyright * 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, see <http://www.gnu.org/licenses/>. */ /** * @page imap_imap IMAP network mailbox * * Support for IMAP4rev1, with the occasional nod to IMAP 4. */ #include "config.h" #include <ctype.h> #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include "imap_private.h" #include "mutt/mutt.h" #include "conn/conn.h" #include "mutt.h" #include "imap.h" #include "auth.h" #include "bcache.h" #include "body.h" #include "buffy.h" #include "context.h" #include "envelope.h" #include "globals.h" #include "header.h" #include "mailbox.h" #include "message.h" #include "mutt_account.h" #include "mutt_curses.h" #include "mutt_logging.h" #include "mutt_socket.h" #include "mx.h" #include "options.h" #include "pattern.h" #include "progress.h" #include "protos.h" #include "sort.h" #include "tags.h" #include "url.h" #ifdef USE_HCACHE #include "hcache/hcache.h" #endif /** * check_capabilities - Make sure we can log in to this server * @param idata Server data * @retval 0 Success * @retval -1 Failure */ static int check_capabilities(struct ImapData *idata) { if (imap_exec(idata, "CAPABILITY", 0) != 0) { imap_error("check_capabilities", idata->buf); return -1; } if (!(mutt_bit_isset(idata->capabilities, IMAP4) || mutt_bit_isset(idata->capabilities, IMAP4REV1))) { mutt_error( _("This IMAP server is ancient. NeoMutt does not work with it.")); return -1; } return 0; } /** * get_flags - Make a simple list out of a FLAGS response * @param hflags List to store flags * @param s String containing flags * @retval ptr End of the flags * @retval ptr NULL Failure * * return stream following FLAGS response */ static char *get_flags(struct ListHead *hflags, char *s) { /* sanity-check string */ if (mutt_str_strncasecmp("FLAGS", s, 5) != 0) { mutt_debug(1, "not a FLAGS response: %s\n", s); return NULL; } s += 5; SKIPWS(s); if (*s != '(') { mutt_debug(1, "bogus FLAGS response: %s\n", s); return NULL; } /* update caller's flags handle */ while (*s && *s != ')') { s++; SKIPWS(s); const char *flag_word = s; while (*s && (*s != ')') && !ISSPACE(*s)) s++; const char ctmp = *s; *s = '\0'; if (*flag_word) mutt_list_insert_tail(hflags, mutt_str_strdup(flag_word)); *s = ctmp; } /* note bad flags response */ if (*s != ')') { mutt_debug(1, "Unterminated FLAGS response: %s\n", s); mutt_list_free(hflags); return NULL; } s++; return s; } /** * set_flag - append str to flags if we currently have permission according to aclbit * @param[in] idata Server data * @param[in] aclbit Permissions, e.g. #MUTT_ACL_WRITE * @param[in] flag Does the email have the flag set? * @param[in] str Server flag name * @param[out] flags Buffer for server command * @param[in] flsize Length of buffer */ static void set_flag(struct ImapData *idata, int aclbit, int flag, const char *str, char *flags, size_t flsize) { if (mutt_bit_isset(idata->ctx->rights, aclbit)) if (flag && imap_has_flag(&idata->flags, str)) mutt_str_strcat(flags, flsize, str); } /** * make_msg_set - Make a message set * @param[in] idata Server data * @param[in] buf Buffer to store message set * @param[in] flag Flags to match, e.g. #MUTT_DELETED * @param[in] changed Matched messages that have been altered * @param[in] invert Flag matches should be inverted * @param[out] pos Cursor used for multiple calls to this function * @retval num Messages in the set * * @note Headers must be in SORT_ORDER. See imap_exec_msgset() for args. * Pos is an opaque pointer a la strtok(). It should be 0 at first call. */ static int make_msg_set(struct ImapData *idata, struct Buffer *buf, int flag, bool changed, bool invert, int *pos) { int count = 0; /* number of messages in message set */ unsigned int setstart = 0; /* start of current message range */ int n; bool started = false; struct Header **hdrs = idata->ctx->hdrs; for (n = *pos; n < idata->ctx->msgcount && buf->dptr - buf->data < IMAP_MAX_CMDLEN; n++) { bool match = false; /* whether current message matches flag condition */ /* don't include pending expunged messages */ if (hdrs[n]->active) { switch (flag) { case MUTT_DELETED: if (hdrs[n]->deleted != HEADER_DATA(hdrs[n])->deleted) match = invert ^ hdrs[n]->deleted; break; case MUTT_FLAG: if (hdrs[n]->flagged != HEADER_DATA(hdrs[n])->flagged) match = invert ^ hdrs[n]->flagged; break; case MUTT_OLD: if (hdrs[n]->old != HEADER_DATA(hdrs[n])->old) match = invert ^ hdrs[n]->old; break; case MUTT_READ: if (hdrs[n]->read != HEADER_DATA(hdrs[n])->read) match = invert ^ hdrs[n]->read; break; case MUTT_REPLIED: if (hdrs[n]->replied != HEADER_DATA(hdrs[n])->replied) match = invert ^ hdrs[n]->replied; break; case MUTT_TAG: if (hdrs[n]->tagged) match = true; break; case MUTT_TRASH: if (hdrs[n]->deleted && !hdrs[n]->purge) match = true; break; } } if (match && (!changed || hdrs[n]->changed)) { count++; if (setstart == 0) { setstart = HEADER_DATA(hdrs[n])->uid; if (!started) { mutt_buffer_printf(buf, "%u", HEADER_DATA(hdrs[n])->uid); started = true; } else mutt_buffer_printf(buf, ",%u", HEADER_DATA(hdrs[n])->uid); } /* tie up if the last message also matches */ else if (n == idata->ctx->msgcount - 1) mutt_buffer_printf(buf, ":%u", HEADER_DATA(hdrs[n])->uid); } /* End current set if message doesn't match or we've reached the end * of the mailbox via inactive messages following the last match. */ else if (setstart && (hdrs[n]->active || n == idata->ctx->msgcount - 1)) { if (HEADER_DATA(hdrs[n - 1])->uid > setstart) mutt_buffer_printf(buf, ":%u", HEADER_DATA(hdrs[n - 1])->uid); setstart = 0; } } *pos = n; return count; } /** * compare_flags_for_copy - Compare local flags against the server * @param h Header of email * @retval true Flags have changed * @retval false Flags match cached server flags * * The comparison of flags EXCLUDES the deleted flag. */ static bool compare_flags_for_copy(struct Header *h) { struct ImapHeaderData *hd = (struct ImapHeaderData *) h->data; if (h->read != hd->read) return true; if (h->old != hd->old) return true; if (h->flagged != hd->flagged) return true; if (h->replied != hd->replied) return true; return false; } /** * sync_helper - Sync flag changes to the server * @param idata Server data * @param right ACL, e.g. #MUTT_ACL_DELETE * @param flag Mutt flag, e.g. MUTT_DELETED * @param name Name of server flag * @retval >=0 Success, number of messages * @retval -1 Failure */ static int sync_helper(struct ImapData *idata, int right, int flag, const char *name) { int count = 0; int rc; char buf[LONG_STRING]; if (!idata->ctx) return -1; if (!mutt_bit_isset(idata->ctx->rights, right)) return 0; if (right == MUTT_ACL_WRITE && !imap_has_flag(&idata->flags, name)) return 0; snprintf(buf, sizeof(buf), "+FLAGS.SILENT (%s)", name); rc = imap_exec_msgset(idata, "UID STORE", buf, flag, 1, 0); if (rc < 0) return rc; count += rc; buf[0] = '-'; rc = imap_exec_msgset(idata, "UID STORE", buf, flag, 1, 1); if (rc < 0) return rc; count += rc; return count; } /** * get_mailbox - Split mailbox URI * @param path Mailbox URI * @param hidata Server data * @param buf Buffer to store mailbox name * @param blen Length of buffer * @retval 0 Success * @retval -1 Failure * * Split up a mailbox URI. The connection info is stored in the ImapData and * the mailbox name is stored in buf. */ static int get_mailbox(const char *path, struct ImapData **hidata, char *buf, size_t blen) { struct ImapMbox mx; if (imap_parse_path(path, &mx)) { mutt_debug(1, "Error parsing %s\n", path); return -1; } if (!(*hidata = imap_conn_find(&(mx.account), ImapPassive ? MUTT_IMAP_CONN_NONEW : 0)) || (*hidata)->state < IMAP_AUTHENTICATED) { FREE(&mx.mbox); return -1; } imap_fix_path(*hidata, mx.mbox, buf, blen); if (!*buf) mutt_str_strfcpy(buf, "INBOX", blen); FREE(&mx.mbox); return 0; } /** * do_search - Perform a search of messages * @param search List of pattern to match * @param allpats Must all patterns match? * @retval num Number of patterns search that should be done server-side * * Count the number of patterns that can be done by the server (are full-text). */ static int do_search(const struct Pattern *search, int allpats) { int rc = 0; const struct Pattern *pat = NULL; for (pat = search; pat; pat = pat->next) { switch (pat->op) { case MUTT_BODY: case MUTT_HEADER: case MUTT_WHOLE_MSG: if (pat->stringmatch) rc++; break; case MUTT_SERVERSEARCH: rc++; break; default: if (pat->child && do_search(pat->child, 1)) rc++; } if (!allpats) break; } return rc; } /** * compile_search - Convert NeoMutt pattern to IMAP search * @param ctx Context * @param pat Pattern to convert * @param buf Buffer for result * @retval 0 Success * @retval -1 Failure * * Convert neomutt Pattern to IMAP SEARCH command containing only elements * that require full-text search (neomutt already has what it needs for most * match types, and does a better job (eg server doesn't support regexes). */ static int compile_search(struct Context *ctx, const struct Pattern *pat, struct Buffer *buf) { if (do_search(pat, 0) == 0) return 0; if (pat->not) mutt_buffer_addstr(buf, "NOT "); if (pat->child) { int clauses; clauses = do_search(pat->child, 1); if (clauses > 0) { const struct Pattern *clause = pat->child; mutt_buffer_addch(buf, '('); while (clauses) { if (do_search(clause, 0)) { if (pat->op == MUTT_OR && clauses > 1) mutt_buffer_addstr(buf, "OR "); clauses--; if (compile_search(ctx, clause, buf) < 0) return -1; if (clauses) mutt_buffer_addch(buf, ' '); } clause = clause->next; } mutt_buffer_addch(buf, ')'); } } else { char term[STRING]; char *delim = NULL; switch (pat->op) { case MUTT_HEADER: mutt_buffer_addstr(buf, "HEADER "); /* extract header name */ delim = strchr(pat->p.str, ':'); if (!delim) { mutt_error(_("Header search without header name: %s"), pat->p.str); return -1; } *delim = '\0'; imap_quote_string(term, sizeof(term), pat->p.str, false); mutt_buffer_addstr(buf, term); mutt_buffer_addch(buf, ' '); /* and field */ *delim = ':'; delim++; SKIPWS(delim); imap_quote_string(term, sizeof(term), delim, false); mutt_buffer_addstr(buf, term); break; case MUTT_BODY: mutt_buffer_addstr(buf, "BODY "); imap_quote_string(term, sizeof(term), pat->p.str, false); mutt_buffer_addstr(buf, term); break; case MUTT_WHOLE_MSG: mutt_buffer_addstr(buf, "TEXT "); imap_quote_string(term, sizeof(term), pat->p.str, false); mutt_buffer_addstr(buf, term); break; case MUTT_SERVERSEARCH: { struct ImapData *idata = ctx->data; if (!mutt_bit_isset(idata->capabilities, X_GM_EXT1)) { mutt_error(_("Server-side custom search not supported: %s"), pat->p.str); return -1; } } mutt_buffer_addstr(buf, "X-GM-RAW "); imap_quote_string(term, sizeof(term), pat->p.str, false); mutt_buffer_addstr(buf, term); break; } } return 0; } /** * longest_common_prefix - Find longest prefix common to two strings * @param dest Destination buffer * @param src Source buffer * @param start Starting offset into string * @param dlen Destination buffer length * @retval num Length of the common string * * Trim dest to the length of the longest prefix it shares with src. */ static size_t longest_common_prefix(char *dest, const char *src, size_t start, size_t dlen) { size_t pos = start; while (pos < dlen && dest[pos] && dest[pos] == src[pos]) pos++; dest[pos] = '\0'; return pos; } /** * complete_hosts - Look for completion matches for mailboxes * @param buf Partial mailbox name to complete * @param buflen Length of buffer * @retval 0 Success * @retval -1 Failure * * look for IMAP URLs to complete from defined mailboxes. Could be extended to * complete over open connections and account/folder hooks too. */ static int complete_hosts(char *buf, size_t buflen) { struct Buffy *mailbox = NULL; struct Connection *conn = NULL; int rc = -1; size_t matchlen; matchlen = mutt_str_strlen(buf); for (mailbox = Incoming; mailbox; mailbox = mailbox->next) { if (mutt_str_strncmp(buf, mailbox->path, matchlen) == 0) { if (rc) { mutt_str_strfcpy(buf, mailbox->path, buflen); rc = 0; } else longest_common_prefix(buf, mailbox->path, matchlen, buflen); } } TAILQ_FOREACH(conn, mutt_socket_head(), entries) { struct Url url; char urlstr[LONG_STRING]; if (conn->account.type != MUTT_ACCT_TYPE_IMAP) continue; mutt_account_tourl(&conn->account, &url); /* FIXME: how to handle multiple users on the same host? */ url.user = NULL; url.path = NULL; url_tostring(&url, urlstr, sizeof(urlstr), 0); if (mutt_str_strncmp(buf, urlstr, matchlen) == 0) { if (rc) { mutt_str_strfcpy(buf, urlstr, buflen); rc = 0; } else longest_common_prefix(buf, urlstr, matchlen, buflen); } } return rc; } /** * imap_access - Check permissions on an IMAP mailbox * @param path Mailbox path * @retval 0 Success * @retval <0 Failure * * TODO: ACL checks. Right now we assume if it exists we can mess with it. */ int imap_access(const char *path) { struct ImapData *idata = NULL; struct ImapMbox mx; char buf[LONG_STRING]; char mailbox[LONG_STRING]; char mbox[LONG_STRING]; int rc; if (imap_parse_path(path, &mx)) return -1; idata = imap_conn_find(&mx.account, ImapPassive ? MUTT_IMAP_CONN_NONEW : 0); if (!idata) { FREE(&mx.mbox); return -1; } imap_fix_path(idata, mx.mbox, mailbox, sizeof(mailbox)); if (!*mailbox) mutt_str_strfcpy(mailbox, "INBOX", sizeof(mailbox)); /* we may already be in the folder we're checking */ if (mutt_str_strcmp(idata->mailbox, mx.mbox) == 0) { FREE(&mx.mbox); return 0; } FREE(&mx.mbox); if (imap_mboxcache_get(idata, mailbox, 0)) { mutt_debug(3, "found %s in cache\n", mailbox); return 0; } imap_munge_mbox_name(idata, mbox, sizeof(mbox), mailbox); if (mutt_bit_isset(idata->capabilities, IMAP4REV1)) snprintf(buf, sizeof(buf), "STATUS %s (UIDVALIDITY)", mbox); else if (mutt_bit_isset(idata->capabilities, STATUS)) snprintf(buf, sizeof(buf), "STATUS %s (UID-VALIDITY)", mbox); else { mutt_debug(2, "STATUS not supported?\n"); return -1; } rc = imap_exec(idata, buf, IMAP_CMD_FAIL_OK); if (rc < 0) { mutt_debug(1, "Can't check STATUS of %s\n", mbox); return rc; } return 0; } /** * imap_create_mailbox - Create a new mailbox * @param idata Server data * @param mailbox Mailbox to create * @retval 0 Success * @retval -1 Failure */ int imap_create_mailbox(struct ImapData *idata, char *mailbox) { char buf[LONG_STRING], mbox[LONG_STRING]; imap_munge_mbox_name(idata, mbox, sizeof(mbox), mailbox); snprintf(buf, sizeof(buf), "CREATE %s", mbox); if (imap_exec(idata, buf, 0) != 0) { mutt_error(_("CREATE failed: %s"), imap_cmd_trailer(idata)); return -1; } return 0; } /** * imap_rename_mailbox - Rename a mailbox * @param idata Server data * @param mx Existing mailbox * @param newname New name for mailbox * @retval 0 Success * @retval -1 Failure */ int imap_rename_mailbox(struct ImapData *idata, struct ImapMbox *mx, const char *newname) { char oldmbox[LONG_STRING]; char newmbox[LONG_STRING]; char buf[LONG_STRING]; imap_munge_mbox_name(idata, oldmbox, sizeof(oldmbox), mx->mbox); imap_munge_mbox_name(idata, newmbox, sizeof(newmbox), newname); snprintf(buf, sizeof(buf), "RENAME %s %s", oldmbox, newmbox); if (imap_exec(idata, buf, 0) != 0) return -1; return 0; } /** * imap_delete_mailbox - Delete a mailbox * @param ctx Context * @param mx Mailbox to delete * @retval 0 Success * @retval -1 Failure */ int imap_delete_mailbox(struct Context *ctx, struct ImapMbox *mx) { char buf[PATH_MAX], mbox[PATH_MAX]; struct ImapData *idata = NULL; if (!ctx || !ctx->data) { idata = imap_conn_find(&mx->account, ImapPassive ? MUTT_IMAP_CONN_NONEW : 0); if (!idata) { FREE(&mx->mbox); return -1; } } else { idata = ctx->data; } imap_munge_mbox_name(idata, mbox, sizeof(mbox), mx->mbox); snprintf(buf, sizeof(buf), "DELETE %s", mbox); if (imap_exec(idata, buf, 0) != 0) return -1; return 0; } /** * imap_logout_all - close all open connections * * Quick and dirty until we can make sure we've got all the context we need. */ void imap_logout_all(void) { struct ConnectionList *head = mutt_socket_head(); struct Connection *np, *tmp; TAILQ_FOREACH_SAFE(np, head, entries, tmp) { if (np->account.type == MUTT_ACCT_TYPE_IMAP && np->fd >= 0) { TAILQ_REMOVE(head, np, entries); mutt_message(_("Closing connection to %s..."), np->account.host); imap_logout((struct ImapData **) (void *) &np->data); mutt_clear_error(); mutt_socket_free(np); } } } /** * imap_read_literal - Read bytes bytes from server into file * @param fp File handle for email file * @param idata Server data * @param bytes Number of bytes to read * @param pbar Progress bar * @retval 0 Success * @retval -1 Failure * * Not explicitly buffered, relies on FILE buffering. * * @note Strips `\r` from `\r\n`. * Apparently even literals use `\r\n`-terminated strings ?! */ int imap_read_literal(FILE *fp, struct ImapData *idata, unsigned long bytes, struct Progress *pbar) { char c; bool r = false; struct Buffer *buf = NULL; if (DebugLevel >= IMAP_LOG_LTRL) buf = mutt_buffer_alloc(bytes + 10); mutt_debug(2, "reading %ld bytes\n", bytes); for (unsigned long pos = 0; pos < bytes; pos++) { if (mutt_socket_readchar(idata->conn, &c) != 1) { mutt_debug(1, "error during read, %ld bytes read\n", pos); idata->status = IMAP_FATAL; mutt_buffer_free(&buf); return -1; } if (r && c != '\n') fputc('\r', fp); if (c == '\r') { r = true; continue; } else r = false; fputc(c, fp); if (pbar && !(pos % 1024)) mutt_progress_update(pbar, pos, -1); if (DebugLevel >= IMAP_LOG_LTRL) mutt_buffer_addch(buf, c); } if (DebugLevel >= IMAP_LOG_LTRL) { mutt_debug(IMAP_LOG_LTRL, "\n%s", buf->data); mutt_buffer_free(&buf); } return 0; } /** * imap_expunge_mailbox - Purge messages from the server * @param idata Server data * * Purge IMAP portion of expunged messages from the context. Must not be done * while something has a handle on any headers (eg inside pager or editor). * That is, check IMAP_REOPEN_ALLOW. */ void imap_expunge_mailbox(struct ImapData *idata) { struct Header *h = NULL; int cacheno; short old_sort; #ifdef USE_HCACHE idata->hcache = imap_hcache_open(idata, NULL); #endif old_sort = Sort; Sort = SORT_ORDER; mutt_sort_headers(idata->ctx, 0); for (int i = 0; i < idata->ctx->msgcount; i++) { h = idata->ctx->hdrs[i]; if (h->index == INT_MAX) { mutt_debug(2, "Expunging message UID %u.\n", HEADER_DATA(h)->uid); h->active = false; idata->ctx->size -= h->content->length; imap_cache_del(idata, h); #ifdef USE_HCACHE imap_hcache_del(idata, HEADER_DATA(h)->uid); #endif /* free cached body from disk, if necessary */ cacheno = HEADER_DATA(h)->uid % IMAP_CACHE_LEN; if (idata->cache[cacheno].uid == HEADER_DATA(h)->uid && idata->cache[cacheno].path) { unlink(idata->cache[cacheno].path); FREE(&idata->cache[cacheno].path); } mutt_hash_int_delete(idata->uid_hash, HEADER_DATA(h)->uid, h); imap_free_header_data((struct ImapHeaderData **) &h->data); } else { h->index = i; /* NeoMutt has several places where it turns off h->active as a * hack. For example to avoid FLAG updates, or to exclude from * imap_exec_msgset. * * Unfortunately, when a reopen is allowed and the IMAP_EXPUNGE_PENDING * flag becomes set (e.g. a flag update to a modified header), * this function will be called by imap_cmd_finish(). * * The mx_update_tables() will free and remove these "inactive" headers, * despite that an EXPUNGE was not received for them. * This would result in memory leaks and segfaults due to dangling * pointers in the msn_index and uid_hash. * * So this is another hack to work around the hacks. We don't want to * remove the messages, so make sure active is on. */ h->active = true; } } #ifdef USE_HCACHE imap_hcache_close(idata); #endif /* We may be called on to expunge at any time. We can't rely on the caller * to always know to rethread */ mx_update_tables(idata->ctx, false); Sort = old_sort; mutt_sort_headers(idata->ctx, 1); } /** * imap_conn_find - Find an open IMAP connection * @param account Account to search * @param flags Flags, e.g. #MUTT_IMAP_CONN_NONEW * @retval ptr Matching connection * @retval NULL Failure * * Find an open IMAP connection matching account, or open a new one if none can * be found. */ struct ImapData *imap_conn_find(const struct Account *account, int flags) { struct Connection *conn = NULL; struct Account *creds = NULL; struct ImapData *idata = NULL; bool new = false; while ((conn = mutt_conn_find(conn, account))) { if (!creds) creds = &conn->account; else memcpy(&conn->account, creds, sizeof(struct Account)); idata = conn->data; if (flags & MUTT_IMAP_CONN_NONEW) { if (!idata) { /* This should only happen if we've come to the end of the list */ mutt_socket_free(conn); return NULL; } else if (idata->state < IMAP_AUTHENTICATED) continue; } if (flags & MUTT_IMAP_CONN_NOSELECT && idata && idata->state >= IMAP_SELECTED) continue; if (idata && idata->status == IMAP_FATAL) continue; break; } if (!conn) return NULL; /* this happens when the initial connection fails */ if (!idata) { /* The current connection is a new connection */ idata = imap_new_idata(); if (!idata) { mutt_socket_free(conn); return NULL; } conn->data = idata; idata->conn = conn; new = true; } if (idata->state == IMAP_DISCONNECTED) imap_open_connection(idata); if (idata->state == IMAP_CONNECTED) { if (imap_authenticate(idata) == IMAP_AUTH_SUCCESS) { idata->state = IMAP_AUTHENTICATED; FREE(&idata->capstr); new = true; if (idata->conn->ssf) mutt_debug(2, "Communication encrypted at %d bits\n", idata->conn->ssf); } else mutt_account_unsetpass(&idata->conn->account); } if (new && idata->state == IMAP_AUTHENTICATED) { /* capabilities may have changed */ imap_exec(idata, "CAPABILITY", IMAP_CMD_QUEUE); /* enable RFC6855, if the server supports that */ if (mutt_bit_isset(idata->capabilities, ENABLE)) imap_exec(idata, "ENABLE UTF8=ACCEPT", IMAP_CMD_QUEUE); /* get root delimiter, '/' as default */ idata->delim = '/'; imap_exec(idata, "LIST \"\" \"\"", IMAP_CMD_QUEUE); /* we may need the root delimiter before we open a mailbox */ imap_exec(idata, NULL, IMAP_CMD_FAIL_OK); } return idata; } /** * imap_open_connection - Open an IMAP connection * @param idata Server data * @retval 0 Success * @retval -1 Failure */ int imap_open_connection(struct ImapData *idata) { char buf[LONG_STRING]; if (mutt_socket_open(idata->conn) < 0) return -1; idata->state = IMAP_CONNECTED; if (imap_cmd_step(idata) != IMAP_CMD_OK) { imap_close_connection(idata); return -1; } if (mutt_str_strncasecmp("* OK", idata->buf, 4) == 0) { if ((mutt_str_strncasecmp("* OK [CAPABILITY", idata->buf, 16) != 0) && check_capabilities(idata)) { goto bail; } #ifdef USE_SSL /* Attempt STARTTLS if available and desired. */ if (!idata->conn->ssf && (SslForceTls || mutt_bit_isset(idata->capabilities, STARTTLS))) { int rc; if (SslForceTls) rc = MUTT_YES; else if ((rc = query_quadoption(SslStarttls, _("Secure connection with TLS?"))) == MUTT_ABORT) { goto err_close_conn; } if (rc == MUTT_YES) { rc = imap_exec(idata, "STARTTLS", IMAP_CMD_FAIL_OK); if (rc == -1) goto bail; if (rc != -2) { if (mutt_ssl_starttls(idata->conn)) { mutt_error(_("Could not negotiate TLS connection")); goto err_close_conn; } else { /* RFC2595 demands we recheck CAPABILITY after TLS completes. */ if (imap_exec(idata, "CAPABILITY", 0)) goto bail; } } } } if (SslForceTls && !idata->conn->ssf) { mutt_error(_("Encrypted connection unavailable")); goto err_close_conn; } #endif } else if (mutt_str_strncasecmp("* PREAUTH", idata->buf, 9) == 0) { idata->state = IMAP_AUTHENTICATED; if (check_capabilities(idata) != 0) goto bail; FREE(&idata->capstr); } else { imap_error("imap_open_connection()", buf); goto bail; } return 0; #ifdef USE_SSL err_close_conn: imap_close_connection(idata); #endif bail: FREE(&idata->capstr); return -1; } /** * imap_close_connection - Close an IMAP connection * @param idata Server data */ void imap_close_connection(struct ImapData *idata) { if (idata->state != IMAP_DISCONNECTED) { mutt_socket_close(idata->conn); idata->state = IMAP_DISCONNECTED; } idata->seqno = idata->nextcmd = idata->lastcmd = idata->status = false; memset(idata->cmds, 0, sizeof(struct ImapCommand) * idata->cmdslots); } /** * imap_logout - Gracefully log out of server * @param idata Server data */ void imap_logout(struct ImapData **idata) { /* we set status here to let imap_handle_untagged know we _expect_ to * receive a bye response (so it doesn't freak out and close the conn) */ (*idata)->status = IMAP_BYE; imap_cmd_start(*idata, "LOGOUT"); if (ImapPollTimeout <= 0 || mutt_socket_poll((*idata)->conn, ImapPollTimeout) != 0) { while (imap_cmd_step(*idata) == IMAP_CMD_CONTINUE) ; } mutt_socket_close((*idata)->conn); imap_free_idata(idata); } /** * imap_has_flag - Does the flag exist in the list * @param flag_list List of server flags * @param flag Flag to find * @retval true Flag exists * * Do a caseless comparison of the flag against a flag list, return true if * found or flag list has '\*'. */ bool imap_has_flag(struct ListHead *flag_list, const char *flag) { if (STAILQ_EMPTY(flag_list)) return false; struct ListNode *np; STAILQ_FOREACH(np, flag_list, entries) { if (mutt_str_strncasecmp(np->data, flag, strlen(np->data)) == 0) return true; if (mutt_str_strncmp(np->data, "\\*", strlen(np->data)) == 0) return true; } return false; } /** * imap_exec_msgset - Prepare commands for all messages matching conditions * @param idata ImapData containing context containing header set * @param pre prefix commands * @param post postfix commands * @param flag flag type on which to filter, e.g. MUTT_REPLIED * @param changed include only changed messages in message set * @param invert invert sense of flag, eg MUTT_READ matches unread messages * @retval num Matched messages * @retval -1 Failure * * pre/post: commands are of the form "%s %s %s %s", tag, pre, message set, post * Prepares commands for all messages matching conditions * (must be flushed with imap_exec) */ int imap_exec_msgset(struct ImapData *idata, const char *pre, const char *post, int flag, int changed, int invert) { struct Header **hdrs = NULL; short oldsort; int pos; int rc; int count = 0; struct Buffer *cmd = mutt_buffer_new(); /* We make a copy of the headers just in case resorting doesn't give exactly the original order (duplicate messages?), because other parts of the ctx are tied to the header order. This may be overkill. */ oldsort = Sort; if (Sort != SORT_ORDER) { hdrs = idata->ctx->hdrs; idata->ctx->hdrs = mutt_mem_malloc(idata->ctx->msgcount * sizeof(struct Header *)); memcpy(idata->ctx->hdrs, hdrs, idata->ctx->msgcount * sizeof(struct Header *)); Sort = SORT_ORDER; qsort(idata->ctx->hdrs, idata->ctx->msgcount, sizeof(struct Header *), mutt_get_sort_func(SORT_ORDER)); } pos = 0; do { cmd->dptr = cmd->data; mutt_buffer_printf(cmd, "%s ", pre); rc = make_msg_set(idata, cmd, flag, changed, invert, &pos); if (rc > 0) { mutt_buffer_printf(cmd, " %s", post); if (imap_exec(idata, cmd->data, IMAP_CMD_QUEUE)) { rc = -1; goto out; } count += rc; } } while (rc > 0); rc = count; out: mutt_buffer_free(&cmd); if (oldsort != Sort) { Sort = oldsort; FREE(&idata->ctx->hdrs); idata->ctx->hdrs = hdrs; } return rc; } /** * imap_sync_message_for_copy - Update server to reflect the flags of a single message * @param[in] idata Server data * @param[in] hdr Header of the email * @param[in] cmd Buffer for the command string * @param[out] err_continue Did the user force a continue? * @retval 0 Success * @retval -1 Failure * * Update the IMAP server to reflect the flags for a single message before * performing a "UID COPY". * * @note This does not sync the "deleted" flag state, because it is not * desirable to propagate that flag into the copy. */ int imap_sync_message_for_copy(struct ImapData *idata, struct Header *hdr, struct Buffer *cmd, int *err_continue) { char flags[LONG_STRING]; char *tags; char uid[11]; if (!compare_flags_for_copy(hdr)) { if (hdr->deleted == HEADER_DATA(hdr)->deleted) hdr->changed = false; return 0; } snprintf(uid, sizeof(uid), "%u", HEADER_DATA(hdr)->uid); cmd->dptr = cmd->data; mutt_buffer_addstr(cmd, "UID STORE "); mutt_buffer_addstr(cmd, uid); flags[0] = '\0'; set_flag(idata, MUTT_ACL_SEEN, hdr->read, "\\Seen ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, hdr->old, "Old ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, hdr->flagged, "\\Flagged ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, hdr->replied, "\\Answered ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_DELETE, HEADER_DATA(hdr)->deleted, "\\Deleted ", flags, sizeof(flags)); if (mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE)) { /* restore system flags */ if (HEADER_DATA(hdr)->flags_system) mutt_str_strcat(flags, sizeof(flags), HEADER_DATA(hdr)->flags_system); /* set custom flags */ tags = driver_tags_get_with_hidden(&hdr->tags); if (tags) { mutt_str_strcat(flags, sizeof(flags), tags); FREE(&tags); } } mutt_str_remove_trailing_ws(flags); /* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to * explicitly revoke all system flags (if we have permission) */ if (!*flags) { set_flag(idata, MUTT_ACL_SEEN, 1, "\\Seen ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, 1, "Old ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, 1, "\\Flagged ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, 1, "\\Answered ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_DELETE, !HEADER_DATA(hdr)->deleted, "\\Deleted ", flags, sizeof(flags)); /* erase custom flags */ if (mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE) && HEADER_DATA(hdr)->flags_remote) mutt_str_strcat(flags, sizeof(flags), HEADER_DATA(hdr)->flags_remote); mutt_str_remove_trailing_ws(flags); mutt_buffer_addstr(cmd, " -FLAGS.SILENT ("); } else mutt_buffer_addstr(cmd, " FLAGS.SILENT ("); mutt_buffer_addstr(cmd, flags); mutt_buffer_addstr(cmd, ")"); /* dumb hack for bad UW-IMAP 4.7 servers spurious FLAGS updates */ hdr->active = false; /* after all this it's still possible to have no flags, if you * have no ACL rights */ if (*flags && (imap_exec(idata, cmd->data, 0) != 0) && err_continue && (*err_continue != MUTT_YES)) { *err_continue = imap_continue("imap_sync_message: STORE failed", idata->buf); if (*err_continue != MUTT_YES) { hdr->active = true; return -1; } } /* server have now the updated flags */ FREE(&HEADER_DATA(hdr)->flags_remote); HEADER_DATA(hdr)->flags_remote = driver_tags_get_with_hidden(&hdr->tags); hdr->active = true; if (hdr->deleted == HEADER_DATA(hdr)->deleted) hdr->changed = false; return 0; } /** * imap_check_mailbox - use the NOOP or IDLE command to poll for new mail * @param ctx Context * @param force Don't wait * @retval #MUTT_REOPENED mailbox has been externally modified * @retval #MUTT_NEW_MAIL new mail has arrived * @retval 0 no change * @retval -1 error */ int imap_check_mailbox(struct Context *ctx, int force) { return imap_check(ctx->data, force); } /** * imap_check - Check for new mail * @param idata Server data * @param force Force a refresh * @retval >0 Success, e.g. #MUTT_REOPENED * @retval -1 Failure */ int imap_check(struct ImapData *idata, int force) { /* overload keyboard timeout to avoid many mailbox checks in a row. * Most users don't like having to wait exactly when they press a key. */ int result = 0; /* try IDLE first, unless force is set */ if (!force && ImapIdle && mutt_bit_isset(idata->capabilities, IDLE) && (idata->state != IMAP_IDLE || time(NULL) >= idata->lastread + ImapKeepalive)) { if (imap_cmd_idle(idata) < 0) return -1; } if (idata->state == IMAP_IDLE) { while ((result = mutt_socket_poll(idata->conn, 0)) > 0) { if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE) { mutt_debug(1, "Error reading IDLE response\n"); return -1; } } if (result < 0) { mutt_debug(1, "Poll failed, disabling IDLE\n"); mutt_bit_unset(idata->capabilities, IDLE); } } if ((force || (idata->state != IMAP_IDLE && time(NULL) >= idata->lastread + Timeout)) && imap_exec(idata, "NOOP", IMAP_CMD_POLL) != 0) { return -1; } /* We call this even when we haven't run NOOP in case we have pending * changes to process, since we can reopen here. */ imap_cmd_finish(idata); if (idata->check_status & IMAP_EXPUNGE_PENDING) result = MUTT_REOPENED; else if (idata->check_status & IMAP_NEWMAIL_PENDING) result = MUTT_NEW_MAIL; else if (idata->check_status & IMAP_FLAGS_PENDING) result = MUTT_FLAGS; idata->check_status = 0; return result; } /** * imap_buffy_check - Check for new mail in subscribed folders * @param check_stats Check for message stats too * @retval num Number of mailboxes with new mail * @retval 0 Failure * * Given a list of mailboxes rather than called once for each so that it can * batch the commands and save on round trips. */ int imap_buffy_check(int check_stats) { struct ImapData *idata = NULL; struct ImapData *lastdata = NULL; struct Buffy *mailbox = NULL; char name[LONG_STRING]; char command[LONG_STRING]; char munged[LONG_STRING]; int buffies = 0; for (mailbox = Incoming; mailbox; mailbox = mailbox->next) { /* Init newly-added mailboxes */ if (!mailbox->magic) { if (mx_is_imap(mailbox->path)) mailbox->magic = MUTT_IMAP; } if (mailbox->magic != MUTT_IMAP) continue; if (get_mailbox(mailbox->path, &idata, name, sizeof(name)) < 0) { mailbox->new = false; continue; } /* Don't issue STATUS on the selected mailbox, it will be NOOPed or * IDLEd elsewhere. * idata->mailbox may be NULL for connections other than the current * mailbox's, and shouldn't expand to INBOX in that case. #3216. */ if (idata->mailbox && (imap_mxcmp(name, idata->mailbox) == 0)) { mailbox->new = false; continue; } if (!mutt_bit_isset(idata->capabilities, IMAP4REV1) && !mutt_bit_isset(idata->capabilities, STATUS)) { mutt_debug(2, "Server doesn't support STATUS\n"); continue; } if (lastdata && idata != lastdata) { /* Send commands to previous server. Sorting the buffy list * may prevent some infelicitous interleavings */ if (imap_exec(lastdata, NULL, IMAP_CMD_FAIL_OK | IMAP_CMD_POLL) == -1) mutt_debug(1, "#1 Error polling mailboxes\n"); lastdata = NULL; } if (!lastdata) lastdata = idata; imap_munge_mbox_name(idata, munged, sizeof(munged), name); if (check_stats) { snprintf(command, sizeof(command), "STATUS %s (UIDNEXT UIDVALIDITY UNSEEN RECENT MESSAGES)", munged); } else { snprintf(command, sizeof(command), "STATUS %s (UIDNEXT UIDVALIDITY UNSEEN RECENT)", munged); } if (imap_exec(idata, command, IMAP_CMD_QUEUE | IMAP_CMD_POLL) < 0) { mutt_debug(1, "Error queueing command\n"); return 0; } } if (lastdata && (imap_exec(lastdata, NULL, IMAP_CMD_FAIL_OK | IMAP_CMD_POLL) == -1)) { mutt_debug(1, "#2 Error polling mailboxes\n"); return 0; } /* collect results */ for (mailbox = Incoming; mailbox; mailbox = mailbox->next) { if (mailbox->magic == MUTT_IMAP && mailbox->new) buffies++; } return buffies; } /** * imap_status - Get the status of a mailbox * @param path Path of mailbox * @param queue true if the command should be queued for the next call * @retval -1 Error * @retval >=0 Count of messages in mailbox * * If queue is true, the command will be sent now and be expected to have been * run on the next call (for pipelining the postponed count). */ int imap_status(char *path, int queue) { static int queued = 0; struct ImapData *idata = NULL; char buf[LONG_STRING]; char mbox[LONG_STRING]; struct ImapStatus *status = NULL; if (get_mailbox(path, &idata, buf, sizeof(buf)) < 0) return -1; /* We are in the folder we're polling - just return the mailbox count. * * Note that imap_mxcmp() converts NULL to "INBOX", so we need to * make sure the idata really is open to a folder. */ if (idata->ctx && !imap_mxcmp(buf, idata->mailbox)) return idata->ctx->msgcount; else if (mutt_bit_isset(idata->capabilities, IMAP4REV1) || mutt_bit_isset(idata->capabilities, STATUS)) { imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf); snprintf(buf, sizeof(buf), "STATUS %s (%s)", mbox, "MESSAGES"); imap_unmunge_mbox_name(idata, mbox); } else { /* Server does not support STATUS, and this is not the current mailbox. * There is no lightweight way to check recent arrivals */ return -1; } if (queue) { imap_exec(idata, buf, IMAP_CMD_QUEUE); queued = 1; return 0; } else if (!queued) imap_exec(idata, buf, 0); queued = 0; status = imap_mboxcache_get(idata, mbox, 0); if (status) return status->messages; return 0; } /** * imap_mboxcache_get - Open an hcache for a mailbox * @param idata Server data * @param mbox Mailbox to cache * @param create Should it be created if it doesn't exist? * @retval ptr Stats of cached mailbox * @retval ptr Stats of new cache entry * @retval NULL Not in cache and create is false * * return cached mailbox stats or NULL if create is 0 */ struct ImapStatus *imap_mboxcache_get(struct ImapData *idata, const char *mbox, bool create) { struct ImapStatus *status = NULL; #ifdef USE_HCACHE header_cache_t *hc = NULL; void *uidvalidity = NULL; void *uidnext = NULL; #endif struct ListNode *np; STAILQ_FOREACH(np, &idata->mboxcache, entries) { status = (struct ImapStatus *) np->data; if (imap_mxcmp(mbox, status->name) == 0) return status; } status = NULL; /* lame */ if (create) { struct ImapStatus *scache = mutt_mem_calloc(1, sizeof(struct ImapStatus)); scache->name = (char *) mbox; mutt_list_insert_tail(&idata->mboxcache, (char *) scache); status = imap_mboxcache_get(idata, mbox, 0); status->name = mutt_str_strdup(mbox); } #ifdef USE_HCACHE hc = imap_hcache_open(idata, mbox); if (hc) { uidvalidity = mutt_hcache_fetch_raw(hc, "/UIDVALIDITY", 12); uidnext = mutt_hcache_fetch_raw(hc, "/UIDNEXT", 8); if (uidvalidity) { if (!status) { mutt_hcache_free(hc, &uidvalidity); mutt_hcache_free(hc, &uidnext); mutt_hcache_close(hc); return imap_mboxcache_get(idata, mbox, 1); } status->uidvalidity = *(unsigned int *) uidvalidity; status->uidnext = uidnext ? *(unsigned int *) uidnext : 0; mutt_debug(3, "hcache uidvalidity %u, uidnext %u\n", status->uidvalidity, status->uidnext); } mutt_hcache_free(hc, &uidvalidity); mutt_hcache_free(hc, &uidnext); mutt_hcache_close(hc); } #endif return status; } /** * imap_mboxcache_free - Free the cached ImapStatus * @param idata Server data */ void imap_mboxcache_free(struct ImapData *idata) { struct ImapStatus *status = NULL; struct ListNode *np; STAILQ_FOREACH(np, &idata->mboxcache, entries) { status = (struct ImapStatus *) np->data; FREE(&status->name); } mutt_list_free(&idata->mboxcache); } /** * imap_search - Find a matching mailbox * @param ctx Context * @param pat Pattern to match * @retval 0 Success * @retval -1 Failure */ int imap_search(struct Context *ctx, const struct Pattern *pat) { struct Buffer buf; struct ImapData *idata = ctx->data; for (int i = 0; i < ctx->msgcount; i++) ctx->hdrs[i]->matched = false; if (do_search(pat, 1) == 0) return 0; mutt_buffer_init(&buf); mutt_buffer_addstr(&buf, "UID SEARCH "); if (compile_search(ctx, pat, &buf) < 0) { FREE(&buf.data); return -1; } if (imap_exec(idata, buf.data, 0) < 0) { FREE(&buf.data); return -1; } FREE(&buf.data); return 0; } /** * imap_subscribe - Subscribe to a mailbox * @param path Mailbox path * @param subscribe True: subscribe, false: unsubscribe * @retval 0 Success * @retval -1 Failure */ int imap_subscribe(char *path, bool subscribe) { struct ImapData *idata = NULL; char buf[LONG_STRING]; char mbox[LONG_STRING]; char errstr[STRING]; struct Buffer err, token; struct ImapMbox mx; if (!mx_is_imap(path) || imap_parse_path(path, &mx) || !mx.mbox) { mutt_error(_("Bad mailbox name")); return -1; } idata = imap_conn_find(&(mx.account), 0); if (!idata) goto fail; imap_fix_path(idata, mx.mbox, buf, sizeof(buf)); if (!*buf) mutt_str_strfcpy(buf, "INBOX", sizeof(buf)); if (ImapCheckSubscribed) { mutt_buffer_init(&token); mutt_buffer_init(&err); err.data = errstr; err.dsize = sizeof(errstr); snprintf(mbox, sizeof(mbox), "%smailboxes \"%s\"", subscribe ? "" : "un", path); if (mutt_parse_rc_line(mbox, &token, &err)) mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr); FREE(&token.data); } if (subscribe) mutt_message(_("Subscribing to %s..."), buf); else mutt_message(_("Unsubscribing from %s..."), buf); imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf); snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox); if (imap_exec(idata, buf, 0) < 0) goto fail; imap_unmunge_mbox_name(idata, mx.mbox); if (subscribe) mutt_message(_("Subscribed to %s"), mx.mbox); else mutt_message(_("Unsubscribed from %s"), mx.mbox); FREE(&mx.mbox); return 0; fail: FREE(&mx.mbox); return -1; } /** * imap_complete - Try to complete an IMAP folder path * @param buf Buffer for result * @param buflen Length of buffer * @param path Partial mailbox name to complete * @retval 0 Success * @retval -1 Failure * * Given a partial IMAP folder path, return a string which adds as much to the * path as is unique */ int imap_complete(char *buf, size_t buflen, char *path) { struct ImapData *idata = NULL; char list[LONG_STRING]; char tmp[LONG_STRING]; struct ImapList listresp; char completion[LONG_STRING]; int clen; size_t matchlen = 0; int completions = 0; struct ImapMbox mx; int rc; if (imap_parse_path(path, &mx)) { mutt_str_strfcpy(buf, path, buflen); return complete_hosts(buf, buflen); } /* don't open a new socket just for completion. Instead complete over * known mailboxes/hooks/etc */ idata = imap_conn_find(&(mx.account), MUTT_IMAP_CONN_NONEW); if (!idata) { FREE(&mx.mbox); mutt_str_strfcpy(buf, path, buflen); return complete_hosts(buf, buflen); } /* reformat path for IMAP list, and append wildcard */ /* don't use INBOX in place of "" */ if (mx.mbox && mx.mbox[0]) imap_fix_path(idata, mx.mbox, list, sizeof(list)); else list[0] = '\0'; /* fire off command */ snprintf(tmp, sizeof(tmp), "%s \"\" \"%s%%\"", ImapListSubscribed ? "LSUB" : "LIST", list); imap_cmd_start(idata, tmp); /* and see what the results are */ mutt_str_strfcpy(completion, NONULL(mx.mbox), sizeof(completion)); idata->cmdtype = IMAP_CT_LIST; idata->cmddata = &listresp; do { listresp.name = NULL; rc = imap_cmd_step(idata); if (rc == IMAP_CMD_CONTINUE && listresp.name) { /* if the folder isn't selectable, append delimiter to force browse * to enter it on second tab. */ if (listresp.noselect) { clen = strlen(listresp.name); listresp.name[clen++] = listresp.delim; listresp.name[clen] = '\0'; } /* copy in first word */ if (!completions) { mutt_str_strfcpy(completion, listresp.name, sizeof(completion)); matchlen = strlen(completion); completions++; continue; } matchlen = longest_common_prefix(completion, listresp.name, 0, matchlen); completions++; } } while (rc == IMAP_CMD_CONTINUE); idata->cmddata = NULL; if (completions) { /* reformat output */ imap_qualify_path(buf, buflen, &mx, completion); mutt_pretty_mailbox(buf, buflen); FREE(&mx.mbox); return 0; } return -1; } /** * imap_fast_trash - Use server COPY command to copy deleted messages to trash * @param ctx Context * @param dest Mailbox to move to * @retval -1 Error * @retval 0 Success * @retval 1 Non-fatal error - try fetch/append */ int imap_fast_trash(struct Context *ctx, char *dest) { char mbox[LONG_STRING]; char mmbox[LONG_STRING]; char prompt[LONG_STRING]; int rc; struct ImapMbox mx; bool triedcreate = false; struct Buffer *sync_cmd = NULL; int err_continue = MUTT_NO; struct ImapData *idata = ctx->data; if (imap_parse_path(dest, &mx)) { mutt_debug(1, "bad destination %s\n", dest); return -1; } /* check that the save-to folder is in the same account */ if (mutt_account_match(&(idata->conn->account), &(mx.account)) == 0) { mutt_debug(3, "%s not same server as %s\n", dest, ctx->path); return 1; } imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox)); if (!*mbox) mutt_str_strfcpy(mbox, "INBOX", sizeof(mbox)); imap_munge_mbox_name(idata, mmbox, sizeof(mmbox), mbox); sync_cmd = mutt_buffer_new(); for (int i = 0; i < ctx->msgcount; i++) { if (ctx->hdrs[i]->active && ctx->hdrs[i]->changed && ctx->hdrs[i]->deleted && !ctx->hdrs[i]->purge) { rc = imap_sync_message_for_copy(idata, ctx->hdrs[i], sync_cmd, &err_continue); if (rc < 0) { mutt_debug(1, "could not sync\n"); goto out; } } } /* loop in case of TRYCREATE */ do { rc = imap_exec_msgset(idata, "UID COPY", mmbox, MUTT_TRASH, 0, 0); if (!rc) { mutt_debug(1, "No messages to trash\n"); rc = -1; goto out; } else if (rc < 0) { mutt_debug(1, "could not queue copy\n"); goto out; } else { mutt_message(ngettext("Copying %d message to %s...", "Copying %d messages to %s...", rc), rc, mbox); } /* let's get it on */ rc = imap_exec(idata, NULL, IMAP_CMD_FAIL_OK); if (rc == -2) { if (triedcreate) { mutt_debug(1, "Already tried to create mailbox %s\n", mbox); break; } /* bail out if command failed for reasons other than nonexistent target */ if (mutt_str_strncasecmp(imap_get_qualifier(idata->buf), "[TRYCREATE]", 11) != 0) break; mutt_debug(3, "server suggests TRYCREATE\n"); snprintf(prompt, sizeof(prompt), _("Create %s?"), mbox); if (Confirmcreate && mutt_yesorno(prompt, 1) != MUTT_YES) { mutt_clear_error(); goto out; } if (imap_create_mailbox(idata, mbox) < 0) break; triedcreate = true; } } while (rc == -2); if (rc != 0) { imap_error("imap_fast_trash", idata->buf); goto out; } rc = 0; out: mutt_buffer_free(&sync_cmd); FREE(&mx.mbox); return (rc < 0) ? -1 : rc; } /** * imap_mbox_open - Implements MxOps::mbox_open() */ static int imap_mbox_open(struct Context *ctx) { struct ImapData *idata = NULL; struct ImapStatus *status = NULL; char buf[PATH_MAX]; char bufout[PATH_MAX]; int count = 0; struct ImapMbox mx, pmx; int rc; if (imap_parse_path(ctx->path, &mx)) { mutt_error(_("%s is an invalid IMAP path"), ctx->path); return -1; } /* we require a connection which isn't currently in IMAP_SELECTED state */ idata = imap_conn_find(&(mx.account), MUTT_IMAP_CONN_NOSELECT); if (!idata) goto fail_noidata; if (idata->state < IMAP_AUTHENTICATED) goto fail; /* once again the context is new */ ctx->data = idata; /* Clean up path and replace the one in the ctx */ imap_fix_path(idata, mx.mbox, buf, sizeof(buf)); if (!*buf) mutt_str_strfcpy(buf, "INBOX", sizeof(buf)); FREE(&(idata->mailbox)); idata->mailbox = mutt_str_strdup(buf); imap_qualify_path(buf, sizeof(buf), &mx, idata->mailbox); FREE(&(ctx->path)); FREE(&(ctx->realpath)); ctx->path = mutt_str_strdup(buf); ctx->realpath = mutt_str_strdup(ctx->path); idata->ctx = ctx; /* clear mailbox status */ idata->status = false; memset(idata->ctx->rights, 0, sizeof(idata->ctx->rights)); idata->new_mail_count = 0; idata->max_msn = 0; mutt_message(_("Selecting %s..."), idata->mailbox); imap_munge_mbox_name(idata, buf, sizeof(buf), idata->mailbox); /* pipeline ACL test */ if (mutt_bit_isset(idata->capabilities, ACL)) { snprintf(bufout, sizeof(bufout), "MYRIGHTS %s", buf); imap_exec(idata, bufout, IMAP_CMD_QUEUE); } /* assume we have all rights if ACL is unavailable */ else { mutt_bit_set(idata->ctx->rights, MUTT_ACL_LOOKUP); mutt_bit_set(idata->ctx->rights, MUTT_ACL_READ); mutt_bit_set(idata->ctx->rights, MUTT_ACL_SEEN); mutt_bit_set(idata->ctx->rights, MUTT_ACL_WRITE); mutt_bit_set(idata->ctx->rights, MUTT_ACL_INSERT); mutt_bit_set(idata->ctx->rights, MUTT_ACL_POST); mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE); mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE); } /* pipeline the postponed count if possible */ pmx.mbox = NULL; if (mx_is_imap(Postponed) && !imap_parse_path(Postponed, &pmx) && mutt_account_match(&pmx.account, &mx.account)) { imap_status(Postponed, 1); } FREE(&pmx.mbox); if (ImapCheckSubscribed) imap_exec(idata, "LSUB \"\" \"*\"", IMAP_CMD_QUEUE); snprintf(bufout, sizeof(bufout), "%s %s", ctx->readonly ? "EXAMINE" : "SELECT", buf); idata->state = IMAP_SELECTED; imap_cmd_start(idata, bufout); status = imap_mboxcache_get(idata, idata->mailbox, 1); do { char *pc = NULL; rc = imap_cmd_step(idata); if (rc != IMAP_CMD_CONTINUE) break; pc = idata->buf + 2; /* Obtain list of available flags here, may be overridden by a * PERMANENTFLAGS tag in the OK response */ if (mutt_str_strncasecmp("FLAGS", pc, 5) == 0) { /* don't override PERMANENTFLAGS */ if (STAILQ_EMPTY(&idata->flags)) { mutt_debug(3, "Getting mailbox FLAGS\n"); pc = get_flags(&idata->flags, pc); if (!pc) goto fail; } } /* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */ else if (mutt_str_strncasecmp("OK [PERMANENTFLAGS", pc, 18) == 0) { mutt_debug(3, "Getting mailbox PERMANENTFLAGS\n"); /* safe to call on NULL */ mutt_list_free(&idata->flags); /* skip "OK [PERMANENT" so syntax is the same as FLAGS */ pc += 13; pc = get_flags(&(idata->flags), pc); if (!pc) goto fail; } /* save UIDVALIDITY for the header cache */ else if (mutt_str_strncasecmp("OK [UIDVALIDITY", pc, 14) == 0) { mutt_debug(3, "Getting mailbox UIDVALIDITY\n"); pc += 3; pc = imap_next_word(pc); if (mutt_str_atoui(pc, &idata->uid_validity) < 0) goto fail; status->uidvalidity = idata->uid_validity; } else if (mutt_str_strncasecmp("OK [UIDNEXT", pc, 11) == 0) { mutt_debug(3, "Getting mailbox UIDNEXT\n"); pc += 3; pc = imap_next_word(pc); if (mutt_str_atoui(pc, &idata->uidnext) < 0) goto fail; status->uidnext = idata->uidnext; } else { pc = imap_next_word(pc); if (mutt_str_strncasecmp("EXISTS", pc, 6) == 0) { count = idata->new_mail_count; idata->new_mail_count = 0; } } } while (rc == IMAP_CMD_CONTINUE); if (rc == IMAP_CMD_NO) { char *s = imap_next_word(idata->buf); /* skip seq */ s = imap_next_word(s); /* Skip response */ mutt_error("%s", s); goto fail; } if (rc != IMAP_CMD_OK) goto fail; /* check for READ-ONLY notification */ if ((mutt_str_strncasecmp(imap_get_qualifier(idata->buf), "[READ-ONLY]", 11) == 0) && !mutt_bit_isset(idata->capabilities, ACL)) { mutt_debug(2, "Mailbox is read-only.\n"); ctx->readonly = true; } /* dump the mailbox flags we've found */ if (DebugLevel > 2) { if (STAILQ_EMPTY(&idata->flags)) mutt_debug(3, "No folder flags found\n"); else { struct ListNode *np; struct Buffer flag_buffer; mutt_buffer_init(&flag_buffer); mutt_buffer_printf(&flag_buffer, "Mailbox flags: "); STAILQ_FOREACH(np, &idata->flags, entries) { mutt_buffer_printf(&flag_buffer, "[%s] ", np->data); } mutt_debug(3, "%s\n", flag_buffer.data); FREE(&flag_buffer.data); } } if (!(mutt_bit_isset(idata->ctx->rights, MUTT_ACL_DELETE) || mutt_bit_isset(idata->ctx->rights, MUTT_ACL_SEEN) || mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE) || mutt_bit_isset(idata->ctx->rights, MUTT_ACL_INSERT))) { ctx->readonly = true; } ctx->hdrmax = count; ctx->hdrs = mutt_mem_calloc(count, sizeof(struct Header *)); ctx->v2r = mutt_mem_calloc(count, sizeof(int)); ctx->msgcount = 0; if (count && (imap_read_headers(idata, 1, count) < 0)) { mutt_error(_("Error opening mailbox")); goto fail; } mutt_debug(2, "msgcount is %d\n", ctx->msgcount); FREE(&mx.mbox); return 0; fail: if (idata->state == IMAP_SELECTED) idata->state = IMAP_AUTHENTICATED; fail_noidata: FREE(&mx.mbox); return -1; } /** * imap_mbox_open_append - Implements MxOps::mbox_open_append() */ static int imap_mbox_open_append(struct Context *ctx, int flags) { struct ImapData *idata = NULL; char mailbox[PATH_MAX]; struct ImapMbox mx; int rc; if (imap_parse_path(ctx->path, &mx)) return -1; /* in APPEND mode, we appear to hijack an existing IMAP connection - * ctx is brand new and mostly empty */ idata = imap_conn_find(&(mx.account), 0); if (!idata) { FREE(&mx.mbox); return -1; } ctx->data = idata; imap_fix_path(idata, mx.mbox, mailbox, sizeof(mailbox)); if (!*mailbox) mutt_str_strfcpy(mailbox, "INBOX", sizeof(mailbox)); FREE(&mx.mbox); rc = imap_access(ctx->path); if (rc == 0) return 0; if (rc == -1) return -1; char buf[PATH_MAX + 64]; snprintf(buf, sizeof(buf), _("Create %s?"), mailbox); if (Confirmcreate && mutt_yesorno(buf, 1) != MUTT_YES) return -1; if (imap_create_mailbox(idata, mailbox) < 0) return -1; return 0; } /** * imap_mbox_close - Implements MxOps::mbox_close() * @retval 0 Always */ static int imap_mbox_close(struct Context *ctx) { struct ImapData *idata = ctx->data; /* Check to see if the mailbox is actually open */ if (!idata) return 0; /* imap_mbox_open_append() borrows the struct ImapData temporarily, * just for the connection, but does not set idata->ctx to the * open-append ctx. * * So when these are equal, it means we are actually closing the * mailbox and should clean up idata. Otherwise, we don't want to * touch idata - it's still being used. */ if (ctx == idata->ctx) { if (idata->status != IMAP_FATAL && idata->state >= IMAP_SELECTED) { /* mx_mbox_close won't sync if there are no deleted messages * and the mailbox is unchanged, so we may have to close here */ if (!ctx->deleted) imap_exec(idata, "CLOSE", IMAP_CMD_QUEUE); idata->state = IMAP_AUTHENTICATED; } idata->reopen &= IMAP_REOPEN_ALLOW; FREE(&(idata->mailbox)); mutt_list_free(&idata->flags); idata->ctx = NULL; mutt_hash_destroy(&idata->uid_hash); FREE(&idata->msn_index); idata->msn_index_size = 0; idata->max_msn = 0; for (int i = 0; i < IMAP_CACHE_LEN; i++) { if (idata->cache[i].path) { unlink(idata->cache[i].path); FREE(&idata->cache[i].path); } } mutt_bcache_close(&idata->bcache); } /* free IMAP part of headers */ for (int i = 0; i < ctx->msgcount; i++) { /* mailbox may not have fully loaded */ if (ctx->hdrs[i] && ctx->hdrs[i]->data) imap_free_header_data((struct ImapHeaderData **) &(ctx->hdrs[i]->data)); } return 0; } /** * imap_msg_open_new - Implements MxOps::msg_open_new() */ static int imap_msg_open_new(struct Context *ctx, struct Message *msg, struct Header *hdr) { char tmp[PATH_MAX]; mutt_mktemp(tmp, sizeof(tmp)); msg->fp = mutt_file_fopen(tmp, "w"); if (!msg->fp) { mutt_perror(tmp); return -1; } msg->path = mutt_str_strdup(tmp); return 0; } /** * imap_mbox_check - Implements MxOps::mbox_check() * @param ctx Context * @param index_hint Remember our place in the index * @retval >0 Success, e.g. #MUTT_REOPENED * @retval -1 Failure */ static int imap_mbox_check(struct Context *ctx, int *index_hint) { int rc; (void) index_hint; imap_allow_reopen(ctx); rc = imap_check(ctx->data, 0); imap_disallow_reopen(ctx); return rc; } /** * imap_sync_mailbox - Sync all the changes to the server * @param ctx Context * @param expunge 0 or 1 - do expunge? * @retval 0 Success * @retval -1 Error */ int imap_sync_mailbox(struct Context *ctx, int expunge) { struct Context *appendctx = NULL; struct Header *h = NULL; struct Header **hdrs = NULL; int oldsort; int rc; struct ImapData *idata = ctx->data; if (idata->state < IMAP_SELECTED) { mutt_debug(2, "no mailbox selected\n"); return -1; } /* This function is only called when the calling code expects the context * to be changed. */ imap_allow_reopen(ctx); rc = imap_check(idata, 0); if (rc != 0) return rc; /* if we are expunging anyway, we can do deleted messages very quickly... */ if (expunge && mutt_bit_isset(ctx->rights, MUTT_ACL_DELETE)) { rc = imap_exec_msgset(idata, "UID STORE", "+FLAGS.SILENT (\\Deleted)", MUTT_DELETED, 1, 0); if (rc < 0) { mutt_error(_("Expunge failed")); goto out; } if (rc > 0) { /* mark these messages as unchanged so second pass ignores them. Done * here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */ for (int i = 0; i < ctx->msgcount; i++) if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->changed) ctx->hdrs[i]->active = false; mutt_message(ngettext("Marking %d message deleted...", "Marking %d messages deleted...", rc), rc); } } #ifdef USE_HCACHE idata->hcache = imap_hcache_open(idata, NULL); #endif /* save messages with real (non-flag) changes */ for (int i = 0; i < ctx->msgcount; i++) { h = ctx->hdrs[i]; if (h->deleted) { imap_cache_del(idata, h); #ifdef USE_HCACHE imap_hcache_del(idata, HEADER_DATA(h)->uid); #endif } if (h->active && h->changed) { #ifdef USE_HCACHE imap_hcache_put(idata, h); #endif /* if the message has been rethreaded or attachments have been deleted * we delete the message and reupload it. * This works better if we're expunging, of course. */ if ((h->env && (h->env->refs_changed || h->env->irt_changed)) || h->attach_del || h->xlabel_changed) { /* L10N: The plural is choosen by the last %d, i.e. the total number */ mutt_message(ngettext("Saving changed message... [%d/%d]", "Saving changed messages... [%d/%d]", ctx->msgcount), i + 1, ctx->msgcount); if (!appendctx) appendctx = mx_mbox_open(ctx->path, MUTT_APPEND | MUTT_QUIET, NULL); if (!appendctx) mutt_debug(1, "Error opening mailbox in append mode\n"); else mutt_save_message_ctx(h, 1, 0, 0, appendctx); h->xlabel_changed = false; } } } #ifdef USE_HCACHE imap_hcache_close(idata); #endif /* presort here to avoid doing 10 resorts in imap_exec_msgset */ oldsort = Sort; if (Sort != SORT_ORDER) { hdrs = ctx->hdrs; ctx->hdrs = mutt_mem_malloc(ctx->msgcount * sizeof(struct Header *)); memcpy(ctx->hdrs, hdrs, ctx->msgcount * sizeof(struct Header *)); Sort = SORT_ORDER; qsort(ctx->hdrs, ctx->msgcount, sizeof(struct Header *), mutt_get_sort_func(SORT_ORDER)); } rc = sync_helper(idata, MUTT_ACL_DELETE, MUTT_DELETED, "\\Deleted"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_WRITE, MUTT_FLAG, "\\Flagged"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_WRITE, MUTT_OLD, "Old"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_SEEN, MUTT_READ, "\\Seen"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_WRITE, MUTT_REPLIED, "\\Answered"); if (oldsort != Sort) { Sort = oldsort; FREE(&ctx->hdrs); ctx->hdrs = hdrs; } /* Flush the queued flags if any were changed in sync_helper. */ if (rc > 0) if (imap_exec(idata, NULL, 0) != IMAP_CMD_OK) rc = -1; if (rc < 0) { if (ctx->closing) { if (mutt_yesorno(_("Error saving flags. Close anyway?"), 0) == MUTT_YES) { rc = 0; idata->state = IMAP_AUTHENTICATED; goto out; } } else mutt_error(_("Error saving flags")); rc = -1; goto out; } /* Update local record of server state to reflect the synchronization just * completed. imap_read_headers always overwrites hcache-origin flags, so * there is no need to mutate the hcache after flag-only changes. */ for (int i = 0; i < ctx->msgcount; i++) { HEADER_DATA(ctx->hdrs[i])->deleted = ctx->hdrs[i]->deleted; HEADER_DATA(ctx->hdrs[i])->flagged = ctx->hdrs[i]->flagged; HEADER_DATA(ctx->hdrs[i])->old = ctx->hdrs[i]->old; HEADER_DATA(ctx->hdrs[i])->read = ctx->hdrs[i]->read; HEADER_DATA(ctx->hdrs[i])->replied = ctx->hdrs[i]->replied; ctx->hdrs[i]->changed = false; } ctx->changed = false; /* We must send an EXPUNGE command if we're not closing. */ if (expunge && !(ctx->closing) && mutt_bit_isset(ctx->rights, MUTT_ACL_DELETE)) { mutt_message(_("Expunging messages from server...")); /* Set expunge bit so we don't get spurious reopened messages */ idata->reopen |= IMAP_EXPUNGE_EXPECTED; if (imap_exec(idata, "EXPUNGE", 0) != 0) { idata->reopen &= ~IMAP_EXPUNGE_EXPECTED; imap_error(_("imap_sync_mailbox: EXPUNGE failed"), idata->buf); rc = -1; goto out; } idata->reopen &= ~IMAP_EXPUNGE_EXPECTED; } if (expunge && ctx->closing) { imap_exec(idata, "CLOSE", IMAP_CMD_QUEUE); idata->state = IMAP_AUTHENTICATED; } if (MessageCacheClean) imap_cache_clean(idata); rc = 0; out: if (appendctx) { mx_fastclose_mailbox(appendctx); FREE(&appendctx); } return rc; } /** * imap_tags_edit - Implements MxOps::tags_edit() */ static int imap_tags_edit(struct Context *ctx, const char *tags, char *buf, size_t buflen) { char *new = NULL; char *checker = NULL; struct ImapData *idata = (struct ImapData *) ctx->data; /* Check for \* flags capability */ if (!imap_has_flag(&idata->flags, NULL)) { mutt_error(_("IMAP server doesn't support custom flags")); return -1; } *buf = '\0'; if (tags) strncpy(buf, tags, buflen); if (mutt_get_field("Tags: ", buf, buflen, 0) != 0) return -1; /* each keyword must be atom defined by rfc822 as: * * atom = 1*<any CHAR except specials, SPACE and CTLs> * CHAR = ( 0.-127. ) * specials = "(" / ")" / "<" / ">" / "@" * / "," / ";" / ":" / "\" / <"> * / "." / "[" / "]" * SPACE = ( 32. ) * CTLS = ( 0.-31., 127.) * * And must be separated by one space. */ new = buf; checker = buf; SKIPWS(checker); while (*checker != '\0') { if (*checker < 32 || *checker >= 127 || // We allow space because it's the separator *checker == 40 || // ( *checker == 41 || // ) *checker == 60 || // < *checker == 62 || // > *checker == 64 || // @ *checker == 44 || // , *checker == 59 || // ; *checker == 58 || // : *checker == 92 || // backslash *checker == 34 || // " *checker == 46 || // . *checker == 91 || // [ *checker == 93) // ] { mutt_error(_("Invalid IMAP flags")); return 0; } /* Skip duplicate space */ while (*checker == ' ' && *(checker + 1) == ' ') checker++; /* copy char to new and go the next one */ *new ++ = *checker++; } *new = '\0'; new = buf; /* rewind */ mutt_str_remove_trailing_ws(new); if (mutt_str_strcmp(tags, buf) == 0) return 0; return 1; } /** * imap_tags_commit - Implements MxOps::tags_commit() * * This method update the server flags on the server by * removing the last know custom flags of a header * and adds the local flags * * If everything success we push the local flags to the * last know custom flags (flags_remote). * * Also this method check that each flags is support by the server * first and remove unsupported one. */ static int imap_tags_commit(struct Context *ctx, struct Header *hdr, char *buf) { struct Buffer *cmd = NULL; char uid[11]; struct ImapData *idata = ctx->data; if (*buf == '\0') buf = NULL; if (!mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE)) return 0; snprintf(uid, sizeof(uid), "%u", HEADER_DATA(hdr)->uid); /* Remove old custom flags */ if (HEADER_DATA(hdr)->flags_remote) { cmd = mutt_buffer_new(); if (!cmd) { mutt_debug(1, "unable to allocate buffer\n"); return -1; } cmd->dptr = cmd->data; mutt_buffer_addstr(cmd, "UID STORE "); mutt_buffer_addstr(cmd, uid); mutt_buffer_addstr(cmd, " -FLAGS.SILENT ("); mutt_buffer_addstr(cmd, HEADER_DATA(hdr)->flags_remote); mutt_buffer_addstr(cmd, ")"); /* Should we return here, or we are fine and we could * continue to add new flags * */ if (imap_exec(idata, cmd->data, 0) != 0) { mutt_buffer_free(&cmd); return -1; } mutt_buffer_free(&cmd); } /* Add new custom flags */ if (buf) { cmd = mutt_buffer_new(); if (!cmd) { mutt_debug(1, "fail to remove old flags\n"); return -1; } cmd->dptr = cmd->data; mutt_buffer_addstr(cmd, "UID STORE "); mutt_buffer_addstr(cmd, uid); mutt_buffer_addstr(cmd, " +FLAGS.SILENT ("); mutt_buffer_addstr(cmd, buf); mutt_buffer_addstr(cmd, ")"); if (imap_exec(idata, cmd->data, 0) != 0) { mutt_debug(1, "fail to add new flags\n"); mutt_buffer_free(&cmd); return -1; } mutt_buffer_free(&cmd); } /* We are good sync them */ mutt_debug(1, "NEW TAGS: %d\n", buf); driver_tags_replace(&hdr->tags, buf); FREE(&HEADER_DATA(hdr)->flags_remote); HEADER_DATA(hdr)->flags_remote = driver_tags_get_with_hidden(&hdr->tags); return 0; } // clang-format off /** * struct mx_imap_ops - Mailbox callback functions for IMAP mailboxes */ struct MxOps mx_imap_ops = { .mbox_open = imap_mbox_open, .mbox_open_append = imap_mbox_open_append, .mbox_check = imap_mbox_check, .mbox_sync = NULL, /* imap syncing is handled by imap_sync_mailbox */ .mbox_close = imap_mbox_close, .msg_open = imap_msg_open, .msg_open_new = imap_msg_open_new, .msg_commit = imap_msg_commit, .msg_close = imap_msg_close, .tags_edit = imap_tags_edit, .tags_commit = imap_tags_commit, }; // clang-format on
./CrossVul/dataset_final_sorted/CWE-77/c/bad_248_0
crossvul-cpp_data_good_2351_3
/* * blkid.c - User command-line interface for libblkid * * Copyright (C) 2001 Andreas Dilger * * %Begin-Header% * This file may be redistributed under the terms of the * GNU Lesser General Public License. * %End-Header% */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #ifdef HAVE_GETOPT_H #include <getopt.h> #else extern int getopt(int argc, char * const argv[], const char *optstring); extern char *optarg; extern int optind; #endif #define OUTPUT_VALUE_ONLY (1 << 1) #define OUTPUT_DEVICE_ONLY (1 << 2) #define OUTPUT_PRETTY_LIST (1 << 3) /* deprecated */ #define OUTPUT_UDEV_LIST (1 << 4) /* deprecated */ #define OUTPUT_EXPORT_LIST (1 << 5) #define LOWPROBE_TOPOLOGY (1 << 1) #define LOWPROBE_SUPERBLOCKS (1 << 2) #define BLKID_EXIT_NOTFOUND 2 /* token or device not found */ #define BLKID_EXIT_OTHER 4 /* bad usage or other error */ #define BLKID_EXIT_AMBIVAL 8 /* ambivalent low-level probing detected */ #include <blkid.h> #include "ismounted.h" #define STRTOXX_EXIT_CODE BLKID_EXIT_OTHER /* strtoxx_or_err() */ #include "strutils.h" #define OPTUTILS_EXIT_CODE BLKID_EXIT_OTHER /* exclusive_option() */ #include "optutils.h" #include "closestream.h" #include "ttyutils.h" #include "xalloc.h" int raw_chars; static void print_version(FILE *out) { fprintf(out, "%s from %s (libblkid %s, %s)\n", program_invocation_short_name, PACKAGE_STRING, LIBBLKID_VERSION, LIBBLKID_DATE); } static void usage(int error) { FILE *out = error ? stderr : stdout; print_version(out); fprintf(out, "Usage:\n" " %1$s -L <label> | -U <uuid>\n\n" " %1$s [-c <file>] [-ghlLv] [-o <format>] [-s <tag>] \n" " [-t <token>] [<dev> ...]\n\n" " %1$s -p [-s <tag>] [-O <offset>] [-S <size>] \n" " [-o <format>] <dev> ...\n\n" " %1$s -i [-s <tag>] [-o <format>] <dev> ...\n\n" "Options:\n" " -c <file> read from <file> instead of reading from the default\n" " cache file (-c /dev/null means no cache)\n" " -d don't encode non-printing characters\n" " -h print this usage message and exit\n" " -g garbage collect the blkid cache\n" " -o <format> output format; can be one of:\n" " value, device, export or full; (default: full)\n" " -k list all known filesystems/RAIDs and exit\n" " -s <tag> show specified tag(s) (default show all tags)\n" " -t <token> find device with a specific token (NAME=value pair)\n" " -l look up only first device with token specified by -t\n" " -L <label> convert LABEL to device name\n" " -U <uuid> convert UUID to device name\n" " -V print version and exit\n" " <dev> specify device(s) to probe (default: all devices)\n\n" "Low-level probing options:\n" " -p low-level superblocks probing (bypass cache)\n" " -i gather information about I/O limits\n" " -S <size> overwrite device size\n" " -O <offset> probe at the given offset\n" " -u <list> filter by \"usage\" (e.g. -u filesystem,raid)\n" " -n <list> filter by filesystem type (e.g. -n vfat,ext3)\n" "\n", program_invocation_short_name); exit(error); } /* * This function does "safe" printing. It will convert non-printable * ASCII characters using '^' and M- notation. * * If 'esc' is defined then escape all chars from esc by \. */ static void safe_print(const char *cp, int len, const char *esc) { unsigned char ch; if (len < 0) len = strlen(cp); while (len--) { ch = *cp++; if (!raw_chars) { if (ch >= 128) { fputs("M-", stdout); ch -= 128; } if ((ch < 32) || (ch == 0x7f)) { fputc('^', stdout); ch ^= 0x40; /* ^@, ^A, ^B; ^? for DEL */ } else if (esc && strchr(esc, ch)) fputc('\\', stdout); } fputc(ch, stdout); } } static int pretty_print_word(const char *str, int max_len, int left_len, int overflow_nl) { int len = strlen(str) + left_len; int ret = 0; fputs(str, stdout); if (overflow_nl && len > max_len) { fputc('\n', stdout); len = 0; } else if (len > max_len) ret = len - max_len; do fputc(' ', stdout); while (len++ < max_len); return ret; } static void pretty_print_line(const char *device, const char *fs_type, const char *label, const char *mtpt, const char *uuid) { static int device_len = 10, fs_type_len = 7; static int label_len = 8, mtpt_len = 14; static int term_width = -1; int len, w; if (term_width < 0) { term_width = get_terminal_width(); if (term_width <= 0) term_width = 80; } if (term_width > 80) { term_width -= 80; w = term_width / 10; if (w > 8) w = 8; term_width -= 2*w; label_len += w; fs_type_len += w; w = term_width/2; device_len += w; mtpt_len +=w; } len = pretty_print_word(device, device_len, 0, 1); len = pretty_print_word(fs_type, fs_type_len, len, 0); len = pretty_print_word(label, label_len, len, 0); pretty_print_word(mtpt, mtpt_len, len, 0); fputs(uuid, stdout); fputc('\n', stdout); } static void pretty_print_dev(blkid_dev dev) { blkid_tag_iterate iter; const char *type, *value, *devname; const char *uuid = "", *fs_type = "", *label = ""; int len, mount_flags; char mtpt[80]; int retval; if (dev == NULL) { pretty_print_line("device", "fs_type", "label", "mount point", "UUID"); for (len=get_terminal_width()-1; len > 0; len--) fputc('-', stdout); fputc('\n', stdout); return; } devname = blkid_dev_devname(dev); if (access(devname, F_OK)) return; /* Get the uuid, label, type */ iter = blkid_tag_iterate_begin(dev); while (blkid_tag_next(iter, &type, &value) == 0) { if (!strcmp(type, "UUID")) uuid = value; if (!strcmp(type, "TYPE")) fs_type = value; if (!strcmp(type, "LABEL")) label = value; } blkid_tag_iterate_end(iter); /* Get the mount point */ mtpt[0] = 0; retval = check_mount_point(devname, &mount_flags, mtpt, sizeof(mtpt)); if (retval == 0) { if (mount_flags & MF_MOUNTED) { if (!mtpt[0]) strcpy(mtpt, "(mounted, mtpt unknown)"); } else if (mount_flags & MF_BUSY) strcpy(mtpt, "(in use)"); else strcpy(mtpt, "(not mounted)"); } pretty_print_line(devname, fs_type, label, mtpt, uuid); } static void print_udev_format(const char *name, const char *value) { char enc[265], safe[256]; size_t namelen = strlen(name); *safe = *enc = '\0'; if (!strcmp(name, "TYPE") || !strcmp(name, "VERSION")) { blkid_encode_string(value, enc, sizeof(enc)); printf("ID_FS_%s=%s\n", name, enc); } else if (!strcmp(name, "UUID") || !strcmp(name, "LABEL") || !strcmp(name, "UUID_SUB")) { blkid_safe_string(value, safe, sizeof(safe)); printf("ID_FS_%s=%s\n", name, safe); blkid_encode_string(value, enc, sizeof(enc)); printf("ID_FS_%s_ENC=%s\n", name, enc); } else if (!strcmp(name, "PTUUID")) { printf("ID_PART_TABLE_UUID=%s\n", value); } else if (!strcmp(name, "PTTYPE")) { printf("ID_PART_TABLE_TYPE=%s\n", value); } else if (!strcmp(name, "PART_ENTRY_NAME") || !strcmp(name, "PART_ENTRY_TYPE")) { blkid_encode_string(value, enc, sizeof(enc)); printf("ID_%s=%s\n", name, enc); } else if (!strncmp(name, "PART_ENTRY_", 11)) printf("ID_%s=%s\n", name, value); else if (namelen >= 15 && ( !strcmp(name + (namelen - 12), "_SECTOR_SIZE") || !strcmp(name + (namelen - 8), "_IO_SIZE") || !strcmp(name, "ALIGNMENT_OFFSET"))) printf("ID_IOLIMIT_%s=%s\n", name, value); else printf("ID_FS_%s=%s\n", name, value); } static int has_item(char *ary[], const char *item) { char **p; for (p = ary; *p != NULL; p++) if (!strcmp(item, *p)) return 1; return 0; } static void print_value(int output, int num, const char *devname, const char *value, const char *name, size_t valsz) { if (output & OUTPUT_VALUE_ONLY) { fputs(value, stdout); fputc('\n', stdout); } else if (output & OUTPUT_UDEV_LIST) { print_udev_format(name, value); } else if (output & OUTPUT_EXPORT_LIST) { if (num == 1 && devname) printf("DEVNAME=%s\n", devname); fputs(name, stdout); fputs("=", stdout); safe_print(value, valsz, " \\\"'$`<>"); fputs("\n", stdout); } else { if (num == 1 && devname) printf("%s:", devname); fputs(" ", stdout); fputs(name, stdout); fputs("=\"", stdout); safe_print(value, valsz, "\"\\"); fputs("\"", stdout); } } static void print_tags(blkid_dev dev, char *show[], int output) { blkid_tag_iterate iter; const char *type, *value, *devname; int num = 1; static int first = 1; if (!dev) return; if (output & OUTPUT_PRETTY_LIST) { pretty_print_dev(dev); return; } devname = blkid_dev_devname(dev); if (output & OUTPUT_DEVICE_ONLY) { printf("%s\n", devname); return; } iter = blkid_tag_iterate_begin(dev); while (blkid_tag_next(iter, &type, &value) == 0) { if (show[0] && !has_item(show, type)) continue; if (num == 1 && !first && (output & (OUTPUT_UDEV_LIST | OUTPUT_EXPORT_LIST))) /* add extra line between output from more devices */ fputc('\n', stdout); print_value(output, num++, devname, value, type, strlen(value)); } blkid_tag_iterate_end(iter); if (num > 1) { if (!(output & (OUTPUT_VALUE_ONLY | OUTPUT_UDEV_LIST | OUTPUT_EXPORT_LIST))) printf("\n"); first = 0; } } static int append_str(char **res, size_t *sz, const char *a, const char *b) { char *str = *res; size_t asz = a ? strlen(a) : 0; size_t bsz = b ? strlen(b) : 0; size_t len = *sz + asz + bsz; if (!len) return -1; *res = str = xrealloc(str, len + 1); str += *sz; if (a) { memcpy(str, a, asz); str += asz; } if (b) { memcpy(str, b, bsz); str += bsz; } *str = '\0'; *sz = len; return 0; } /* * Compose and print ID_FS_AMBIVALENT for udev */ static int print_udev_ambivalent(blkid_probe pr) { char *val = NULL; size_t valsz = 0; int count = 0, rc = -1; while (!blkid_do_probe(pr)) { const char *usage_txt = NULL, *type = NULL, *version = NULL; char enc[256]; blkid_probe_lookup_value(pr, "USAGE", &usage_txt, NULL); blkid_probe_lookup_value(pr, "TYPE", &type, NULL); blkid_probe_lookup_value(pr, "VERSION", &version, NULL); if (!usage_txt || !type) continue; blkid_encode_string(usage_txt, enc, sizeof(enc)); if (append_str(&val, &valsz, enc, ":")) goto done; blkid_encode_string(type, enc, sizeof(enc)); if (append_str(&val, &valsz, enc, version ? ":" : " ")) goto done; if (version) { blkid_encode_string(version, enc, sizeof(enc)); if (append_str(&val, &valsz, enc, " ")) goto done; } count++; } if (count > 1) { *(val + valsz - 1) = '\0'; /* rem tailing whitespace */ printf("ID_FS_AMBIVALENT=%s\n", val); rc = 0; } done: free(val); return rc; } static int lowprobe_superblocks(blkid_probe pr) { struct stat st; int rc, fd = blkid_probe_get_fd(pr); if (fd < 0 || fstat(fd, &st)) return -1; blkid_probe_enable_partitions(pr, 1); if (!S_ISCHR(st.st_mode) && blkid_probe_get_size(pr) <= 1024 * 1440 && blkid_probe_is_wholedisk(pr)) { /* * check if the small disk is partitioned, if yes then * don't probe for filesystems. */ blkid_probe_enable_superblocks(pr, 0); rc = blkid_do_fullprobe(pr); if (rc < 0) return rc; /* -1 = error, 1 = nothing, 0 = succes */ if (blkid_probe_lookup_value(pr, "PTTYPE", NULL, NULL) == 0) return 0; /* partition table detected */ } blkid_probe_set_partitions_flags(pr, BLKID_PARTS_ENTRY_DETAILS); blkid_probe_enable_superblocks(pr, 1); return blkid_do_safeprobe(pr); } static int lowprobe_topology(blkid_probe pr) { /* enable topology probing only */ blkid_probe_enable_topology(pr, 1); blkid_probe_enable_superblocks(pr, 0); blkid_probe_enable_partitions(pr, 0); return blkid_do_fullprobe(pr); } static int lowprobe_device(blkid_probe pr, const char *devname, int chain, char *show[], int output, blkid_loff_t offset, blkid_loff_t size) { const char *data; const char *name; int nvals = 0, n, num = 1; size_t len; int fd; int rc = 0; static int first = 1; fd = open(devname, O_RDONLY|O_CLOEXEC); if (fd < 0) { fprintf(stderr, "error: %s: %m\n", devname); return BLKID_EXIT_NOTFOUND; } if (blkid_probe_set_device(pr, fd, offset, size)) goto done; if (chain & LOWPROBE_TOPOLOGY) rc = lowprobe_topology(pr); if (rc >= 0 && (chain & LOWPROBE_SUPERBLOCKS)) rc = lowprobe_superblocks(pr); if (rc < 0) goto done; if (!rc) nvals = blkid_probe_numof_values(pr); if (nvals && !(chain & LOWPROBE_TOPOLOGY) && !(output & OUTPUT_UDEV_LIST) && !blkid_probe_has_value(pr, "TYPE") && !blkid_probe_has_value(pr, "PTTYPE")) /* * Ignore probing result if there is not any filesystem or * partition table on the device and udev output is not * requested. * * The udev db stores information about partitions, so * PART_ENTRY_* values are alway important. */ nvals = 0; if (nvals && !first && output & (OUTPUT_UDEV_LIST | OUTPUT_EXPORT_LIST)) /* add extra line between output from devices */ fputc('\n', stdout); if (nvals && (output & OUTPUT_DEVICE_ONLY)) { printf("%s\n", devname); goto done; } for (n = 0; n < nvals; n++) { if (blkid_probe_get_value(pr, n, &name, &data, &len)) continue; if (show[0] && !has_item(show, name)) continue; len = strnlen((char *) data, len); print_value(output, num++, devname, (char *) data, name, len); } if (first) first = 0; if (nvals >= 1 && !(output & (OUTPUT_VALUE_ONLY | OUTPUT_UDEV_LIST | OUTPUT_EXPORT_LIST))) printf("\n"); done: if (rc == -2) { if (output & OUTPUT_UDEV_LIST) print_udev_ambivalent(pr); else fprintf(stderr, "%s: ambivalent result (probably more " "filesystems on the device, use wipefs(8) " "to see more details)\n", devname); } close(fd); if (rc == -2) return BLKID_EXIT_AMBIVAL; /* ambivalent probing result */ if (!nvals) return BLKID_EXIT_NOTFOUND; /* nothing detected */ return 0; /* success */ } /* converts comma separated list to BLKID_USAGE_* mask */ static int list_to_usage(const char *list, int *flag) { int mask = 0; const char *word = NULL, *p = list; if (p && strncmp(p, "no", 2) == 0) { *flag = BLKID_FLTR_NOTIN; p += 2; } if (!p || !*p) goto err; while(p) { word = p; p = strchr(p, ','); if (p) p++; if (!strncmp(word, "filesystem", 10)) mask |= BLKID_USAGE_FILESYSTEM; else if (!strncmp(word, "raid", 4)) mask |= BLKID_USAGE_RAID; else if (!strncmp(word, "crypto", 6)) mask |= BLKID_USAGE_CRYPTO; else if (!strncmp(word, "other", 5)) mask |= BLKID_USAGE_OTHER; else goto err; } return mask; err: *flag = 0; fprintf(stderr, "unknown keyword in -u <list> argument: '%s'\n", word ? word : list); exit(BLKID_EXIT_OTHER); } /* converts comma separated list to types[] */ static char **list_to_types(const char *list, int *flag) { int i; const char *p = list; char **res = NULL; if (p && strncmp(p, "no", 2) == 0) { *flag = BLKID_FLTR_NOTIN; p += 2; } if (!p || !*p) { fprintf(stderr, "error: -u <list> argument is empty\n"); goto err; } for (i = 1; p && (p = strchr(p, ',')); i++, p++); res = xcalloc(i + 1, sizeof(char *)); p = *flag & BLKID_FLTR_NOTIN ? list + 2 : list; i = 0; while(p) { const char *word = p; p = strchr(p, ','); res[i++] = p ? xstrndup(word, p - word) : xstrdup(word); if (p) p++; } res[i] = NULL; return res; err: *flag = 0; free(res); exit(BLKID_EXIT_OTHER); } static void free_types_list(char *list[]) { char **n; if (!list) return; for (n = list; *n; n++) free(*n); free(list); } int main(int argc, char **argv) { blkid_cache cache = NULL; char **devices = NULL; char *show[128] = { NULL, }; char *search_type = NULL, *search_value = NULL; char *read = NULL; int fltr_usage = 0; char **fltr_type = NULL; int fltr_flag = BLKID_FLTR_ONLYIN; unsigned int numdev = 0, numtag = 0; int version = 0; int err = BLKID_EXIT_OTHER; unsigned int i; int output_format = 0; int lookup = 0, gc = 0, lowprobe = 0, eval = 0; int c; uintmax_t offset = 0, size = 0; static const ul_excl_t excl[] = { /* rows and cols in in ASCII order */ { 'n','u' }, { 0 } }; int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT; show[0] = NULL; atexit(close_stdout); while ((c = getopt (argc, argv, "c:df:ghilL:n:ko:O:ps:S:t:u:U:w:Vv")) != EOF) { err_exclusive_options(c, NULL, excl, excl_st); switch (c) { case 'c': if (optarg && !*optarg) read = NULL; else read = optarg; break; case 'd': raw_chars = 1; break; case 'L': eval++; search_value = xstrdup(optarg); search_type = xstrdup("LABEL"); break; case 'n': fltr_type = list_to_types(optarg, &fltr_flag); break; case 'u': fltr_usage = list_to_usage(optarg, &fltr_flag); break; case 'U': eval++; search_value = xstrdup(optarg); search_type = xstrdup("UUID"); break; case 'i': lowprobe |= LOWPROBE_TOPOLOGY; break; case 'l': lookup++; break; case 'g': gc = 1; break; case 'k': { size_t idx = 0; const char *name = NULL; while (blkid_superblocks_get_name(idx++, &name, NULL) == 0) printf("%s\n", name); exit(EXIT_SUCCESS); } case 'o': if (!strcmp(optarg, "value")) output_format = OUTPUT_VALUE_ONLY; else if (!strcmp(optarg, "device")) output_format = OUTPUT_DEVICE_ONLY; else if (!strcmp(optarg, "list")) output_format = OUTPUT_PRETTY_LIST; /* deprecated */ else if (!strcmp(optarg, "udev")) output_format = OUTPUT_UDEV_LIST; else if (!strcmp(optarg, "export")) output_format = OUTPUT_EXPORT_LIST; else if (!strcmp(optarg, "full")) output_format = 0; else { fprintf(stderr, "Invalid output format %s. " "Choose from value,\n\t" "device, list, udev or full\n", optarg); exit(BLKID_EXIT_OTHER); } break; case 'O': offset = strtosize_or_err(optarg, "invalid offset argument"); break; case 'p': lowprobe |= LOWPROBE_SUPERBLOCKS; break; case 's': if (numtag + 1 >= sizeof(show) / sizeof(*show)) { fprintf(stderr, "Too many tags specified\n"); usage(err); } show[numtag++] = optarg; show[numtag] = NULL; break; case 'S': size = strtosize_or_err(optarg, "invalid size argument"); break; case 't': if (search_type) { fprintf(stderr, "Can only search for " "one NAME=value pair\n"); usage(err); } if (blkid_parse_tag_string(optarg, &search_type, &search_value)) { fprintf(stderr, "-t needs NAME=value pair\n"); usage(err); } break; case 'V': case 'v': version = 1; break; case 'w': /* ignore - backward compatibility */ break; case 'h': err = 0; /* fallthrough */ default: usage(err); } } /* The rest of the args are device names */ if (optind < argc) { devices = xcalloc(argc - optind, sizeof(char *)); while (optind < argc) devices[numdev++] = argv[optind++]; } if (version) { print_version(stdout); goto exit; } /* convert LABEL/UUID lookup to evaluate request */ if (lookup && output_format == OUTPUT_DEVICE_ONLY && search_type && (!strcmp(search_type, "LABEL") || !strcmp(search_type, "UUID"))) { eval++; lookup = 0; } if (!lowprobe && !eval && blkid_get_cache(&cache, read) < 0) goto exit; if (gc) { blkid_gc_cache(cache); err = 0; goto exit; } err = BLKID_EXIT_NOTFOUND; if (eval == 0 && (output_format & OUTPUT_PRETTY_LIST)) { if (lowprobe) { fprintf(stderr, "The low-level probing mode does not " "support 'list' output format\n"); exit(BLKID_EXIT_OTHER); } pretty_print_dev(NULL); } if (lowprobe) { /* * Low-level API */ blkid_probe pr; if (!numdev) { fprintf(stderr, "The low-level probing mode " "requires a device\n"); exit(BLKID_EXIT_OTHER); } /* automatically enable 'export' format for I/O Limits */ if (!output_format && (lowprobe & LOWPROBE_TOPOLOGY)) output_format = OUTPUT_EXPORT_LIST; pr = blkid_new_probe(); if (!pr) goto exit; if (lowprobe & LOWPROBE_SUPERBLOCKS) { blkid_probe_set_superblocks_flags(pr, BLKID_SUBLKS_LABEL | BLKID_SUBLKS_UUID | BLKID_SUBLKS_TYPE | BLKID_SUBLKS_SECTYPE | BLKID_SUBLKS_USAGE | BLKID_SUBLKS_VERSION); if (fltr_usage && blkid_probe_filter_superblocks_usage( pr, fltr_flag, fltr_usage)) goto exit; else if (fltr_type && blkid_probe_filter_superblocks_type( pr, fltr_flag, fltr_type)) goto exit; } for (i = 0; i < numdev; i++) { err = lowprobe_device(pr, devices[i], lowprobe, show, output_format, (blkid_loff_t) offset, (blkid_loff_t) size); if (err) break; } blkid_free_probe(pr); } else if (eval) { /* * Evaluate API */ char *res = blkid_evaluate_tag(search_type, search_value, NULL); if (res) { err = 0; printf("%s\n", res); } } else if (lookup) { /* * Classic (cache based) API */ blkid_dev dev; if (!search_type) { fprintf(stderr, "The lookup option requires a " "search type specified using -t\n"); exit(BLKID_EXIT_OTHER); } /* Load any additional devices not in the cache */ for (i = 0; i < numdev; i++) blkid_get_dev(cache, devices[i], BLKID_DEV_NORMAL); if ((dev = blkid_find_dev_with_tag(cache, search_type, search_value))) { print_tags(dev, show, output_format); err = 0; } /* If we didn't specify a single device, show all available devices */ } else if (!numdev) { blkid_dev_iterate iter; blkid_dev dev; blkid_probe_all(cache); iter = blkid_dev_iterate_begin(cache); blkid_dev_set_search(iter, search_type, search_value); while (blkid_dev_next(iter, &dev) == 0) { dev = blkid_verify(cache, dev); if (!dev) continue; print_tags(dev, show, output_format); err = 0; } blkid_dev_iterate_end(iter); /* Add all specified devices to cache (optionally display tags) */ } else for (i = 0; i < numdev; i++) { blkid_dev dev = blkid_get_dev(cache, devices[i], BLKID_DEV_NORMAL); if (dev) { if (search_type && !blkid_dev_has_tag(dev, search_type, search_value)) continue; print_tags(dev, show, output_format); err = 0; } } exit: free(search_type); free(search_value); free_types_list(fltr_type); if (!lowprobe && !eval) blkid_put_cache(cache); free(devices); return err; }
./CrossVul/dataset_final_sorted/CWE-77/c/good_2351_3
crossvul-cpp_data_bad_251_2
/** * @file * IMAP network mailbox * * @authors * Copyright (C) 1996-1998,2012 Michael R. Elkins <me@mutt.org> * Copyright (C) 1996-1999 Brandon Long <blong@fiction.net> * Copyright (C) 1999-2009,2012,2017 Brendan Cully <brendan@kublai.com> * * @copyright * 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, see <http://www.gnu.org/licenses/>. */ /** * @page imap_imap IMAP network mailbox * * Support for IMAP4rev1, with the occasional nod to IMAP 4. */ #include "config.h" #include <ctype.h> #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include "imap_private.h" #include "mutt/mutt.h" #include "conn/conn.h" #include "mutt.h" #include "imap.h" #include "auth.h" #include "bcache.h" #include "body.h" #include "buffy.h" #include "context.h" #include "envelope.h" #include "globals.h" #include "header.h" #include "mailbox.h" #include "message.h" #include "mutt_account.h" #include "mutt_curses.h" #include "mutt_logging.h" #include "mutt_socket.h" #include "mx.h" #include "options.h" #include "pattern.h" #include "progress.h" #include "protos.h" #include "sort.h" #include "tags.h" #include "url.h" #ifdef USE_HCACHE #include "hcache/hcache.h" #endif /** * check_capabilities - Make sure we can log in to this server * @param idata Server data * @retval 0 Success * @retval -1 Failure */ static int check_capabilities(struct ImapData *idata) { if (imap_exec(idata, "CAPABILITY", 0) != 0) { imap_error("check_capabilities", idata->buf); return -1; } if (!(mutt_bit_isset(idata->capabilities, IMAP4) || mutt_bit_isset(idata->capabilities, IMAP4REV1))) { mutt_error( _("This IMAP server is ancient. NeoMutt does not work with it.")); return -1; } return 0; } /** * get_flags - Make a simple list out of a FLAGS response * @param hflags List to store flags * @param s String containing flags * @retval ptr End of the flags * @retval ptr NULL Failure * * return stream following FLAGS response */ static char *get_flags(struct ListHead *hflags, char *s) { /* sanity-check string */ if (mutt_str_strncasecmp("FLAGS", s, 5) != 0) { mutt_debug(1, "not a FLAGS response: %s\n", s); return NULL; } s += 5; SKIPWS(s); if (*s != '(') { mutt_debug(1, "bogus FLAGS response: %s\n", s); return NULL; } /* update caller's flags handle */ while (*s && *s != ')') { s++; SKIPWS(s); const char *flag_word = s; while (*s && (*s != ')') && !ISSPACE(*s)) s++; const char ctmp = *s; *s = '\0'; if (*flag_word) mutt_list_insert_tail(hflags, mutt_str_strdup(flag_word)); *s = ctmp; } /* note bad flags response */ if (*s != ')') { mutt_debug(1, "Unterminated FLAGS response: %s\n", s); mutt_list_free(hflags); return NULL; } s++; return s; } /** * set_flag - append str to flags if we currently have permission according to aclbit * @param[in] idata Server data * @param[in] aclbit Permissions, e.g. #MUTT_ACL_WRITE * @param[in] flag Does the email have the flag set? * @param[in] str Server flag name * @param[out] flags Buffer for server command * @param[in] flsize Length of buffer */ static void set_flag(struct ImapData *idata, int aclbit, int flag, const char *str, char *flags, size_t flsize) { if (mutt_bit_isset(idata->ctx->rights, aclbit)) if (flag && imap_has_flag(&idata->flags, str)) mutt_str_strcat(flags, flsize, str); } /** * make_msg_set - Make a message set * @param[in] idata Server data * @param[in] buf Buffer to store message set * @param[in] flag Flags to match, e.g. #MUTT_DELETED * @param[in] changed Matched messages that have been altered * @param[in] invert Flag matches should be inverted * @param[out] pos Cursor used for multiple calls to this function * @retval num Messages in the set * * @note Headers must be in SORT_ORDER. See imap_exec_msgset() for args. * Pos is an opaque pointer a la strtok(). It should be 0 at first call. */ static int make_msg_set(struct ImapData *idata, struct Buffer *buf, int flag, bool changed, bool invert, int *pos) { int count = 0; /* number of messages in message set */ unsigned int setstart = 0; /* start of current message range */ int n; bool started = false; struct Header **hdrs = idata->ctx->hdrs; for (n = *pos; n < idata->ctx->msgcount && buf->dptr - buf->data < IMAP_MAX_CMDLEN; n++) { bool match = false; /* whether current message matches flag condition */ /* don't include pending expunged messages */ if (hdrs[n]->active) { switch (flag) { case MUTT_DELETED: if (hdrs[n]->deleted != HEADER_DATA(hdrs[n])->deleted) match = invert ^ hdrs[n]->deleted; break; case MUTT_FLAG: if (hdrs[n]->flagged != HEADER_DATA(hdrs[n])->flagged) match = invert ^ hdrs[n]->flagged; break; case MUTT_OLD: if (hdrs[n]->old != HEADER_DATA(hdrs[n])->old) match = invert ^ hdrs[n]->old; break; case MUTT_READ: if (hdrs[n]->read != HEADER_DATA(hdrs[n])->read) match = invert ^ hdrs[n]->read; break; case MUTT_REPLIED: if (hdrs[n]->replied != HEADER_DATA(hdrs[n])->replied) match = invert ^ hdrs[n]->replied; break; case MUTT_TAG: if (hdrs[n]->tagged) match = true; break; case MUTT_TRASH: if (hdrs[n]->deleted && !hdrs[n]->purge) match = true; break; } } if (match && (!changed || hdrs[n]->changed)) { count++; if (setstart == 0) { setstart = HEADER_DATA(hdrs[n])->uid; if (!started) { mutt_buffer_printf(buf, "%u", HEADER_DATA(hdrs[n])->uid); started = true; } else mutt_buffer_printf(buf, ",%u", HEADER_DATA(hdrs[n])->uid); } /* tie up if the last message also matches */ else if (n == idata->ctx->msgcount - 1) mutt_buffer_printf(buf, ":%u", HEADER_DATA(hdrs[n])->uid); } /* End current set if message doesn't match or we've reached the end * of the mailbox via inactive messages following the last match. */ else if (setstart && (hdrs[n]->active || n == idata->ctx->msgcount - 1)) { if (HEADER_DATA(hdrs[n - 1])->uid > setstart) mutt_buffer_printf(buf, ":%u", HEADER_DATA(hdrs[n - 1])->uid); setstart = 0; } } *pos = n; return count; } /** * compare_flags_for_copy - Compare local flags against the server * @param h Header of email * @retval true Flags have changed * @retval false Flags match cached server flags * * The comparison of flags EXCLUDES the deleted flag. */ static bool compare_flags_for_copy(struct Header *h) { struct ImapHeaderData *hd = (struct ImapHeaderData *) h->data; if (h->read != hd->read) return true; if (h->old != hd->old) return true; if (h->flagged != hd->flagged) return true; if (h->replied != hd->replied) return true; return false; } /** * sync_helper - Sync flag changes to the server * @param idata Server data * @param right ACL, e.g. #MUTT_ACL_DELETE * @param flag Mutt flag, e.g. MUTT_DELETED * @param name Name of server flag * @retval >=0 Success, number of messages * @retval -1 Failure */ static int sync_helper(struct ImapData *idata, int right, int flag, const char *name) { int count = 0; int rc; char buf[LONG_STRING]; if (!idata->ctx) return -1; if (!mutt_bit_isset(idata->ctx->rights, right)) return 0; if (right == MUTT_ACL_WRITE && !imap_has_flag(&idata->flags, name)) return 0; snprintf(buf, sizeof(buf), "+FLAGS.SILENT (%s)", name); rc = imap_exec_msgset(idata, "UID STORE", buf, flag, 1, 0); if (rc < 0) return rc; count += rc; buf[0] = '-'; rc = imap_exec_msgset(idata, "UID STORE", buf, flag, 1, 1); if (rc < 0) return rc; count += rc; return count; } /** * get_mailbox - Split mailbox URI * @param path Mailbox URI * @param hidata Server data * @param buf Buffer to store mailbox name * @param blen Length of buffer * @retval 0 Success * @retval -1 Failure * * Split up a mailbox URI. The connection info is stored in the ImapData and * the mailbox name is stored in buf. */ static int get_mailbox(const char *path, struct ImapData **hidata, char *buf, size_t blen) { struct ImapMbox mx; if (imap_parse_path(path, &mx)) { mutt_debug(1, "Error parsing %s\n", path); return -1; } if (!(*hidata = imap_conn_find(&(mx.account), ImapPassive ? MUTT_IMAP_CONN_NONEW : 0)) || (*hidata)->state < IMAP_AUTHENTICATED) { FREE(&mx.mbox); return -1; } imap_fix_path(*hidata, mx.mbox, buf, blen); if (!*buf) mutt_str_strfcpy(buf, "INBOX", blen); FREE(&mx.mbox); return 0; } /** * do_search - Perform a search of messages * @param search List of pattern to match * @param allpats Must all patterns match? * @retval num Number of patterns search that should be done server-side * * Count the number of patterns that can be done by the server (are full-text). */ static int do_search(const struct Pattern *search, int allpats) { int rc = 0; const struct Pattern *pat = NULL; for (pat = search; pat; pat = pat->next) { switch (pat->op) { case MUTT_BODY: case MUTT_HEADER: case MUTT_WHOLE_MSG: if (pat->stringmatch) rc++; break; case MUTT_SERVERSEARCH: rc++; break; default: if (pat->child && do_search(pat->child, 1)) rc++; } if (!allpats) break; } return rc; } /** * compile_search - Convert NeoMutt pattern to IMAP search * @param ctx Context * @param pat Pattern to convert * @param buf Buffer for result * @retval 0 Success * @retval -1 Failure * * Convert neomutt Pattern to IMAP SEARCH command containing only elements * that require full-text search (neomutt already has what it needs for most * match types, and does a better job (eg server doesn't support regexes). */ static int compile_search(struct Context *ctx, const struct Pattern *pat, struct Buffer *buf) { if (do_search(pat, 0) == 0) return 0; if (pat->not) mutt_buffer_addstr(buf, "NOT "); if (pat->child) { int clauses; clauses = do_search(pat->child, 1); if (clauses > 0) { const struct Pattern *clause = pat->child; mutt_buffer_addch(buf, '('); while (clauses) { if (do_search(clause, 0)) { if (pat->op == MUTT_OR && clauses > 1) mutt_buffer_addstr(buf, "OR "); clauses--; if (compile_search(ctx, clause, buf) < 0) return -1; if (clauses) mutt_buffer_addch(buf, ' '); } clause = clause->next; } mutt_buffer_addch(buf, ')'); } } else { char term[STRING]; char *delim = NULL; switch (pat->op) { case MUTT_HEADER: mutt_buffer_addstr(buf, "HEADER "); /* extract header name */ delim = strchr(pat->p.str, ':'); if (!delim) { mutt_error(_("Header search without header name: %s"), pat->p.str); return -1; } *delim = '\0'; imap_quote_string(term, sizeof(term), pat->p.str); mutt_buffer_addstr(buf, term); mutt_buffer_addch(buf, ' '); /* and field */ *delim = ':'; delim++; SKIPWS(delim); imap_quote_string(term, sizeof(term), delim); mutt_buffer_addstr(buf, term); break; case MUTT_BODY: mutt_buffer_addstr(buf, "BODY "); imap_quote_string(term, sizeof(term), pat->p.str); mutt_buffer_addstr(buf, term); break; case MUTT_WHOLE_MSG: mutt_buffer_addstr(buf, "TEXT "); imap_quote_string(term, sizeof(term), pat->p.str); mutt_buffer_addstr(buf, term); break; case MUTT_SERVERSEARCH: { struct ImapData *idata = ctx->data; if (!mutt_bit_isset(idata->capabilities, X_GM_EXT1)) { mutt_error(_("Server-side custom search not supported: %s"), pat->p.str); return -1; } } mutt_buffer_addstr(buf, "X-GM-RAW "); imap_quote_string(term, sizeof(term), pat->p.str); mutt_buffer_addstr(buf, term); break; } } return 0; } /** * longest_common_prefix - Find longest prefix common to two strings * @param dest Destination buffer * @param src Source buffer * @param start Starting offset into string * @param dlen Destination buffer length * @retval num Length of the common string * * Trim dest to the length of the longest prefix it shares with src. */ static size_t longest_common_prefix(char *dest, const char *src, size_t start, size_t dlen) { size_t pos = start; while (pos < dlen && dest[pos] && dest[pos] == src[pos]) pos++; dest[pos] = '\0'; return pos; } /** * complete_hosts - Look for completion matches for mailboxes * @param buf Partial mailbox name to complete * @param buflen Length of buffer * @retval 0 Success * @retval -1 Failure * * look for IMAP URLs to complete from defined mailboxes. Could be extended to * complete over open connections and account/folder hooks too. */ static int complete_hosts(char *buf, size_t buflen) { struct Buffy *mailbox = NULL; struct Connection *conn = NULL; int rc = -1; size_t matchlen; matchlen = mutt_str_strlen(buf); for (mailbox = Incoming; mailbox; mailbox = mailbox->next) { if (mutt_str_strncmp(buf, mailbox->path, matchlen) == 0) { if (rc) { mutt_str_strfcpy(buf, mailbox->path, buflen); rc = 0; } else longest_common_prefix(buf, mailbox->path, matchlen, buflen); } } TAILQ_FOREACH(conn, mutt_socket_head(), entries) { struct Url url; char urlstr[LONG_STRING]; if (conn->account.type != MUTT_ACCT_TYPE_IMAP) continue; mutt_account_tourl(&conn->account, &url); /* FIXME: how to handle multiple users on the same host? */ url.user = NULL; url.path = NULL; url_tostring(&url, urlstr, sizeof(urlstr), 0); if (mutt_str_strncmp(buf, urlstr, matchlen) == 0) { if (rc) { mutt_str_strfcpy(buf, urlstr, buflen); rc = 0; } else longest_common_prefix(buf, urlstr, matchlen, buflen); } } return rc; } /** * imap_access - Check permissions on an IMAP mailbox * @param path Mailbox path * @retval 0 Success * @retval <0 Failure * * TODO: ACL checks. Right now we assume if it exists we can mess with it. */ int imap_access(const char *path) { struct ImapData *idata = NULL; struct ImapMbox mx; char buf[LONG_STRING]; char mailbox[LONG_STRING]; char mbox[LONG_STRING]; int rc; if (imap_parse_path(path, &mx)) return -1; idata = imap_conn_find(&mx.account, ImapPassive ? MUTT_IMAP_CONN_NONEW : 0); if (!idata) { FREE(&mx.mbox); return -1; } imap_fix_path(idata, mx.mbox, mailbox, sizeof(mailbox)); if (!*mailbox) mutt_str_strfcpy(mailbox, "INBOX", sizeof(mailbox)); /* we may already be in the folder we're checking */ if (mutt_str_strcmp(idata->mailbox, mx.mbox) == 0) { FREE(&mx.mbox); return 0; } FREE(&mx.mbox); if (imap_mboxcache_get(idata, mailbox, 0)) { mutt_debug(3, "found %s in cache\n", mailbox); return 0; } imap_munge_mbox_name(idata, mbox, sizeof(mbox), mailbox); if (mutt_bit_isset(idata->capabilities, IMAP4REV1)) snprintf(buf, sizeof(buf), "STATUS %s (UIDVALIDITY)", mbox); else if (mutt_bit_isset(idata->capabilities, STATUS)) snprintf(buf, sizeof(buf), "STATUS %s (UID-VALIDITY)", mbox); else { mutt_debug(2, "STATUS not supported?\n"); return -1; } rc = imap_exec(idata, buf, IMAP_CMD_FAIL_OK); if (rc < 0) { mutt_debug(1, "Can't check STATUS of %s\n", mbox); return rc; } return 0; } /** * imap_create_mailbox - Create a new mailbox * @param idata Server data * @param mailbox Mailbox to create * @retval 0 Success * @retval -1 Failure */ int imap_create_mailbox(struct ImapData *idata, char *mailbox) { char buf[LONG_STRING], mbox[LONG_STRING]; imap_munge_mbox_name(idata, mbox, sizeof(mbox), mailbox); snprintf(buf, sizeof(buf), "CREATE %s", mbox); if (imap_exec(idata, buf, 0) != 0) { mutt_error(_("CREATE failed: %s"), imap_cmd_trailer(idata)); return -1; } return 0; } /** * imap_rename_mailbox - Rename a mailbox * @param idata Server data * @param mx Existing mailbox * @param newname New name for mailbox * @retval 0 Success * @retval -1 Failure */ int imap_rename_mailbox(struct ImapData *idata, struct ImapMbox *mx, const char *newname) { char oldmbox[LONG_STRING]; char newmbox[LONG_STRING]; char buf[LONG_STRING]; imap_munge_mbox_name(idata, oldmbox, sizeof(oldmbox), mx->mbox); imap_munge_mbox_name(idata, newmbox, sizeof(newmbox), newname); snprintf(buf, sizeof(buf), "RENAME %s %s", oldmbox, newmbox); if (imap_exec(idata, buf, 0) != 0) return -1; return 0; } /** * imap_delete_mailbox - Delete a mailbox * @param ctx Context * @param mx Mailbox to delete * @retval 0 Success * @retval -1 Failure */ int imap_delete_mailbox(struct Context *ctx, struct ImapMbox *mx) { char buf[PATH_MAX], mbox[PATH_MAX]; struct ImapData *idata = NULL; if (!ctx || !ctx->data) { idata = imap_conn_find(&mx->account, ImapPassive ? MUTT_IMAP_CONN_NONEW : 0); if (!idata) { FREE(&mx->mbox); return -1; } } else { idata = ctx->data; } imap_munge_mbox_name(idata, mbox, sizeof(mbox), mx->mbox); snprintf(buf, sizeof(buf), "DELETE %s", mbox); if (imap_exec(idata, buf, 0) != 0) return -1; return 0; } /** * imap_logout_all - close all open connections * * Quick and dirty until we can make sure we've got all the context we need. */ void imap_logout_all(void) { struct ConnectionList *head = mutt_socket_head(); struct Connection *np, *tmp; TAILQ_FOREACH_SAFE(np, head, entries, tmp) { if (np->account.type == MUTT_ACCT_TYPE_IMAP && np->fd >= 0) { TAILQ_REMOVE(head, np, entries); mutt_message(_("Closing connection to %s..."), np->account.host); imap_logout((struct ImapData **) (void *) &np->data); mutt_clear_error(); mutt_socket_free(np); } } } /** * imap_read_literal - Read bytes bytes from server into file * @param fp File handle for email file * @param idata Server data * @param bytes Number of bytes to read * @param pbar Progress bar * @retval 0 Success * @retval -1 Failure * * Not explicitly buffered, relies on FILE buffering. * * @note Strips `\r` from `\r\n`. * Apparently even literals use `\r\n`-terminated strings ?! */ int imap_read_literal(FILE *fp, struct ImapData *idata, unsigned long bytes, struct Progress *pbar) { char c; bool r = false; struct Buffer *buf = NULL; if (DebugLevel >= IMAP_LOG_LTRL) buf = mutt_buffer_alloc(bytes + 10); mutt_debug(2, "reading %ld bytes\n", bytes); for (unsigned long pos = 0; pos < bytes; pos++) { if (mutt_socket_readchar(idata->conn, &c) != 1) { mutt_debug(1, "error during read, %ld bytes read\n", pos); idata->status = IMAP_FATAL; mutt_buffer_free(&buf); return -1; } if (r && c != '\n') fputc('\r', fp); if (c == '\r') { r = true; continue; } else r = false; fputc(c, fp); if (pbar && !(pos % 1024)) mutt_progress_update(pbar, pos, -1); if (DebugLevel >= IMAP_LOG_LTRL) mutt_buffer_addch(buf, c); } if (DebugLevel >= IMAP_LOG_LTRL) { mutt_debug(IMAP_LOG_LTRL, "\n%s", buf->data); mutt_buffer_free(&buf); } return 0; } /** * imap_expunge_mailbox - Purge messages from the server * @param idata Server data * * Purge IMAP portion of expunged messages from the context. Must not be done * while something has a handle on any headers (eg inside pager or editor). * That is, check IMAP_REOPEN_ALLOW. */ void imap_expunge_mailbox(struct ImapData *idata) { struct Header *h = NULL; int cacheno; short old_sort; #ifdef USE_HCACHE idata->hcache = imap_hcache_open(idata, NULL); #endif old_sort = Sort; Sort = SORT_ORDER; mutt_sort_headers(idata->ctx, 0); for (int i = 0; i < idata->ctx->msgcount; i++) { h = idata->ctx->hdrs[i]; if (h->index == INT_MAX) { mutt_debug(2, "Expunging message UID %u.\n", HEADER_DATA(h)->uid); h->active = false; idata->ctx->size -= h->content->length; imap_cache_del(idata, h); #ifdef USE_HCACHE imap_hcache_del(idata, HEADER_DATA(h)->uid); #endif /* free cached body from disk, if necessary */ cacheno = HEADER_DATA(h)->uid % IMAP_CACHE_LEN; if (idata->cache[cacheno].uid == HEADER_DATA(h)->uid && idata->cache[cacheno].path) { unlink(idata->cache[cacheno].path); FREE(&idata->cache[cacheno].path); } mutt_hash_int_delete(idata->uid_hash, HEADER_DATA(h)->uid, h); imap_free_header_data((struct ImapHeaderData **) &h->data); } else { h->index = i; /* NeoMutt has several places where it turns off h->active as a * hack. For example to avoid FLAG updates, or to exclude from * imap_exec_msgset. * * Unfortunately, when a reopen is allowed and the IMAP_EXPUNGE_PENDING * flag becomes set (e.g. a flag update to a modified header), * this function will be called by imap_cmd_finish(). * * The mx_update_tables() will free and remove these "inactive" headers, * despite that an EXPUNGE was not received for them. * This would result in memory leaks and segfaults due to dangling * pointers in the msn_index and uid_hash. * * So this is another hack to work around the hacks. We don't want to * remove the messages, so make sure active is on. */ h->active = true; } } #ifdef USE_HCACHE imap_hcache_close(idata); #endif /* We may be called on to expunge at any time. We can't rely on the caller * to always know to rethread */ mx_update_tables(idata->ctx, false); Sort = old_sort; mutt_sort_headers(idata->ctx, 1); } /** * imap_conn_find - Find an open IMAP connection * @param account Account to search * @param flags Flags, e.g. #MUTT_IMAP_CONN_NONEW * @retval ptr Matching connection * @retval NULL Failure * * Find an open IMAP connection matching account, or open a new one if none can * be found. */ struct ImapData *imap_conn_find(const struct Account *account, int flags) { struct Connection *conn = NULL; struct Account *creds = NULL; struct ImapData *idata = NULL; bool new = false; while ((conn = mutt_conn_find(conn, account))) { if (!creds) creds = &conn->account; else memcpy(&conn->account, creds, sizeof(struct Account)); idata = conn->data; if (flags & MUTT_IMAP_CONN_NONEW) { if (!idata) { /* This should only happen if we've come to the end of the list */ mutt_socket_free(conn); return NULL; } else if (idata->state < IMAP_AUTHENTICATED) continue; } if (flags & MUTT_IMAP_CONN_NOSELECT && idata && idata->state >= IMAP_SELECTED) continue; if (idata && idata->status == IMAP_FATAL) continue; break; } if (!conn) return NULL; /* this happens when the initial connection fails */ if (!idata) { /* The current connection is a new connection */ idata = imap_new_idata(); if (!idata) { mutt_socket_free(conn); return NULL; } conn->data = idata; idata->conn = conn; new = true; } if (idata->state == IMAP_DISCONNECTED) imap_open_connection(idata); if (idata->state == IMAP_CONNECTED) { if (imap_authenticate(idata) == IMAP_AUTH_SUCCESS) { idata->state = IMAP_AUTHENTICATED; FREE(&idata->capstr); new = true; if (idata->conn->ssf) mutt_debug(2, "Communication encrypted at %d bits\n", idata->conn->ssf); } else mutt_account_unsetpass(&idata->conn->account); } if (new && idata->state == IMAP_AUTHENTICATED) { /* capabilities may have changed */ imap_exec(idata, "CAPABILITY", IMAP_CMD_QUEUE); /* enable RFC6855, if the server supports that */ if (mutt_bit_isset(idata->capabilities, ENABLE)) imap_exec(idata, "ENABLE UTF8=ACCEPT", IMAP_CMD_QUEUE); /* get root delimiter, '/' as default */ idata->delim = '/'; imap_exec(idata, "LIST \"\" \"\"", IMAP_CMD_QUEUE); /* we may need the root delimiter before we open a mailbox */ imap_exec(idata, NULL, IMAP_CMD_FAIL_OK); } return idata; } /** * imap_open_connection - Open an IMAP connection * @param idata Server data * @retval 0 Success * @retval -1 Failure */ int imap_open_connection(struct ImapData *idata) { char buf[LONG_STRING]; if (mutt_socket_open(idata->conn) < 0) return -1; idata->state = IMAP_CONNECTED; if (imap_cmd_step(idata) != IMAP_CMD_OK) { imap_close_connection(idata); return -1; } if (mutt_str_strncasecmp("* OK", idata->buf, 4) == 0) { if ((mutt_str_strncasecmp("* OK [CAPABILITY", idata->buf, 16) != 0) && check_capabilities(idata)) { goto bail; } #ifdef USE_SSL /* Attempt STARTTLS if available and desired. */ if (!idata->conn->ssf && (SslForceTls || mutt_bit_isset(idata->capabilities, STARTTLS))) { int rc; if (SslForceTls) rc = MUTT_YES; else if ((rc = query_quadoption(SslStarttls, _("Secure connection with TLS?"))) == MUTT_ABORT) { goto err_close_conn; } if (rc == MUTT_YES) { rc = imap_exec(idata, "STARTTLS", IMAP_CMD_FAIL_OK); if (rc == -1) goto bail; if (rc != -2) { if (mutt_ssl_starttls(idata->conn)) { mutt_error(_("Could not negotiate TLS connection")); goto err_close_conn; } else { /* RFC2595 demands we recheck CAPABILITY after TLS completes. */ if (imap_exec(idata, "CAPABILITY", 0)) goto bail; } } } } if (SslForceTls && !idata->conn->ssf) { mutt_error(_("Encrypted connection unavailable")); goto err_close_conn; } #endif } else if (mutt_str_strncasecmp("* PREAUTH", idata->buf, 9) == 0) { idata->state = IMAP_AUTHENTICATED; if (check_capabilities(idata) != 0) goto bail; FREE(&idata->capstr); } else { imap_error("imap_open_connection()", buf); goto bail; } return 0; #ifdef USE_SSL err_close_conn: imap_close_connection(idata); #endif bail: FREE(&idata->capstr); return -1; } /** * imap_close_connection - Close an IMAP connection * @param idata Server data */ void imap_close_connection(struct ImapData *idata) { if (idata->state != IMAP_DISCONNECTED) { mutt_socket_close(idata->conn); idata->state = IMAP_DISCONNECTED; } idata->seqno = idata->nextcmd = idata->lastcmd = idata->status = false; memset(idata->cmds, 0, sizeof(struct ImapCommand) * idata->cmdslots); } /** * imap_logout - Gracefully log out of server * @param idata Server data */ void imap_logout(struct ImapData **idata) { /* we set status here to let imap_handle_untagged know we _expect_ to * receive a bye response (so it doesn't freak out and close the conn) */ (*idata)->status = IMAP_BYE; imap_cmd_start(*idata, "LOGOUT"); if (ImapPollTimeout <= 0 || mutt_socket_poll((*idata)->conn, ImapPollTimeout) != 0) { while (imap_cmd_step(*idata) == IMAP_CMD_CONTINUE) ; } mutt_socket_close((*idata)->conn); imap_free_idata(idata); } /** * imap_has_flag - Does the flag exist in the list * @param flag_list List of server flags * @param flag Flag to find * @retval true Flag exists * * Do a caseless comparison of the flag against a flag list, return true if * found or flag list has '\*'. */ bool imap_has_flag(struct ListHead *flag_list, const char *flag) { if (STAILQ_EMPTY(flag_list)) return false; struct ListNode *np; STAILQ_FOREACH(np, flag_list, entries) { if (mutt_str_strncasecmp(np->data, flag, strlen(np->data)) == 0) return true; if (mutt_str_strncmp(np->data, "\\*", strlen(np->data)) == 0) return true; } return false; } /** * imap_exec_msgset - Prepare commands for all messages matching conditions * @param idata ImapData containing context containing header set * @param pre prefix commands * @param post postfix commands * @param flag flag type on which to filter, e.g. MUTT_REPLIED * @param changed include only changed messages in message set * @param invert invert sense of flag, eg MUTT_READ matches unread messages * @retval num Matched messages * @retval -1 Failure * * pre/post: commands are of the form "%s %s %s %s", tag, pre, message set, post * Prepares commands for all messages matching conditions * (must be flushed with imap_exec) */ int imap_exec_msgset(struct ImapData *idata, const char *pre, const char *post, int flag, int changed, int invert) { struct Header **hdrs = NULL; short oldsort; int pos; int rc; int count = 0; struct Buffer *cmd = mutt_buffer_new(); /* We make a copy of the headers just in case resorting doesn't give exactly the original order (duplicate messages?), because other parts of the ctx are tied to the header order. This may be overkill. */ oldsort = Sort; if (Sort != SORT_ORDER) { hdrs = idata->ctx->hdrs; idata->ctx->hdrs = mutt_mem_malloc(idata->ctx->msgcount * sizeof(struct Header *)); memcpy(idata->ctx->hdrs, hdrs, idata->ctx->msgcount * sizeof(struct Header *)); Sort = SORT_ORDER; qsort(idata->ctx->hdrs, idata->ctx->msgcount, sizeof(struct Header *), mutt_get_sort_func(SORT_ORDER)); } pos = 0; do { cmd->dptr = cmd->data; mutt_buffer_printf(cmd, "%s ", pre); rc = make_msg_set(idata, cmd, flag, changed, invert, &pos); if (rc > 0) { mutt_buffer_printf(cmd, " %s", post); if (imap_exec(idata, cmd->data, IMAP_CMD_QUEUE)) { rc = -1; goto out; } count += rc; } } while (rc > 0); rc = count; out: mutt_buffer_free(&cmd); if (oldsort != Sort) { Sort = oldsort; FREE(&idata->ctx->hdrs); idata->ctx->hdrs = hdrs; } return rc; } /** * imap_sync_message_for_copy - Update server to reflect the flags of a single message * @param[in] idata Server data * @param[in] hdr Header of the email * @param[in] cmd Buffer for the command string * @param[out] err_continue Did the user force a continue? * @retval 0 Success * @retval -1 Failure * * Update the IMAP server to reflect the flags for a single message before * performing a "UID COPY". * * @note This does not sync the "deleted" flag state, because it is not * desirable to propagate that flag into the copy. */ int imap_sync_message_for_copy(struct ImapData *idata, struct Header *hdr, struct Buffer *cmd, int *err_continue) { char flags[LONG_STRING]; char *tags; char uid[11]; if (!compare_flags_for_copy(hdr)) { if (hdr->deleted == HEADER_DATA(hdr)->deleted) hdr->changed = false; return 0; } snprintf(uid, sizeof(uid), "%u", HEADER_DATA(hdr)->uid); cmd->dptr = cmd->data; mutt_buffer_addstr(cmd, "UID STORE "); mutt_buffer_addstr(cmd, uid); flags[0] = '\0'; set_flag(idata, MUTT_ACL_SEEN, hdr->read, "\\Seen ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, hdr->old, "Old ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, hdr->flagged, "\\Flagged ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, hdr->replied, "\\Answered ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_DELETE, HEADER_DATA(hdr)->deleted, "\\Deleted ", flags, sizeof(flags)); if (mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE)) { /* restore system flags */ if (HEADER_DATA(hdr)->flags_system) mutt_str_strcat(flags, sizeof(flags), HEADER_DATA(hdr)->flags_system); /* set custom flags */ tags = driver_tags_get_with_hidden(&hdr->tags); if (tags) { mutt_str_strcat(flags, sizeof(flags), tags); FREE(&tags); } } mutt_str_remove_trailing_ws(flags); /* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to * explicitly revoke all system flags (if we have permission) */ if (!*flags) { set_flag(idata, MUTT_ACL_SEEN, 1, "\\Seen ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, 1, "Old ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, 1, "\\Flagged ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_WRITE, 1, "\\Answered ", flags, sizeof(flags)); set_flag(idata, MUTT_ACL_DELETE, !HEADER_DATA(hdr)->deleted, "\\Deleted ", flags, sizeof(flags)); /* erase custom flags */ if (mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE) && HEADER_DATA(hdr)->flags_remote) mutt_str_strcat(flags, sizeof(flags), HEADER_DATA(hdr)->flags_remote); mutt_str_remove_trailing_ws(flags); mutt_buffer_addstr(cmd, " -FLAGS.SILENT ("); } else mutt_buffer_addstr(cmd, " FLAGS.SILENT ("); mutt_buffer_addstr(cmd, flags); mutt_buffer_addstr(cmd, ")"); /* dumb hack for bad UW-IMAP 4.7 servers spurious FLAGS updates */ hdr->active = false; /* after all this it's still possible to have no flags, if you * have no ACL rights */ if (*flags && (imap_exec(idata, cmd->data, 0) != 0) && err_continue && (*err_continue != MUTT_YES)) { *err_continue = imap_continue("imap_sync_message: STORE failed", idata->buf); if (*err_continue != MUTT_YES) { hdr->active = true; return -1; } } /* server have now the updated flags */ FREE(&HEADER_DATA(hdr)->flags_remote); HEADER_DATA(hdr)->flags_remote = driver_tags_get_with_hidden(&hdr->tags); hdr->active = true; if (hdr->deleted == HEADER_DATA(hdr)->deleted) hdr->changed = false; return 0; } /** * imap_check_mailbox - use the NOOP or IDLE command to poll for new mail * @param ctx Context * @param force Don't wait * @retval #MUTT_REOPENED mailbox has been externally modified * @retval #MUTT_NEW_MAIL new mail has arrived * @retval 0 no change * @retval -1 error */ int imap_check_mailbox(struct Context *ctx, int force) { return imap_check(ctx->data, force); } /** * imap_check - Check for new mail * @param idata Server data * @param force Force a refresh * @retval >0 Success, e.g. #MUTT_REOPENED * @retval -1 Failure */ int imap_check(struct ImapData *idata, int force) { /* overload keyboard timeout to avoid many mailbox checks in a row. * Most users don't like having to wait exactly when they press a key. */ int result = 0; /* try IDLE first, unless force is set */ if (!force && ImapIdle && mutt_bit_isset(idata->capabilities, IDLE) && (idata->state != IMAP_IDLE || time(NULL) >= idata->lastread + ImapKeepalive)) { if (imap_cmd_idle(idata) < 0) return -1; } if (idata->state == IMAP_IDLE) { while ((result = mutt_socket_poll(idata->conn, 0)) > 0) { if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE) { mutt_debug(1, "Error reading IDLE response\n"); return -1; } } if (result < 0) { mutt_debug(1, "Poll failed, disabling IDLE\n"); mutt_bit_unset(idata->capabilities, IDLE); } } if ((force || (idata->state != IMAP_IDLE && time(NULL) >= idata->lastread + Timeout)) && imap_exec(idata, "NOOP", IMAP_CMD_POLL) != 0) { return -1; } /* We call this even when we haven't run NOOP in case we have pending * changes to process, since we can reopen here. */ imap_cmd_finish(idata); if (idata->check_status & IMAP_EXPUNGE_PENDING) result = MUTT_REOPENED; else if (idata->check_status & IMAP_NEWMAIL_PENDING) result = MUTT_NEW_MAIL; else if (idata->check_status & IMAP_FLAGS_PENDING) result = MUTT_FLAGS; idata->check_status = 0; return result; } /** * imap_buffy_check - Check for new mail in subscribed folders * @param check_stats Check for message stats too * @retval num Number of mailboxes with new mail * @retval 0 Failure * * Given a list of mailboxes rather than called once for each so that it can * batch the commands and save on round trips. */ int imap_buffy_check(int check_stats) { struct ImapData *idata = NULL; struct ImapData *lastdata = NULL; struct Buffy *mailbox = NULL; char name[LONG_STRING]; char command[LONG_STRING]; char munged[LONG_STRING]; int buffies = 0; for (mailbox = Incoming; mailbox; mailbox = mailbox->next) { /* Init newly-added mailboxes */ if (!mailbox->magic) { if (mx_is_imap(mailbox->path)) mailbox->magic = MUTT_IMAP; } if (mailbox->magic != MUTT_IMAP) continue; if (get_mailbox(mailbox->path, &idata, name, sizeof(name)) < 0) { mailbox->new = false; continue; } /* Don't issue STATUS on the selected mailbox, it will be NOOPed or * IDLEd elsewhere. * idata->mailbox may be NULL for connections other than the current * mailbox's, and shouldn't expand to INBOX in that case. #3216. */ if (idata->mailbox && (imap_mxcmp(name, idata->mailbox) == 0)) { mailbox->new = false; continue; } if (!mutt_bit_isset(idata->capabilities, IMAP4REV1) && !mutt_bit_isset(idata->capabilities, STATUS)) { mutt_debug(2, "Server doesn't support STATUS\n"); continue; } if (lastdata && idata != lastdata) { /* Send commands to previous server. Sorting the buffy list * may prevent some infelicitous interleavings */ if (imap_exec(lastdata, NULL, IMAP_CMD_FAIL_OK | IMAP_CMD_POLL) == -1) mutt_debug(1, "#1 Error polling mailboxes\n"); lastdata = NULL; } if (!lastdata) lastdata = idata; imap_munge_mbox_name(idata, munged, sizeof(munged), name); if (check_stats) { snprintf(command, sizeof(command), "STATUS %s (UIDNEXT UIDVALIDITY UNSEEN RECENT MESSAGES)", munged); } else { snprintf(command, sizeof(command), "STATUS %s (UIDNEXT UIDVALIDITY UNSEEN RECENT)", munged); } if (imap_exec(idata, command, IMAP_CMD_QUEUE | IMAP_CMD_POLL) < 0) { mutt_debug(1, "Error queueing command\n"); return 0; } } if (lastdata && (imap_exec(lastdata, NULL, IMAP_CMD_FAIL_OK | IMAP_CMD_POLL) == -1)) { mutt_debug(1, "#2 Error polling mailboxes\n"); return 0; } /* collect results */ for (mailbox = Incoming; mailbox; mailbox = mailbox->next) { if (mailbox->magic == MUTT_IMAP && mailbox->new) buffies++; } return buffies; } /** * imap_status - Get the status of a mailbox * @param path Path of mailbox * @param queue true if the command should be queued for the next call * @retval -1 Error * @retval >=0 Count of messages in mailbox * * If queue is true, the command will be sent now and be expected to have been * run on the next call (for pipelining the postponed count). */ int imap_status(char *path, int queue) { static int queued = 0; struct ImapData *idata = NULL; char buf[LONG_STRING]; char mbox[LONG_STRING]; struct ImapStatus *status = NULL; if (get_mailbox(path, &idata, buf, sizeof(buf)) < 0) return -1; /* We are in the folder we're polling - just return the mailbox count. * * Note that imap_mxcmp() converts NULL to "INBOX", so we need to * make sure the idata really is open to a folder. */ if (idata->ctx && !imap_mxcmp(buf, idata->mailbox)) return idata->ctx->msgcount; else if (mutt_bit_isset(idata->capabilities, IMAP4REV1) || mutt_bit_isset(idata->capabilities, STATUS)) { imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf); snprintf(buf, sizeof(buf), "STATUS %s (%s)", mbox, "MESSAGES"); imap_unmunge_mbox_name(idata, mbox); } else { /* Server does not support STATUS, and this is not the current mailbox. * There is no lightweight way to check recent arrivals */ return -1; } if (queue) { imap_exec(idata, buf, IMAP_CMD_QUEUE); queued = 1; return 0; } else if (!queued) imap_exec(idata, buf, 0); queued = 0; status = imap_mboxcache_get(idata, mbox, 0); if (status) return status->messages; return 0; } /** * imap_mboxcache_get - Open an hcache for a mailbox * @param idata Server data * @param mbox Mailbox to cache * @param create Should it be created if it doesn't exist? * @retval ptr Stats of cached mailbox * @retval ptr Stats of new cache entry * @retval NULL Not in cache and create is false * * return cached mailbox stats or NULL if create is 0 */ struct ImapStatus *imap_mboxcache_get(struct ImapData *idata, const char *mbox, bool create) { struct ImapStatus *status = NULL; #ifdef USE_HCACHE header_cache_t *hc = NULL; void *uidvalidity = NULL; void *uidnext = NULL; #endif struct ListNode *np; STAILQ_FOREACH(np, &idata->mboxcache, entries) { status = (struct ImapStatus *) np->data; if (imap_mxcmp(mbox, status->name) == 0) return status; } status = NULL; /* lame */ if (create) { struct ImapStatus *scache = mutt_mem_calloc(1, sizeof(struct ImapStatus)); scache->name = (char *) mbox; mutt_list_insert_tail(&idata->mboxcache, (char *) scache); status = imap_mboxcache_get(idata, mbox, 0); status->name = mutt_str_strdup(mbox); } #ifdef USE_HCACHE hc = imap_hcache_open(idata, mbox); if (hc) { uidvalidity = mutt_hcache_fetch_raw(hc, "/UIDVALIDITY", 12); uidnext = mutt_hcache_fetch_raw(hc, "/UIDNEXT", 8); if (uidvalidity) { if (!status) { mutt_hcache_free(hc, &uidvalidity); mutt_hcache_free(hc, &uidnext); mutt_hcache_close(hc); return imap_mboxcache_get(idata, mbox, 1); } status->uidvalidity = *(unsigned int *) uidvalidity; status->uidnext = uidnext ? *(unsigned int *) uidnext : 0; mutt_debug(3, "hcache uidvalidity %u, uidnext %u\n", status->uidvalidity, status->uidnext); } mutt_hcache_free(hc, &uidvalidity); mutt_hcache_free(hc, &uidnext); mutt_hcache_close(hc); } #endif return status; } /** * imap_mboxcache_free - Free the cached ImapStatus * @param idata Server data */ void imap_mboxcache_free(struct ImapData *idata) { struct ImapStatus *status = NULL; struct ListNode *np; STAILQ_FOREACH(np, &idata->mboxcache, entries) { status = (struct ImapStatus *) np->data; FREE(&status->name); } mutt_list_free(&idata->mboxcache); } /** * imap_search - Find a matching mailbox * @param ctx Context * @param pat Pattern to match * @retval 0 Success * @retval -1 Failure */ int imap_search(struct Context *ctx, const struct Pattern *pat) { struct Buffer buf; struct ImapData *idata = ctx->data; for (int i = 0; i < ctx->msgcount; i++) ctx->hdrs[i]->matched = false; if (do_search(pat, 1) == 0) return 0; mutt_buffer_init(&buf); mutt_buffer_addstr(&buf, "UID SEARCH "); if (compile_search(ctx, pat, &buf) < 0) { FREE(&buf.data); return -1; } if (imap_exec(idata, buf.data, 0) < 0) { FREE(&buf.data); return -1; } FREE(&buf.data); return 0; } /** * imap_subscribe - Subscribe to a mailbox * @param path Mailbox path * @param subscribe True: subscribe, false: unsubscribe * @retval 0 Success * @retval -1 Failure */ int imap_subscribe(char *path, bool subscribe) { struct ImapData *idata = NULL; char buf[LONG_STRING]; char mbox[LONG_STRING]; char errstr[STRING]; struct Buffer err, token; struct ImapMbox mx; if (!mx_is_imap(path) || imap_parse_path(path, &mx) || !mx.mbox) { mutt_error(_("Bad mailbox name")); return -1; } idata = imap_conn_find(&(mx.account), 0); if (!idata) goto fail; imap_fix_path(idata, mx.mbox, buf, sizeof(buf)); if (!*buf) mutt_str_strfcpy(buf, "INBOX", sizeof(buf)); if (ImapCheckSubscribed) { mutt_buffer_init(&token); mutt_buffer_init(&err); err.data = errstr; err.dsize = sizeof(errstr); snprintf(mbox, sizeof(mbox), "%smailboxes \"%s\"", subscribe ? "" : "un", path); if (mutt_parse_rc_line(mbox, &token, &err)) mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr); FREE(&token.data); } if (subscribe) mutt_message(_("Subscribing to %s..."), buf); else mutt_message(_("Unsubscribing from %s..."), buf); imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf); snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox); if (imap_exec(idata, buf, 0) < 0) goto fail; imap_unmunge_mbox_name(idata, mx.mbox); if (subscribe) mutt_message(_("Subscribed to %s"), mx.mbox); else mutt_message(_("Unsubscribed from %s"), mx.mbox); FREE(&mx.mbox); return 0; fail: FREE(&mx.mbox); return -1; } /** * imap_complete - Try to complete an IMAP folder path * @param buf Buffer for result * @param buflen Length of buffer * @param path Partial mailbox name to complete * @retval 0 Success * @retval -1 Failure * * Given a partial IMAP folder path, return a string which adds as much to the * path as is unique */ int imap_complete(char *buf, size_t buflen, char *path) { struct ImapData *idata = NULL; char list[LONG_STRING]; char tmp[LONG_STRING]; struct ImapList listresp; char completion[LONG_STRING]; int clen; size_t matchlen = 0; int completions = 0; struct ImapMbox mx; int rc; if (imap_parse_path(path, &mx)) { mutt_str_strfcpy(buf, path, buflen); return complete_hosts(buf, buflen); } /* don't open a new socket just for completion. Instead complete over * known mailboxes/hooks/etc */ idata = imap_conn_find(&(mx.account), MUTT_IMAP_CONN_NONEW); if (!idata) { FREE(&mx.mbox); mutt_str_strfcpy(buf, path, buflen); return complete_hosts(buf, buflen); } /* reformat path for IMAP list, and append wildcard */ /* don't use INBOX in place of "" */ if (mx.mbox && mx.mbox[0]) imap_fix_path(idata, mx.mbox, list, sizeof(list)); else list[0] = '\0'; /* fire off command */ snprintf(tmp, sizeof(tmp), "%s \"\" \"%s%%\"", ImapListSubscribed ? "LSUB" : "LIST", list); imap_cmd_start(idata, tmp); /* and see what the results are */ mutt_str_strfcpy(completion, NONULL(mx.mbox), sizeof(completion)); idata->cmdtype = IMAP_CT_LIST; idata->cmddata = &listresp; do { listresp.name = NULL; rc = imap_cmd_step(idata); if (rc == IMAP_CMD_CONTINUE && listresp.name) { /* if the folder isn't selectable, append delimiter to force browse * to enter it on second tab. */ if (listresp.noselect) { clen = strlen(listresp.name); listresp.name[clen++] = listresp.delim; listresp.name[clen] = '\0'; } /* copy in first word */ if (!completions) { mutt_str_strfcpy(completion, listresp.name, sizeof(completion)); matchlen = strlen(completion); completions++; continue; } matchlen = longest_common_prefix(completion, listresp.name, 0, matchlen); completions++; } } while (rc == IMAP_CMD_CONTINUE); idata->cmddata = NULL; if (completions) { /* reformat output */ imap_qualify_path(buf, buflen, &mx, completion); mutt_pretty_mailbox(buf, buflen); FREE(&mx.mbox); return 0; } return -1; } /** * imap_fast_trash - Use server COPY command to copy deleted messages to trash * @param ctx Context * @param dest Mailbox to move to * @retval -1 Error * @retval 0 Success * @retval 1 Non-fatal error - try fetch/append */ int imap_fast_trash(struct Context *ctx, char *dest) { char mbox[LONG_STRING]; char mmbox[LONG_STRING]; char prompt[LONG_STRING]; int rc; struct ImapMbox mx; bool triedcreate = false; struct Buffer *sync_cmd = NULL; int err_continue = MUTT_NO; struct ImapData *idata = ctx->data; if (imap_parse_path(dest, &mx)) { mutt_debug(1, "bad destination %s\n", dest); return -1; } /* check that the save-to folder is in the same account */ if (mutt_account_match(&(idata->conn->account), &(mx.account)) == 0) { mutt_debug(3, "%s not same server as %s\n", dest, ctx->path); return 1; } imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox)); if (!*mbox) mutt_str_strfcpy(mbox, "INBOX", sizeof(mbox)); imap_munge_mbox_name(idata, mmbox, sizeof(mmbox), mbox); sync_cmd = mutt_buffer_new(); for (int i = 0; i < ctx->msgcount; i++) { if (ctx->hdrs[i]->active && ctx->hdrs[i]->changed && ctx->hdrs[i]->deleted && !ctx->hdrs[i]->purge) { rc = imap_sync_message_for_copy(idata, ctx->hdrs[i], sync_cmd, &err_continue); if (rc < 0) { mutt_debug(1, "could not sync\n"); goto out; } } } /* loop in case of TRYCREATE */ do { rc = imap_exec_msgset(idata, "UID COPY", mmbox, MUTT_TRASH, 0, 0); if (!rc) { mutt_debug(1, "No messages to trash\n"); rc = -1; goto out; } else if (rc < 0) { mutt_debug(1, "could not queue copy\n"); goto out; } else { mutt_message(ngettext("Copying %d message to %s...", "Copying %d messages to %s...", rc), rc, mbox); } /* let's get it on */ rc = imap_exec(idata, NULL, IMAP_CMD_FAIL_OK); if (rc == -2) { if (triedcreate) { mutt_debug(1, "Already tried to create mailbox %s\n", mbox); break; } /* bail out if command failed for reasons other than nonexistent target */ if (mutt_str_strncasecmp(imap_get_qualifier(idata->buf), "[TRYCREATE]", 11) != 0) break; mutt_debug(3, "server suggests TRYCREATE\n"); snprintf(prompt, sizeof(prompt), _("Create %s?"), mbox); if (Confirmcreate && mutt_yesorno(prompt, 1) != MUTT_YES) { mutt_clear_error(); goto out; } if (imap_create_mailbox(idata, mbox) < 0) break; triedcreate = true; } } while (rc == -2); if (rc != 0) { imap_error("imap_fast_trash", idata->buf); goto out; } rc = 0; out: mutt_buffer_free(&sync_cmd); FREE(&mx.mbox); return (rc < 0) ? -1 : rc; } /** * imap_mbox_open - Implements MxOps::mbox_open() */ static int imap_mbox_open(struct Context *ctx) { struct ImapData *idata = NULL; struct ImapStatus *status = NULL; char buf[PATH_MAX]; char bufout[PATH_MAX]; int count = 0; struct ImapMbox mx, pmx; int rc; if (imap_parse_path(ctx->path, &mx)) { mutt_error(_("%s is an invalid IMAP path"), ctx->path); return -1; } /* we require a connection which isn't currently in IMAP_SELECTED state */ idata = imap_conn_find(&(mx.account), MUTT_IMAP_CONN_NOSELECT); if (!idata) goto fail_noidata; if (idata->state < IMAP_AUTHENTICATED) goto fail; /* once again the context is new */ ctx->data = idata; /* Clean up path and replace the one in the ctx */ imap_fix_path(idata, mx.mbox, buf, sizeof(buf)); if (!*buf) mutt_str_strfcpy(buf, "INBOX", sizeof(buf)); FREE(&(idata->mailbox)); idata->mailbox = mutt_str_strdup(buf); imap_qualify_path(buf, sizeof(buf), &mx, idata->mailbox); FREE(&(ctx->path)); FREE(&(ctx->realpath)); ctx->path = mutt_str_strdup(buf); ctx->realpath = mutt_str_strdup(ctx->path); idata->ctx = ctx; /* clear mailbox status */ idata->status = false; memset(idata->ctx->rights, 0, sizeof(idata->ctx->rights)); idata->new_mail_count = 0; idata->max_msn = 0; mutt_message(_("Selecting %s..."), idata->mailbox); imap_munge_mbox_name(idata, buf, sizeof(buf), idata->mailbox); /* pipeline ACL test */ if (mutt_bit_isset(idata->capabilities, ACL)) { snprintf(bufout, sizeof(bufout), "MYRIGHTS %s", buf); imap_exec(idata, bufout, IMAP_CMD_QUEUE); } /* assume we have all rights if ACL is unavailable */ else { mutt_bit_set(idata->ctx->rights, MUTT_ACL_LOOKUP); mutt_bit_set(idata->ctx->rights, MUTT_ACL_READ); mutt_bit_set(idata->ctx->rights, MUTT_ACL_SEEN); mutt_bit_set(idata->ctx->rights, MUTT_ACL_WRITE); mutt_bit_set(idata->ctx->rights, MUTT_ACL_INSERT); mutt_bit_set(idata->ctx->rights, MUTT_ACL_POST); mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE); mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE); } /* pipeline the postponed count if possible */ pmx.mbox = NULL; if (mx_is_imap(Postponed) && !imap_parse_path(Postponed, &pmx) && mutt_account_match(&pmx.account, &mx.account)) { imap_status(Postponed, 1); } FREE(&pmx.mbox); if (ImapCheckSubscribed) imap_exec(idata, "LSUB \"\" \"*\"", IMAP_CMD_QUEUE); snprintf(bufout, sizeof(bufout), "%s %s", ctx->readonly ? "EXAMINE" : "SELECT", buf); idata->state = IMAP_SELECTED; imap_cmd_start(idata, bufout); status = imap_mboxcache_get(idata, idata->mailbox, 1); do { char *pc = NULL; rc = imap_cmd_step(idata); if (rc != IMAP_CMD_CONTINUE) break; pc = idata->buf + 2; /* Obtain list of available flags here, may be overridden by a * PERMANENTFLAGS tag in the OK response */ if (mutt_str_strncasecmp("FLAGS", pc, 5) == 0) { /* don't override PERMANENTFLAGS */ if (STAILQ_EMPTY(&idata->flags)) { mutt_debug(3, "Getting mailbox FLAGS\n"); pc = get_flags(&idata->flags, pc); if (!pc) goto fail; } } /* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */ else if (mutt_str_strncasecmp("OK [PERMANENTFLAGS", pc, 18) == 0) { mutt_debug(3, "Getting mailbox PERMANENTFLAGS\n"); /* safe to call on NULL */ mutt_list_free(&idata->flags); /* skip "OK [PERMANENT" so syntax is the same as FLAGS */ pc += 13; pc = get_flags(&(idata->flags), pc); if (!pc) goto fail; } /* save UIDVALIDITY for the header cache */ else if (mutt_str_strncasecmp("OK [UIDVALIDITY", pc, 14) == 0) { mutt_debug(3, "Getting mailbox UIDVALIDITY\n"); pc += 3; pc = imap_next_word(pc); if (mutt_str_atoui(pc, &idata->uid_validity) < 0) goto fail; status->uidvalidity = idata->uid_validity; } else if (mutt_str_strncasecmp("OK [UIDNEXT", pc, 11) == 0) { mutt_debug(3, "Getting mailbox UIDNEXT\n"); pc += 3; pc = imap_next_word(pc); if (mutt_str_atoui(pc, &idata->uidnext) < 0) goto fail; status->uidnext = idata->uidnext; } else { pc = imap_next_word(pc); if (mutt_str_strncasecmp("EXISTS", pc, 6) == 0) { count = idata->new_mail_count; idata->new_mail_count = 0; } } } while (rc == IMAP_CMD_CONTINUE); if (rc == IMAP_CMD_NO) { char *s = imap_next_word(idata->buf); /* skip seq */ s = imap_next_word(s); /* Skip response */ mutt_error("%s", s); goto fail; } if (rc != IMAP_CMD_OK) goto fail; /* check for READ-ONLY notification */ if ((mutt_str_strncasecmp(imap_get_qualifier(idata->buf), "[READ-ONLY]", 11) == 0) && !mutt_bit_isset(idata->capabilities, ACL)) { mutt_debug(2, "Mailbox is read-only.\n"); ctx->readonly = true; } /* dump the mailbox flags we've found */ if (DebugLevel > 2) { if (STAILQ_EMPTY(&idata->flags)) mutt_debug(3, "No folder flags found\n"); else { struct ListNode *np; struct Buffer flag_buffer; mutt_buffer_init(&flag_buffer); mutt_buffer_printf(&flag_buffer, "Mailbox flags: "); STAILQ_FOREACH(np, &idata->flags, entries) { mutt_buffer_printf(&flag_buffer, "[%s] ", np->data); } mutt_debug(3, "%s\n", flag_buffer.data); FREE(&flag_buffer.data); } } if (!(mutt_bit_isset(idata->ctx->rights, MUTT_ACL_DELETE) || mutt_bit_isset(idata->ctx->rights, MUTT_ACL_SEEN) || mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE) || mutt_bit_isset(idata->ctx->rights, MUTT_ACL_INSERT))) { ctx->readonly = true; } ctx->hdrmax = count; ctx->hdrs = mutt_mem_calloc(count, sizeof(struct Header *)); ctx->v2r = mutt_mem_calloc(count, sizeof(int)); ctx->msgcount = 0; if (count && (imap_read_headers(idata, 1, count) < 0)) { mutt_error(_("Error opening mailbox")); goto fail; } mutt_debug(2, "msgcount is %d\n", ctx->msgcount); FREE(&mx.mbox); return 0; fail: if (idata->state == IMAP_SELECTED) idata->state = IMAP_AUTHENTICATED; fail_noidata: FREE(&mx.mbox); return -1; } /** * imap_mbox_open_append - Implements MxOps::mbox_open_append() */ static int imap_mbox_open_append(struct Context *ctx, int flags) { struct ImapData *idata = NULL; char mailbox[PATH_MAX]; struct ImapMbox mx; int rc; if (imap_parse_path(ctx->path, &mx)) return -1; /* in APPEND mode, we appear to hijack an existing IMAP connection - * ctx is brand new and mostly empty */ idata = imap_conn_find(&(mx.account), 0); if (!idata) { FREE(&mx.mbox); return -1; } ctx->data = idata; imap_fix_path(idata, mx.mbox, mailbox, sizeof(mailbox)); if (!*mailbox) mutt_str_strfcpy(mailbox, "INBOX", sizeof(mailbox)); FREE(&mx.mbox); rc = imap_access(ctx->path); if (rc == 0) return 0; if (rc == -1) return -1; char buf[PATH_MAX + 64]; snprintf(buf, sizeof(buf), _("Create %s?"), mailbox); if (Confirmcreate && mutt_yesorno(buf, 1) != MUTT_YES) return -1; if (imap_create_mailbox(idata, mailbox) < 0) return -1; return 0; } /** * imap_mbox_close - Implements MxOps::mbox_close() * @retval 0 Always */ static int imap_mbox_close(struct Context *ctx) { struct ImapData *idata = ctx->data; /* Check to see if the mailbox is actually open */ if (!idata) return 0; /* imap_mbox_open_append() borrows the struct ImapData temporarily, * just for the connection, but does not set idata->ctx to the * open-append ctx. * * So when these are equal, it means we are actually closing the * mailbox and should clean up idata. Otherwise, we don't want to * touch idata - it's still being used. */ if (ctx == idata->ctx) { if (idata->status != IMAP_FATAL && idata->state >= IMAP_SELECTED) { /* mx_mbox_close won't sync if there are no deleted messages * and the mailbox is unchanged, so we may have to close here */ if (!ctx->deleted) imap_exec(idata, "CLOSE", IMAP_CMD_QUEUE); idata->state = IMAP_AUTHENTICATED; } idata->reopen &= IMAP_REOPEN_ALLOW; FREE(&(idata->mailbox)); mutt_list_free(&idata->flags); idata->ctx = NULL; mutt_hash_destroy(&idata->uid_hash); FREE(&idata->msn_index); idata->msn_index_size = 0; idata->max_msn = 0; for (int i = 0; i < IMAP_CACHE_LEN; i++) { if (idata->cache[i].path) { unlink(idata->cache[i].path); FREE(&idata->cache[i].path); } } mutt_bcache_close(&idata->bcache); } /* free IMAP part of headers */ for (int i = 0; i < ctx->msgcount; i++) { /* mailbox may not have fully loaded */ if (ctx->hdrs[i] && ctx->hdrs[i]->data) imap_free_header_data((struct ImapHeaderData **) &(ctx->hdrs[i]->data)); } return 0; } /** * imap_msg_open_new - Implements MxOps::msg_open_new() */ static int imap_msg_open_new(struct Context *ctx, struct Message *msg, struct Header *hdr) { char tmp[PATH_MAX]; mutt_mktemp(tmp, sizeof(tmp)); msg->fp = mutt_file_fopen(tmp, "w"); if (!msg->fp) { mutt_perror(tmp); return -1; } msg->path = mutt_str_strdup(tmp); return 0; } /** * imap_mbox_check - Implements MxOps::mbox_check() * @param ctx Context * @param index_hint Remember our place in the index * @retval >0 Success, e.g. #MUTT_REOPENED * @retval -1 Failure */ static int imap_mbox_check(struct Context *ctx, int *index_hint) { int rc; (void) index_hint; imap_allow_reopen(ctx); rc = imap_check(ctx->data, 0); imap_disallow_reopen(ctx); return rc; } /** * imap_sync_mailbox - Sync all the changes to the server * @param ctx Context * @param expunge 0 or 1 - do expunge? * @retval 0 Success * @retval -1 Error */ int imap_sync_mailbox(struct Context *ctx, int expunge) { struct Context *appendctx = NULL; struct Header *h = NULL; struct Header **hdrs = NULL; int oldsort; int rc; struct ImapData *idata = ctx->data; if (idata->state < IMAP_SELECTED) { mutt_debug(2, "no mailbox selected\n"); return -1; } /* This function is only called when the calling code expects the context * to be changed. */ imap_allow_reopen(ctx); rc = imap_check(idata, 0); if (rc != 0) return rc; /* if we are expunging anyway, we can do deleted messages very quickly... */ if (expunge && mutt_bit_isset(ctx->rights, MUTT_ACL_DELETE)) { rc = imap_exec_msgset(idata, "UID STORE", "+FLAGS.SILENT (\\Deleted)", MUTT_DELETED, 1, 0); if (rc < 0) { mutt_error(_("Expunge failed")); goto out; } if (rc > 0) { /* mark these messages as unchanged so second pass ignores them. Done * here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */ for (int i = 0; i < ctx->msgcount; i++) if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->changed) ctx->hdrs[i]->active = false; mutt_message(ngettext("Marking %d message deleted...", "Marking %d messages deleted...", rc), rc); } } #ifdef USE_HCACHE idata->hcache = imap_hcache_open(idata, NULL); #endif /* save messages with real (non-flag) changes */ for (int i = 0; i < ctx->msgcount; i++) { h = ctx->hdrs[i]; if (h->deleted) { imap_cache_del(idata, h); #ifdef USE_HCACHE imap_hcache_del(idata, HEADER_DATA(h)->uid); #endif } if (h->active && h->changed) { #ifdef USE_HCACHE imap_hcache_put(idata, h); #endif /* if the message has been rethreaded or attachments have been deleted * we delete the message and reupload it. * This works better if we're expunging, of course. */ if ((h->env && (h->env->refs_changed || h->env->irt_changed)) || h->attach_del || h->xlabel_changed) { /* L10N: The plural is choosen by the last %d, i.e. the total number */ mutt_message(ngettext("Saving changed message... [%d/%d]", "Saving changed messages... [%d/%d]", ctx->msgcount), i + 1, ctx->msgcount); if (!appendctx) appendctx = mx_mbox_open(ctx->path, MUTT_APPEND | MUTT_QUIET, NULL); if (!appendctx) mutt_debug(1, "Error opening mailbox in append mode\n"); else mutt_save_message_ctx(h, 1, 0, 0, appendctx); h->xlabel_changed = false; } } } #ifdef USE_HCACHE imap_hcache_close(idata); #endif /* presort here to avoid doing 10 resorts in imap_exec_msgset */ oldsort = Sort; if (Sort != SORT_ORDER) { hdrs = ctx->hdrs; ctx->hdrs = mutt_mem_malloc(ctx->msgcount * sizeof(struct Header *)); memcpy(ctx->hdrs, hdrs, ctx->msgcount * sizeof(struct Header *)); Sort = SORT_ORDER; qsort(ctx->hdrs, ctx->msgcount, sizeof(struct Header *), mutt_get_sort_func(SORT_ORDER)); } rc = sync_helper(idata, MUTT_ACL_DELETE, MUTT_DELETED, "\\Deleted"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_WRITE, MUTT_FLAG, "\\Flagged"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_WRITE, MUTT_OLD, "Old"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_SEEN, MUTT_READ, "\\Seen"); if (rc >= 0) rc |= sync_helper(idata, MUTT_ACL_WRITE, MUTT_REPLIED, "\\Answered"); if (oldsort != Sort) { Sort = oldsort; FREE(&ctx->hdrs); ctx->hdrs = hdrs; } /* Flush the queued flags if any were changed in sync_helper. */ if (rc > 0) if (imap_exec(idata, NULL, 0) != IMAP_CMD_OK) rc = -1; if (rc < 0) { if (ctx->closing) { if (mutt_yesorno(_("Error saving flags. Close anyway?"), 0) == MUTT_YES) { rc = 0; idata->state = IMAP_AUTHENTICATED; goto out; } } else mutt_error(_("Error saving flags")); rc = -1; goto out; } /* Update local record of server state to reflect the synchronization just * completed. imap_read_headers always overwrites hcache-origin flags, so * there is no need to mutate the hcache after flag-only changes. */ for (int i = 0; i < ctx->msgcount; i++) { HEADER_DATA(ctx->hdrs[i])->deleted = ctx->hdrs[i]->deleted; HEADER_DATA(ctx->hdrs[i])->flagged = ctx->hdrs[i]->flagged; HEADER_DATA(ctx->hdrs[i])->old = ctx->hdrs[i]->old; HEADER_DATA(ctx->hdrs[i])->read = ctx->hdrs[i]->read; HEADER_DATA(ctx->hdrs[i])->replied = ctx->hdrs[i]->replied; ctx->hdrs[i]->changed = false; } ctx->changed = false; /* We must send an EXPUNGE command if we're not closing. */ if (expunge && !(ctx->closing) && mutt_bit_isset(ctx->rights, MUTT_ACL_DELETE)) { mutt_message(_("Expunging messages from server...")); /* Set expunge bit so we don't get spurious reopened messages */ idata->reopen |= IMAP_EXPUNGE_EXPECTED; if (imap_exec(idata, "EXPUNGE", 0) != 0) { idata->reopen &= ~IMAP_EXPUNGE_EXPECTED; imap_error(_("imap_sync_mailbox: EXPUNGE failed"), idata->buf); rc = -1; goto out; } idata->reopen &= ~IMAP_EXPUNGE_EXPECTED; } if (expunge && ctx->closing) { imap_exec(idata, "CLOSE", IMAP_CMD_QUEUE); idata->state = IMAP_AUTHENTICATED; } if (MessageCacheClean) imap_cache_clean(idata); rc = 0; out: if (appendctx) { mx_fastclose_mailbox(appendctx); FREE(&appendctx); } return rc; } /** * imap_tags_edit - Implements MxOps::tags_edit() */ static int imap_tags_edit(struct Context *ctx, const char *tags, char *buf, size_t buflen) { char *new = NULL; char *checker = NULL; struct ImapData *idata = (struct ImapData *) ctx->data; /* Check for \* flags capability */ if (!imap_has_flag(&idata->flags, NULL)) { mutt_error(_("IMAP server doesn't support custom flags")); return -1; } *buf = '\0'; if (tags) strncpy(buf, tags, buflen); if (mutt_get_field("Tags: ", buf, buflen, 0) != 0) return -1; /* each keyword must be atom defined by rfc822 as: * * atom = 1*<any CHAR except specials, SPACE and CTLs> * CHAR = ( 0.-127. ) * specials = "(" / ")" / "<" / ">" / "@" * / "," / ";" / ":" / "\" / <"> * / "." / "[" / "]" * SPACE = ( 32. ) * CTLS = ( 0.-31., 127.) * * And must be separated by one space. */ new = buf; checker = buf; SKIPWS(checker); while (*checker != '\0') { if (*checker < 32 || *checker >= 127 || // We allow space because it's the separator *checker == 40 || // ( *checker == 41 || // ) *checker == 60 || // < *checker == 62 || // > *checker == 64 || // @ *checker == 44 || // , *checker == 59 || // ; *checker == 58 || // : *checker == 92 || // backslash *checker == 34 || // " *checker == 46 || // . *checker == 91 || // [ *checker == 93) // ] { mutt_error(_("Invalid IMAP flags")); return 0; } /* Skip duplicate space */ while (*checker == ' ' && *(checker + 1) == ' ') checker++; /* copy char to new and go the next one */ *new ++ = *checker++; } *new = '\0'; new = buf; /* rewind */ mutt_str_remove_trailing_ws(new); if (mutt_str_strcmp(tags, buf) == 0) return 0; return 1; } /** * imap_tags_commit - Implements MxOps::tags_commit() * * This method update the server flags on the server by * removing the last know custom flags of a header * and adds the local flags * * If everything success we push the local flags to the * last know custom flags (flags_remote). * * Also this method check that each flags is support by the server * first and remove unsupported one. */ static int imap_tags_commit(struct Context *ctx, struct Header *hdr, char *buf) { struct Buffer *cmd = NULL; char uid[11]; struct ImapData *idata = ctx->data; if (*buf == '\0') buf = NULL; if (!mutt_bit_isset(idata->ctx->rights, MUTT_ACL_WRITE)) return 0; snprintf(uid, sizeof(uid), "%u", HEADER_DATA(hdr)->uid); /* Remove old custom flags */ if (HEADER_DATA(hdr)->flags_remote) { cmd = mutt_buffer_new(); if (!cmd) { mutt_debug(1, "unable to allocate buffer\n"); return -1; } cmd->dptr = cmd->data; mutt_buffer_addstr(cmd, "UID STORE "); mutt_buffer_addstr(cmd, uid); mutt_buffer_addstr(cmd, " -FLAGS.SILENT ("); mutt_buffer_addstr(cmd, HEADER_DATA(hdr)->flags_remote); mutt_buffer_addstr(cmd, ")"); /* Should we return here, or we are fine and we could * continue to add new flags * */ if (imap_exec(idata, cmd->data, 0) != 0) { mutt_buffer_free(&cmd); return -1; } mutt_buffer_free(&cmd); } /* Add new custom flags */ if (buf) { cmd = mutt_buffer_new(); if (!cmd) { mutt_debug(1, "fail to remove old flags\n"); return -1; } cmd->dptr = cmd->data; mutt_buffer_addstr(cmd, "UID STORE "); mutt_buffer_addstr(cmd, uid); mutt_buffer_addstr(cmd, " +FLAGS.SILENT ("); mutt_buffer_addstr(cmd, buf); mutt_buffer_addstr(cmd, ")"); if (imap_exec(idata, cmd->data, 0) != 0) { mutt_debug(1, "fail to add new flags\n"); mutt_buffer_free(&cmd); return -1; } mutt_buffer_free(&cmd); } /* We are good sync them */ mutt_debug(1, "NEW TAGS: %d\n", buf); driver_tags_replace(&hdr->tags, buf); FREE(&HEADER_DATA(hdr)->flags_remote); HEADER_DATA(hdr)->flags_remote = driver_tags_get_with_hidden(&hdr->tags); return 0; } // clang-format off /** * struct mx_imap_ops - Mailbox callback functions for IMAP mailboxes */ struct MxOps mx_imap_ops = { .mbox_open = imap_mbox_open, .mbox_open_append = imap_mbox_open_append, .mbox_check = imap_mbox_check, .mbox_sync = NULL, /* imap syncing is handled by imap_sync_mailbox */ .mbox_close = imap_mbox_close, .msg_open = imap_msg_open, .msg_open_new = imap_msg_open_new, .msg_commit = imap_msg_commit, .msg_close = imap_msg_close, .tags_edit = imap_tags_edit, .tags_commit = imap_tags_commit, }; // clang-format on
./CrossVul/dataset_final_sorted/CWE-77/c/bad_251_2
crossvul-cpp_data_good_251_1
/** * @file * Send/receive commands to/from an IMAP server * * @authors * Copyright (C) 1996-1998,2010,2012 Michael R. Elkins <me@mutt.org> * Copyright (C) 1996-1999 Brandon Long <blong@fiction.net> * Copyright (C) 1999-2009,2011 Brendan Cully <brendan@kublai.com> * * @copyright * 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, see <http://www.gnu.org/licenses/>. */ /** * @page imap_command Send/receive commands to/from an IMAP server * * Send/receive commands to/from an IMAP server */ #include "config.h" #include <ctype.h> #include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "imap_private.h" #include "mutt/mutt.h" #include "conn/conn.h" #include "buffy.h" #include "context.h" #include "globals.h" #include "header.h" #include "imap/imap.h" #include "mailbox.h" #include "message.h" #include "mutt_account.h" #include "mutt_menu.h" #include "mutt_socket.h" #include "mx.h" #include "options.h" #include "protos.h" #include "url.h" #define IMAP_CMD_BUFSIZE 512 /** * Capabilities - Server capabilities strings that we understand * * @note This must be kept in the same order as ImapCaps. * * @note Gmail documents one string but use another, so we support both. */ static const char *const Capabilities[] = { "IMAP4", "IMAP4rev1", "STATUS", "ACL", "NAMESPACE", "AUTH=CRAM-MD5", "AUTH=GSSAPI", "AUTH=ANONYMOUS", "STARTTLS", "LOGINDISABLED", "IDLE", "SASL-IR", "ENABLE", "X-GM-EXT-1", "X-GM-EXT1", NULL, }; /** * cmd_queue_full - Is the IMAP command queue full? * @param idata Server data * @retval true Queue is full */ static bool cmd_queue_full(struct ImapData *idata) { if ((idata->nextcmd + 1) % idata->cmdslots == idata->lastcmd) return true; return false; } /** * cmd_new - Create and queue a new command control block * @param idata IMAP data * @retval NULL if the pipeline is full * @retval ptr New command */ static struct ImapCommand *cmd_new(struct ImapData *idata) { struct ImapCommand *cmd = NULL; if (cmd_queue_full(idata)) { mutt_debug(3, "IMAP command queue full\n"); return NULL; } cmd = idata->cmds + idata->nextcmd; idata->nextcmd = (idata->nextcmd + 1) % idata->cmdslots; snprintf(cmd->seq, sizeof(cmd->seq), "a%04u", idata->seqno++); if (idata->seqno > 9999) idata->seqno = 0; cmd->state = IMAP_CMD_NEW; return cmd; } /** * cmd_queue - Add a IMAP command to the queue * @param idata Server data * @param cmdstr Command string * @param flags Server flags, e.g. #IMAP_CMD_POLL * @retval 0 Success * @retval <0 Failure, e.g. #IMAP_CMD_BAD * * If the queue is full, attempts to drain it. */ static int cmd_queue(struct ImapData *idata, const char *cmdstr, int flags) { if (cmd_queue_full(idata)) { mutt_debug(3, "Draining IMAP command pipeline\n"); const int rc = imap_exec(idata, NULL, IMAP_CMD_FAIL_OK | (flags & IMAP_CMD_POLL)); if (rc < 0 && rc != -2) return rc; } struct ImapCommand *cmd = cmd_new(idata); if (!cmd) return IMAP_CMD_BAD; if (mutt_buffer_printf(idata->cmdbuf, "%s %s\r\n", cmd->seq, cmdstr) < 0) return IMAP_CMD_BAD; return 0; } /** * cmd_handle_fatal - When ImapData is in fatal state, do what we can * @param idata Server data */ static void cmd_handle_fatal(struct ImapData *idata) { idata->status = IMAP_FATAL; if ((idata->state >= IMAP_SELECTED) && (idata->reopen & IMAP_REOPEN_ALLOW)) { mx_fastclose_mailbox(idata->ctx); mutt_socket_close(idata->conn); mutt_error(_("Mailbox %s@%s closed"), idata->conn->account.login, idata->conn->account.host); idata->state = IMAP_DISCONNECTED; } imap_close_connection(idata); if (!idata->recovering) { idata->recovering = true; if (imap_conn_find(&idata->conn->account, 0)) mutt_clear_error(); idata->recovering = false; } } /** * cmd_start - Start a new IMAP command * @param idata Server data * @param cmdstr Command string * @param flags Command flags, e.g. #IMAP_CMD_QUEUE * @retval 0 Success * @retval <0 Failure, e.g. #IMAP_CMD_BAD */ static int cmd_start(struct ImapData *idata, const char *cmdstr, int flags) { int rc; if (idata->status == IMAP_FATAL) { cmd_handle_fatal(idata); return -1; } if (cmdstr && ((rc = cmd_queue(idata, cmdstr, flags)) < 0)) return rc; if (flags & IMAP_CMD_QUEUE) return 0; if (idata->cmdbuf->dptr == idata->cmdbuf->data) return IMAP_CMD_BAD; rc = mutt_socket_send_d(idata->conn, idata->cmdbuf->data, (flags & IMAP_CMD_PASS) ? IMAP_LOG_PASS : IMAP_LOG_CMD); idata->cmdbuf->dptr = idata->cmdbuf->data; /* unidle when command queue is flushed */ if (idata->state == IMAP_IDLE) idata->state = IMAP_SELECTED; return (rc < 0) ? IMAP_CMD_BAD : 0; } /** * cmd_status - parse response line for tagged OK/NO/BAD * @param s Status string from server * @retval 0 Success * @retval <0 Failure, e.g. #IMAP_CMD_BAD */ static int cmd_status(const char *s) { s = imap_next_word((char *) s); if (mutt_str_strncasecmp("OK", s, 2) == 0) return IMAP_CMD_OK; if (mutt_str_strncasecmp("NO", s, 2) == 0) return IMAP_CMD_NO; return IMAP_CMD_BAD; } /** * cmd_parse_expunge - Parse expunge command * @param idata Server data * @param s String containing MSN of message to expunge * * cmd_parse_expunge: mark headers with new sequence ID and mark idata to be * reopened at our earliest convenience */ static void cmd_parse_expunge(struct ImapData *idata, const char *s) { unsigned int exp_msn; struct Header *h = NULL; mutt_debug(2, "Handling EXPUNGE\n"); if (mutt_str_atoui(s, &exp_msn) < 0 || exp_msn < 1 || exp_msn > idata->max_msn) return; h = idata->msn_index[exp_msn - 1]; if (h) { /* imap_expunge_mailbox() will rewrite h->index. * It needs to resort using SORT_ORDER anyway, so setting to INT_MAX * makes the code simpler and possibly more efficient. */ h->index = INT_MAX; HEADER_DATA(h)->msn = 0; } /* decrement seqno of those above. */ for (unsigned int cur = exp_msn; cur < idata->max_msn; cur++) { h = idata->msn_index[cur]; if (h) HEADER_DATA(h)->msn--; idata->msn_index[cur - 1] = h; } idata->msn_index[idata->max_msn - 1] = NULL; idata->max_msn--; idata->reopen |= IMAP_EXPUNGE_PENDING; } /** * cmd_parse_fetch - Load fetch response into ImapData * @param idata Server data * @param s String containing MSN of message to fetch * * Currently only handles unanticipated FETCH responses, and only FLAGS data. * We get these if another client has changed flags for a mailbox we've * selected. Of course, a lot of code here duplicates code in message.c. */ static void cmd_parse_fetch(struct ImapData *idata, char *s) { unsigned int msn, uid; struct Header *h = NULL; int server_changes = 0; mutt_debug(3, "Handling FETCH\n"); if (mutt_str_atoui(s, &msn) < 0 || msn < 1 || msn > idata->max_msn) { mutt_debug(3, "#1 FETCH response ignored for this message\n"); return; } h = idata->msn_index[msn - 1]; if (!h || !h->active) { mutt_debug(3, "#2 FETCH response ignored for this message\n"); return; } mutt_debug(2, "Message UID %u updated\n", HEADER_DATA(h)->uid); /* skip FETCH */ s = imap_next_word(s); s = imap_next_word(s); if (*s != '(') { mutt_debug(1, "Malformed FETCH response\n"); return; } s++; while (*s) { SKIPWS(s); if (mutt_str_strncasecmp("FLAGS", s, 5) == 0) { imap_set_flags(idata, h, s, &server_changes); if (server_changes) { /* If server flags could conflict with neomutt's flags, reopen the mailbox. */ if (h->changed) idata->reopen |= IMAP_EXPUNGE_PENDING; else idata->check_status = IMAP_FLAGS_PENDING; } return; } else if (mutt_str_strncasecmp("UID", s, 3) == 0) { s += 3; SKIPWS(s); if (mutt_str_atoui(s, &uid) < 0) { mutt_debug(2, "Illegal UID. Skipping update.\n"); return; } if (uid != HEADER_DATA(h)->uid) { mutt_debug(2, "FETCH UID vs MSN mismatch. Skipping update.\n"); return; } s = imap_next_word(s); } else if (*s == ')') s++; /* end of request */ else if (*s) { mutt_debug(2, "Only handle FLAGS updates\n"); return; } } } /** * cmd_parse_capability - set capability bits according to CAPABILITY response * @param idata Server data * @param s Command string with capabilities */ static void cmd_parse_capability(struct ImapData *idata, char *s) { mutt_debug(3, "Handling CAPABILITY\n"); s = imap_next_word(s); char *bracket = strchr(s, ']'); if (bracket) *bracket = '\0'; FREE(&idata->capstr); idata->capstr = mutt_str_strdup(s); memset(idata->capabilities, 0, sizeof(idata->capabilities)); while (*s) { for (int i = 0; i < CAPMAX; i++) { if (mutt_str_word_casecmp(Capabilities[i], s) == 0) { mutt_bit_set(idata->capabilities, i); mutt_debug(4, " Found capability \"%s\": %d\n", Capabilities[i], i); break; } } s = imap_next_word(s); } } /** * cmd_parse_list - Parse a server LIST command (list mailboxes) * @param idata Server data * @param s Command string with folder list */ static void cmd_parse_list(struct ImapData *idata, char *s) { struct ImapList *list = NULL; struct ImapList lb; char delimbuf[5]; /* worst case: "\\"\0 */ unsigned int litlen; if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST) list = (struct ImapList *) idata->cmddata; else list = &lb; memset(list, 0, sizeof(struct ImapList)); /* flags */ s = imap_next_word(s); if (*s != '(') { mutt_debug(1, "Bad LIST response\n"); return; } s++; while (*s) { if (mutt_str_strncasecmp(s, "\\NoSelect", 9) == 0) list->noselect = true; else if (mutt_str_strncasecmp(s, "\\NoInferiors", 12) == 0) list->noinferiors = true; /* See draft-gahrns-imap-child-mailbox-?? */ else if (mutt_str_strncasecmp(s, "\\HasNoChildren", 14) == 0) list->noinferiors = true; s = imap_next_word(s); if (*(s - 2) == ')') break; } /* Delimiter */ if (mutt_str_strncasecmp(s, "NIL", 3) != 0) { delimbuf[0] = '\0'; mutt_str_strcat(delimbuf, 5, s); imap_unquote_string(delimbuf); list->delim = delimbuf[0]; } /* Name */ s = imap_next_word(s); /* Notes often responds with literals here. We need a real tokenizer. */ if (imap_get_literal_count(s, &litlen) == 0) { if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE) { idata->status = IMAP_FATAL; return; } list->name = idata->buf; } else { imap_unmunge_mbox_name(idata, s); list->name = s; } if (list->name[0] == '\0') { idata->delim = list->delim; mutt_debug(3, "Root delimiter: %c\n", idata->delim); } } /** * cmd_parse_lsub - Parse a server LSUB (list subscribed mailboxes) * @param idata Server data * @param s Command string with folder list */ static void cmd_parse_lsub(struct ImapData *idata, char *s) { char buf[STRING]; char errstr[STRING]; struct Buffer err, token; struct Url url; struct ImapList list; if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST) { /* caller will handle response itself */ cmd_parse_list(idata, s); return; } if (!ImapCheckSubscribed) return; idata->cmdtype = IMAP_CT_LIST; idata->cmddata = &list; cmd_parse_list(idata, s); idata->cmddata = NULL; /* noselect is for a gmail quirk (#3445) */ if (!list.name || list.noselect) return; mutt_debug(3, "Subscribing to %s\n", list.name); mutt_str_strfcpy(buf, "mailboxes \"", sizeof(buf)); mutt_account_tourl(&idata->conn->account, &url); /* escape \ and " */ imap_quote_string(errstr, sizeof(errstr), list.name, true); url.path = errstr + 1; url.path[strlen(url.path) - 1] = '\0'; if (mutt_str_strcmp(url.user, ImapUser) == 0) url.user = NULL; url_tostring(&url, buf + 11, sizeof(buf) - 11, 0); mutt_str_strcat(buf, sizeof(buf), "\""); mutt_buffer_init(&token); mutt_buffer_init(&err); err.data = errstr; err.dsize = sizeof(errstr); if (mutt_parse_rc_line(buf, &token, &err)) mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr); FREE(&token.data); } /** * cmd_parse_myrights - Set rights bits according to MYRIGHTS response * @param idata Server data * @param s Command string with rights info */ static void cmd_parse_myrights(struct ImapData *idata, const char *s) { mutt_debug(2, "Handling MYRIGHTS\n"); s = imap_next_word((char *) s); s = imap_next_word((char *) s); /* zero out current rights set */ memset(idata->ctx->rights, 0, sizeof(idata->ctx->rights)); while (*s && !isspace((unsigned char) *s)) { switch (*s) { case 'a': mutt_bit_set(idata->ctx->rights, MUTT_ACL_ADMIN); break; case 'e': mutt_bit_set(idata->ctx->rights, MUTT_ACL_EXPUNGE); break; case 'i': mutt_bit_set(idata->ctx->rights, MUTT_ACL_INSERT); break; case 'k': mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE); break; case 'l': mutt_bit_set(idata->ctx->rights, MUTT_ACL_LOOKUP); break; case 'p': mutt_bit_set(idata->ctx->rights, MUTT_ACL_POST); break; case 'r': mutt_bit_set(idata->ctx->rights, MUTT_ACL_READ); break; case 's': mutt_bit_set(idata->ctx->rights, MUTT_ACL_SEEN); break; case 't': mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE); break; case 'w': mutt_bit_set(idata->ctx->rights, MUTT_ACL_WRITE); break; case 'x': mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELMX); break; /* obsolete rights */ case 'c': mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE); mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELMX); break; case 'd': mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE); mutt_bit_set(idata->ctx->rights, MUTT_ACL_EXPUNGE); break; default: mutt_debug(1, "Unknown right: %c\n", *s); } s++; } } /** * cmd_parse_search - store SEARCH response for later use * @param idata Server data * @param s Command string with search results */ static void cmd_parse_search(struct ImapData *idata, const char *s) { unsigned int uid; struct Header *h = NULL; mutt_debug(2, "Handling SEARCH\n"); while ((s = imap_next_word((char *) s)) && *s != '\0') { if (mutt_str_atoui(s, &uid) < 0) continue; h = (struct Header *) mutt_hash_int_find(idata->uid_hash, uid); if (h) h->matched = true; } } /** * cmd_parse_status - Parse status from server * @param idata Server data * @param s Command string with status info * * first cut: just do buffy update. Later we may wish to cache all mailbox * information, even that not desired by buffy */ static void cmd_parse_status(struct ImapData *idata, char *s) { char *value = NULL; struct Buffy *inc = NULL; struct ImapMbox mx; struct ImapStatus *status = NULL; unsigned int olduv, oldun; unsigned int litlen; short new = 0; short new_msg_count = 0; char *mailbox = imap_next_word(s); /* We need a real tokenizer. */ if (imap_get_literal_count(mailbox, &litlen) == 0) { if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE) { idata->status = IMAP_FATAL; return; } mailbox = idata->buf; s = mailbox + litlen; *s = '\0'; s++; SKIPWS(s); } else { s = imap_next_word(mailbox); *(s - 1) = '\0'; imap_unmunge_mbox_name(idata, mailbox); } status = imap_mboxcache_get(idata, mailbox, 1); olduv = status->uidvalidity; oldun = status->uidnext; if (*s++ != '(') { mutt_debug(1, "Error parsing STATUS\n"); return; } while (*s && *s != ')') { value = imap_next_word(s); errno = 0; const unsigned long ulcount = strtoul(value, &value, 10); if (((errno == ERANGE) && (ulcount == ULONG_MAX)) || ((unsigned int) ulcount != ulcount)) { mutt_debug(1, "Error parsing STATUS number\n"); return; } const unsigned int count = (unsigned int) ulcount; if (mutt_str_strncmp("MESSAGES", s, 8) == 0) { status->messages = count; new_msg_count = 1; } else if (mutt_str_strncmp("RECENT", s, 6) == 0) status->recent = count; else if (mutt_str_strncmp("UIDNEXT", s, 7) == 0) status->uidnext = count; else if (mutt_str_strncmp("UIDVALIDITY", s, 11) == 0) status->uidvalidity = count; else if (mutt_str_strncmp("UNSEEN", s, 6) == 0) status->unseen = count; s = value; if (*s && *s != ')') s = imap_next_word(s); } mutt_debug(3, "%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n", status->name, status->uidvalidity, status->uidnext, status->messages, status->recent, status->unseen); /* caller is prepared to handle the result herself */ if (idata->cmddata && idata->cmdtype == IMAP_CT_STATUS) { memcpy(idata->cmddata, status, sizeof(struct ImapStatus)); return; } mutt_debug(3, "Running default STATUS handler\n"); /* should perhaps move this code back to imap_buffy_check */ for (inc = Incoming; inc; inc = inc->next) { if (inc->magic != MUTT_IMAP) continue; if (imap_parse_path(inc->path, &mx) < 0) { mutt_debug(1, "Error parsing mailbox %s, skipping\n", inc->path); continue; } if (imap_account_match(&idata->conn->account, &mx.account)) { if (mx.mbox) { value = mutt_str_strdup(mx.mbox); imap_fix_path(idata, mx.mbox, value, mutt_str_strlen(value) + 1); FREE(&mx.mbox); } else value = mutt_str_strdup("INBOX"); if (value && (imap_mxcmp(mailbox, value) == 0)) { mutt_debug(3, "Found %s in buffy list (OV: %u ON: %u U: %d)\n", mailbox, olduv, oldun, status->unseen); if (MailCheckRecent) { if (olduv && olduv == status->uidvalidity) { if (oldun < status->uidnext) new = (status->unseen > 0); } else if (!olduv && !oldun) { /* first check per session, use recent. might need a flag for this. */ new = (status->recent > 0); } else new = (status->unseen > 0); } else new = (status->unseen > 0); #ifdef USE_SIDEBAR if ((inc->new != new) || (inc->msg_count != status->messages) || (inc->msg_unread != status->unseen)) { mutt_menu_set_current_redraw(REDRAW_SIDEBAR); } #endif inc->new = new; if (new_msg_count) inc->msg_count = status->messages; inc->msg_unread = status->unseen; if (inc->new) { /* force back to keep detecting new mail until the mailbox is opened */ status->uidnext = oldun; } FREE(&value); return; } FREE(&value); } FREE(&mx.mbox); } } /** * cmd_parse_enabled - Record what the server has enabled * @param idata Server data * @param s Command string containing acceptable encodings */ static void cmd_parse_enabled(struct ImapData *idata, const char *s) { mutt_debug(2, "Handling ENABLED\n"); while ((s = imap_next_word((char *) s)) && *s != '\0') { if ((mutt_str_strncasecmp(s, "UTF8=ACCEPT", 11) == 0) || (mutt_str_strncasecmp(s, "UTF8=ONLY", 9) == 0)) { idata->unicode = 1; } } } /** * cmd_handle_untagged - fallback parser for otherwise unhandled messages * @param idata Server data * @retval 0 Success * @retval -1 Failure */ static int cmd_handle_untagged(struct ImapData *idata) { unsigned int count = 0; char *s = imap_next_word(idata->buf); char *pn = imap_next_word(s); if ((idata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s)) { pn = s; s = imap_next_word(s); /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the * connection, so update that one. */ if (mutt_str_strncasecmp("EXISTS", s, 6) == 0) { mutt_debug(2, "Handling EXISTS\n"); /* new mail arrived */ if (mutt_str_atoui(pn, &count) < 0) { mutt_debug(1, "Malformed EXISTS: '%s'\n", pn); } if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn) { /* Notes 6.0.3 has a tendency to report fewer messages exist than * it should. */ mutt_debug(1, "Message count is out of sync\n"); return 0; } /* at least the InterChange server sends EXISTS messages freely, * even when there is no new mail */ else if (count == idata->max_msn) mutt_debug(3, "superfluous EXISTS message.\n"); else { if (!(idata->reopen & IMAP_EXPUNGE_PENDING)) { mutt_debug(2, "New mail in %s - %d messages total.\n", idata->mailbox, count); idata->reopen |= IMAP_NEWMAIL_PENDING; } idata->new_mail_count = count; } } /* pn vs. s: need initial seqno */ else if (mutt_str_strncasecmp("EXPUNGE", s, 7) == 0) cmd_parse_expunge(idata, pn); else if (mutt_str_strncasecmp("FETCH", s, 5) == 0) cmd_parse_fetch(idata, pn); } else if (mutt_str_strncasecmp("CAPABILITY", s, 10) == 0) cmd_parse_capability(idata, s); else if (mutt_str_strncasecmp("OK [CAPABILITY", s, 14) == 0) cmd_parse_capability(idata, pn); else if (mutt_str_strncasecmp("OK [CAPABILITY", pn, 14) == 0) cmd_parse_capability(idata, imap_next_word(pn)); else if (mutt_str_strncasecmp("LIST", s, 4) == 0) cmd_parse_list(idata, s); else if (mutt_str_strncasecmp("LSUB", s, 4) == 0) cmd_parse_lsub(idata, s); else if (mutt_str_strncasecmp("MYRIGHTS", s, 8) == 0) cmd_parse_myrights(idata, s); else if (mutt_str_strncasecmp("SEARCH", s, 6) == 0) cmd_parse_search(idata, s); else if (mutt_str_strncasecmp("STATUS", s, 6) == 0) cmd_parse_status(idata, s); else if (mutt_str_strncasecmp("ENABLED", s, 7) == 0) cmd_parse_enabled(idata, s); else if (mutt_str_strncasecmp("BYE", s, 3) == 0) { mutt_debug(2, "Handling BYE\n"); /* check if we're logging out */ if (idata->status == IMAP_BYE) return 0; /* server shut down our connection */ s += 3; SKIPWS(s); mutt_error("%s", s); cmd_handle_fatal(idata); return -1; } else if (ImapServernoise && (mutt_str_strncasecmp("NO", s, 2) == 0)) { mutt_debug(2, "Handling untagged NO\n"); /* Display the warning message from the server */ mutt_error("%s", s + 3); } return 0; } /** * imap_cmd_start - Given an IMAP command, send it to the server * @param idata Server data * @param cmdstr Command string to send * @retval 0 Success * @retval <0 Failure, e.g. #IMAP_CMD_BAD * * If cmdstr is NULL, sends queued commands. */ int imap_cmd_start(struct ImapData *idata, const char *cmdstr) { return cmd_start(idata, cmdstr, 0); } /** * imap_cmd_step - Reads server responses from an IMAP command * @param idata Server data * @retval 0 Success * @retval <0 Failure, e.g. #IMAP_CMD_BAD * * detects tagged completion response, handles untagged messages, can read * arbitrarily large strings (using malloc, so don't make it _too_ large!). */ int imap_cmd_step(struct ImapData *idata) { size_t len = 0; int c; int rc; int stillrunning = 0; struct ImapCommand *cmd = NULL; if (idata->status == IMAP_FATAL) { cmd_handle_fatal(idata); return IMAP_CMD_BAD; } /* read into buffer, expanding buffer as necessary until we have a full * line */ do { if (len == idata->blen) { mutt_mem_realloc(&idata->buf, idata->blen + IMAP_CMD_BUFSIZE); idata->blen = idata->blen + IMAP_CMD_BUFSIZE; mutt_debug(3, "grew buffer to %u bytes\n", idata->blen); } /* back up over '\0' */ if (len) len--; c = mutt_socket_readln(idata->buf + len, idata->blen - len, idata->conn); if (c <= 0) { mutt_debug(1, "Error reading server response.\n"); cmd_handle_fatal(idata); return IMAP_CMD_BAD; } len += c; } /* if we've read all the way to the end of the buffer, we haven't read a * full line (mutt_socket_readln strips the \r, so we always have at least * one character free when we've read a full line) */ while (len == idata->blen); /* don't let one large string make cmd->buf hog memory forever */ if ((idata->blen > IMAP_CMD_BUFSIZE) && (len <= IMAP_CMD_BUFSIZE)) { mutt_mem_realloc(&idata->buf, IMAP_CMD_BUFSIZE); idata->blen = IMAP_CMD_BUFSIZE; mutt_debug(3, "shrank buffer to %u bytes\n", idata->blen); } idata->lastread = time(NULL); /* handle untagged messages. The caller still gets its shot afterwards. */ if (((mutt_str_strncmp(idata->buf, "* ", 2) == 0) || (mutt_str_strncmp(imap_next_word(idata->buf), "OK [", 4) == 0)) && cmd_handle_untagged(idata)) { return IMAP_CMD_BAD; } /* server demands a continuation response from us */ if (idata->buf[0] == '+') return IMAP_CMD_RESPOND; /* Look for tagged command completions. * * Some response handlers can end up recursively calling * imap_cmd_step() and end up handling all tagged command * completions. * (e.g. FETCH->set_flag->set_header_color->~h pattern match.) * * Other callers don't even create an idata->cmds entry. * * For both these cases, we default to returning OK */ rc = IMAP_CMD_OK; c = idata->lastcmd; do { cmd = &idata->cmds[c]; if (cmd->state == IMAP_CMD_NEW) { if (mutt_str_strncmp(idata->buf, cmd->seq, SEQLEN) == 0) { if (!stillrunning) { /* first command in queue has finished - move queue pointer up */ idata->lastcmd = (idata->lastcmd + 1) % idata->cmdslots; } cmd->state = cmd_status(idata->buf); /* bogus - we don't know which command result to return here. Caller * should provide a tag. */ rc = cmd->state; } else stillrunning++; } c = (c + 1) % idata->cmdslots; } while (c != idata->nextcmd); if (stillrunning) rc = IMAP_CMD_CONTINUE; else { mutt_debug(3, "IMAP queue drained\n"); imap_cmd_finish(idata); } return rc; } /** * imap_code - Was the command successful * @param s IMAP command status * @retval 1 Command result was OK * @retval 0 If NO or BAD */ bool imap_code(const char *s) { return (cmd_status(s) == IMAP_CMD_OK); } /** * imap_cmd_trailer - Extra information after tagged command response if any * @param idata Server data * @retval ptr Extra command information (pointer into idata->buf) * @retval "" Error (static string) */ const char *imap_cmd_trailer(struct ImapData *idata) { static const char *notrailer = ""; const char *s = idata->buf; if (!s) { mutt_debug(2, "not a tagged response\n"); return notrailer; } s = imap_next_word((char *) s); if (!s || ((mutt_str_strncasecmp(s, "OK", 2) != 0) && (mutt_str_strncasecmp(s, "NO", 2) != 0) && (mutt_str_strncasecmp(s, "BAD", 3) != 0))) { mutt_debug(2, "not a command completion: %s\n", idata->buf); return notrailer; } s = imap_next_word((char *) s); if (!s) return notrailer; return s; } /** * imap_exec - Execute a command and wait for the response from the server * @param idata IMAP data * @param cmdstr Command to execute * @param flags Flags (see below) * @retval 0 Success * @retval -1 Failure * @retval -2 OK Failure * * Also, handle untagged responses. * * Flags: * * IMAP_CMD_FAIL_OK: the calling procedure can handle failure. * This is used for checking for a mailbox on append and login * * IMAP_CMD_PASS: command contains a password. Suppress logging. * * IMAP_CMD_QUEUE: only queue command, do not execute. * * IMAP_CMD_POLL: poll the socket for a response before running imap_cmd_step. */ int imap_exec(struct ImapData *idata, const char *cmdstr, int flags) { int rc; rc = cmd_start(idata, cmdstr, flags); if (rc < 0) { cmd_handle_fatal(idata); return -1; } if (flags & IMAP_CMD_QUEUE) return 0; if ((flags & IMAP_CMD_POLL) && (ImapPollTimeout > 0) && (mutt_socket_poll(idata->conn, ImapPollTimeout)) == 0) { mutt_error(_("Connection to %s timed out"), idata->conn->account.host); cmd_handle_fatal(idata); return -1; } /* Allow interruptions, particularly useful if there are network problems. */ mutt_sig_allow_interrupt(1); do rc = imap_cmd_step(idata); while (rc == IMAP_CMD_CONTINUE); mutt_sig_allow_interrupt(0); if (rc == IMAP_CMD_NO && (flags & IMAP_CMD_FAIL_OK)) return -2; if (rc != IMAP_CMD_OK) { if ((flags & IMAP_CMD_FAIL_OK) && idata->status != IMAP_FATAL) return -2; mutt_debug(1, "command failed: %s\n", idata->buf); return -1; } return 0; } /** * imap_cmd_finish - Attempt to perform cleanup * @param idata Server data * * Attempts to perform cleanup (eg fetch new mail if detected, do expunge). * Called automatically by imap_cmd_step(), but may be called at any time. * Called by imap_check_mailbox() just before the index is refreshed, for * instance. */ void imap_cmd_finish(struct ImapData *idata) { if (idata->status == IMAP_FATAL) { cmd_handle_fatal(idata); return; } if (!(idata->state >= IMAP_SELECTED) || idata->ctx->closing) return; if (idata->reopen & IMAP_REOPEN_ALLOW) { unsigned int count = idata->new_mail_count; if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && (idata->reopen & IMAP_NEWMAIL_PENDING) && count > idata->max_msn) { /* read new mail messages */ mutt_debug(2, "Fetching new mail\n"); /* check_status: curs_main uses imap_check_mailbox to detect * whether the index needs updating */ idata->check_status = IMAP_NEWMAIL_PENDING; imap_read_headers(idata, idata->max_msn + 1, count); } else if (idata->reopen & IMAP_EXPUNGE_PENDING) { mutt_debug(2, "Expunging mailbox\n"); imap_expunge_mailbox(idata); /* Detect whether we've gotten unexpected EXPUNGE messages */ if ((idata->reopen & IMAP_EXPUNGE_PENDING) && !(idata->reopen & IMAP_EXPUNGE_EXPECTED)) idata->check_status = IMAP_EXPUNGE_PENDING; idata->reopen &= ~(IMAP_EXPUNGE_PENDING | IMAP_NEWMAIL_PENDING | IMAP_EXPUNGE_EXPECTED); } } idata->status = false; } /** * imap_cmd_idle - Enter the IDLE state * @param idata Server data * @retval 0 Success * @retval <0 Failure, e.g. #IMAP_CMD_BAD */ int imap_cmd_idle(struct ImapData *idata) { int rc; if (cmd_start(idata, "IDLE", IMAP_CMD_POLL) < 0) { cmd_handle_fatal(idata); return -1; } if ((ImapPollTimeout > 0) && (mutt_socket_poll(idata->conn, ImapPollTimeout)) == 0) { mutt_error(_("Connection to %s timed out"), idata->conn->account.host); cmd_handle_fatal(idata); return -1; } do rc = imap_cmd_step(idata); while (rc == IMAP_CMD_CONTINUE); if (rc == IMAP_CMD_RESPOND) { /* successfully entered IDLE state */ idata->state = IMAP_IDLE; /* queue automatic exit when next command is issued */ mutt_buffer_printf(idata->cmdbuf, "DONE\r\n"); rc = IMAP_CMD_OK; } if (rc != IMAP_CMD_OK) { mutt_debug(1, "error starting IDLE\n"); return -1; } return 0; }
./CrossVul/dataset_final_sorted/CWE-77/c/good_251_1
crossvul-cpp_data_bad_1979_0
/*************************************************************************/ /* image_loader_tga.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "image_loader_tga.h" #include "core/error/error_macros.h" #include "core/io/file_access_memory.h" #include "core/os/os.h" #include "core/string/print_string.h" Error ImageLoaderTGA::decode_tga_rle(const uint8_t *p_compressed_buffer, size_t p_pixel_size, uint8_t *p_uncompressed_buffer, size_t p_output_size) { Error error; Vector<uint8_t> pixels; error = pixels.resize(p_pixel_size); if (error != OK) { return error; } uint8_t *pixels_w = pixels.ptrw(); size_t compressed_pos = 0; size_t output_pos = 0; size_t c = 0; size_t count = 0; while (output_pos < p_output_size) { c = p_compressed_buffer[compressed_pos]; compressed_pos += 1; count = (c & 0x7f) + 1; if (c & 0x80) { for (size_t i = 0; i < p_pixel_size; i++) { pixels_w[i] = p_compressed_buffer[compressed_pos]; compressed_pos += 1; } for (size_t i = 0; i < count; i++) { for (size_t j = 0; j < p_pixel_size; j++) { p_uncompressed_buffer[output_pos + j] = pixels_w[j]; } output_pos += p_pixel_size; } } else { count *= p_pixel_size; for (size_t i = 0; i < count; i++) { p_uncompressed_buffer[output_pos] = p_compressed_buffer[compressed_pos]; compressed_pos += 1; output_pos += 1; } } } return OK; } Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buffer, const tga_header_s &p_header, const uint8_t *p_palette, const bool p_is_monochrome) { #define TGA_PUT_PIXEL(r, g, b, a) \ int image_data_ofs = ((y * width) + x); \ image_data_w[image_data_ofs * 4 + 0] = r; \ image_data_w[image_data_ofs * 4 + 1] = g; \ image_data_w[image_data_ofs * 4 + 2] = b; \ image_data_w[image_data_ofs * 4 + 3] = a; uint32_t width = p_header.image_width; uint32_t height = p_header.image_height; tga_origin_e origin = static_cast<tga_origin_e>((p_header.image_descriptor & TGA_ORIGIN_MASK) >> TGA_ORIGIN_SHIFT); uint32_t x_start; int32_t x_step; uint32_t x_end; uint32_t y_start; int32_t y_step; uint32_t y_end; if (origin == TGA_ORIGIN_TOP_LEFT || origin == TGA_ORIGIN_TOP_RIGHT) { y_start = 0; y_step = 1; y_end = height; } else { y_start = height - 1; y_step = -1; y_end = -1; } if (origin == TGA_ORIGIN_TOP_LEFT || origin == TGA_ORIGIN_BOTTOM_LEFT) { x_start = 0; x_step = 1; x_end = width; } else { x_start = width - 1; x_step = -1; x_end = -1; } Vector<uint8_t> image_data; image_data.resize(width * height * sizeof(uint32_t)); uint8_t *image_data_w = image_data.ptrw(); size_t i = 0; uint32_t x = x_start; uint32_t y = y_start; if (p_header.pixel_depth == 8) { if (p_is_monochrome) { while (y != y_end) { while (x != x_end) { uint8_t shade = p_buffer[i]; TGA_PUT_PIXEL(shade, shade, shade, 0xff) x += x_step; i += 1; } x = x_start; y += y_step; } } else { while (y != y_end) { while (x != x_end) { uint8_t index = p_buffer[i]; uint8_t r = 0x00; uint8_t g = 0x00; uint8_t b = 0x00; uint8_t a = 0xff; if (p_header.color_map_depth == 24) { // Due to low-high byte order, the color table must be // read in the same order as image data (little endian) r = (p_palette[(index * 3) + 2]); g = (p_palette[(index * 3) + 1]); b = (p_palette[(index * 3) + 0]); } else { return ERR_INVALID_DATA; } TGA_PUT_PIXEL(r, g, b, a) x += x_step; i += 1; } x = x_start; y += y_step; } } } else if (p_header.pixel_depth == 24) { while (y != y_end) { while (x != x_end) { uint8_t r = p_buffer[i + 2]; uint8_t g = p_buffer[i + 1]; uint8_t b = p_buffer[i + 0]; TGA_PUT_PIXEL(r, g, b, 0xff) x += x_step; i += 3; } x = x_start; y += y_step; } } else if (p_header.pixel_depth == 32) { while (y != y_end) { while (x != x_end) { uint8_t a = p_buffer[i + 3]; uint8_t r = p_buffer[i + 2]; uint8_t g = p_buffer[i + 1]; uint8_t b = p_buffer[i + 0]; TGA_PUT_PIXEL(r, g, b, a) x += x_step; i += 4; } x = x_start; y += y_step; } } p_image->create(width, height, false, Image::FORMAT_RGBA8, image_data); return OK; } Error ImageLoaderTGA::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) { Vector<uint8_t> src_image; int src_image_len = f->get_len(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); ERR_FAIL_COND_V(src_image_len < (int)sizeof(tga_header_s), ERR_FILE_CORRUPT); src_image.resize(src_image_len); Error err = OK; tga_header_s tga_header; tga_header.id_length = f->get_8(); tga_header.color_map_type = f->get_8(); tga_header.image_type = static_cast<tga_type_e>(f->get_8()); tga_header.first_color_entry = f->get_16(); tga_header.color_map_length = f->get_16(); tga_header.color_map_depth = f->get_8(); tga_header.x_origin = f->get_16(); tga_header.y_origin = f->get_16(); tga_header.image_width = f->get_16(); tga_header.image_height = f->get_16(); tga_header.pixel_depth = f->get_8(); tga_header.image_descriptor = f->get_8(); bool is_encoded = (tga_header.image_type == TGA_TYPE_RLE_INDEXED || tga_header.image_type == TGA_TYPE_RLE_RGB || tga_header.image_type == TGA_TYPE_RLE_MONOCHROME); bool has_color_map = (tga_header.image_type == TGA_TYPE_RLE_INDEXED || tga_header.image_type == TGA_TYPE_INDEXED); bool is_monochrome = (tga_header.image_type == TGA_TYPE_RLE_MONOCHROME || tga_header.image_type == TGA_TYPE_MONOCHROME); if (tga_header.image_type == TGA_TYPE_NO_DATA) { err = FAILED; } if (has_color_map) { if (tga_header.color_map_length > 256 || (tga_header.color_map_depth != 24) || tga_header.color_map_type != 1) { err = FAILED; } } else { if (tga_header.color_map_type) { err = FAILED; } } if (tga_header.image_width <= 0 || tga_header.image_height <= 0) { err = FAILED; } if (!(tga_header.pixel_depth == 8 || tga_header.pixel_depth == 24 || tga_header.pixel_depth == 32)) { err = FAILED; } if (err == OK) { f->seek(f->get_position() + tga_header.id_length); Vector<uint8_t> palette; if (has_color_map) { size_t color_map_size = tga_header.color_map_length * (tga_header.color_map_depth >> 3); err = palette.resize(color_map_size); if (err == OK) { uint8_t *palette_w = palette.ptrw(); f->get_buffer(&palette_w[0], color_map_size); } else { return OK; } } uint8_t *src_image_w = src_image.ptrw(); f->get_buffer(&src_image_w[0], src_image_len - f->get_position()); const uint8_t *src_image_r = src_image.ptr(); const size_t pixel_size = tga_header.pixel_depth >> 3; const size_t buffer_size = (tga_header.image_width * tga_header.image_height) * pixel_size; Vector<uint8_t> uncompressed_buffer; uncompressed_buffer.resize(buffer_size); uint8_t *uncompressed_buffer_w = uncompressed_buffer.ptrw(); const uint8_t *uncompressed_buffer_r; const uint8_t *buffer = nullptr; if (is_encoded) { err = decode_tga_rle(src_image_r, pixel_size, uncompressed_buffer_w, buffer_size); if (err == OK) { uncompressed_buffer_r = uncompressed_buffer.ptr(); buffer = uncompressed_buffer_r; } } else { buffer = src_image_r; }; if (err == OK) { const uint8_t *palette_r = palette.ptr(); err = convert_to_image(p_image, buffer, tga_header, palette_r, is_monochrome); } } f->close(); return err; } void ImageLoaderTGA::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("tga"); } static Ref<Image> _tga_mem_loader_func(const uint8_t *p_tga, int p_size) { FileAccessMemory memfile; Error open_memfile_error = memfile.open_custom(p_tga, p_size); ERR_FAIL_COND_V_MSG(open_memfile_error, Ref<Image>(), "Could not create memfile for TGA image buffer."); Ref<Image> img; img.instance(); Error load_error = ImageLoaderTGA().load_image(img, &memfile, false, 1.0f); ERR_FAIL_COND_V_MSG(load_error, Ref<Image>(), "Failed to load TGA image."); return img; } ImageLoaderTGA::ImageLoaderTGA() { Image::_tga_mem_loader_func = _tga_mem_loader_func; }
./CrossVul/dataset_final_sorted/CWE-787/cpp/bad_1979_0
crossvul-cpp_data_good_839_0
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "StructuredHeadersUtilities.h" #include "StructuredHeadersConstants.h" #include "proxygen/lib/utils/Base64.h" namespace proxygen { namespace StructuredHeaders { bool isLcAlpha(char c) { return c >= 0x61 && c <= 0x7A; } bool isValidIdentifierChar(char c) { return isLcAlpha(c) || std::isdigit(c) || c == '_' || c == '-' || c == '*' || c == '/'; } bool isValidEncodedBinaryContentChar( char c) { return std::isalpha(c) || std::isdigit(c) || c == '+' || c == '/' || c == '='; } bool isValidStringChar(char c) { /* * The difference between the character restriction here and that mentioned * in section 3.7 of version 6 of the Structured Headers draft is that this * function accepts \ and DQUOTE characters. These characters are allowed * as long as they are present as a part of an escape sequence, which is * checked for in the parseString() function in the StructuredHeadersBuffer. */ return c >= 0x20 && c <= 0x7E; } bool isValidIdentifier(const std::string& s) { if (s.size() == 0 || !isLcAlpha(s[0])) { return false; } for (char c : s) { if (!isValidIdentifierChar(c)) { return false; } } return true; } bool isValidString(const std::string& s) { for (char c : s) { if (!isValidStringChar(c)) { return false; } } return true; } bool isValidEncodedBinaryContent( const std::string& s) { if (s.size() % 4 != 0) { return false; } bool equalSeen = false; for (auto it = s.begin(); it != s.end(); it++) { if (*it == '=') { equalSeen = true; } else if (equalSeen || !isValidEncodedBinaryContentChar(*it)) { return false; } } return true; } bool itemTypeMatchesContent( const StructuredHeaderItem& input) { switch (input.tag) { case StructuredHeaderItem::Type::BINARYCONTENT: case StructuredHeaderItem::Type::IDENTIFIER: case StructuredHeaderItem::Type::STRING: return input.value.type() == typeid(std::string); case StructuredHeaderItem::Type::INT64: return input.value.type() == typeid(int64_t); case StructuredHeaderItem::Type::DOUBLE: return input.value.type() == typeid(double); case StructuredHeaderItem::Type::NONE: return true; } return false; } std::string decodeBase64( const std::string& encoded) { if (encoded.size() == 0) { // special case, to prevent an integer overflow down below. return std::string(); } int padding = 0; for (auto it = encoded.rbegin(); padding < 2 && it != encoded.rend() && *it == '='; ++it) { ++padding; } return Base64::decode(encoded, padding); } std::string encodeBase64(const std::string& input) { return Base64::encode(folly::ByteRange( reinterpret_cast<const uint8_t*>(input.c_str()), input.length())); } } }
./CrossVul/dataset_final_sorted/CWE-787/cpp/good_839_0
crossvul-cpp_data_bad_5228_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/mbstring/ext_mbstring.h" #include "hphp/runtime/base/string-buffer.h" #include "hphp/runtime/base/request-local.h" #include "hphp/runtime/ext/mbstring/php_unicode.h" #include "hphp/runtime/ext/mbstring/unicode_data.h" #include "hphp/runtime/ext/string/ext_string.h" #include "hphp/runtime/ext/std/ext_std_output.h" #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/zend-url.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/runtime/base/ini-setting.h" #include "hphp/runtime/base/request-event-handler.h" extern "C" { #include <mbfl/mbfl_convert.h> #include <mbfl/mbfilter.h> #include <mbfl/mbfilter_pass.h> #include <oniguruma.h> #include <map> } #define php_mb_re_pattern_buffer re_pattern_buffer #define php_mb_regex_t regex_t #define php_mb_re_registers re_registers extern void mbfl_memory_device_unput(mbfl_memory_device *device); #define PARSE_POST 0 #define PARSE_GET 1 #define PARSE_COOKIE 2 #define PARSE_STRING 3 #define PARSE_ENV 4 #define PARSE_SERVER 5 #define PARSE_SESSION 6 namespace HPHP { /////////////////////////////////////////////////////////////////////////////// // statics #define PHP_MBSTR_STACK_BLOCK_SIZE 32 typedef struct _php_mb_nls_ident_list { mbfl_no_language lang; mbfl_no_encoding* list; int list_size; } php_mb_nls_ident_list; static mbfl_no_encoding php_mb_default_identify_list_ja[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_jis, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_jp, mbfl_no_encoding_sjis }; static mbfl_no_encoding php_mb_default_identify_list_cn[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_cn, mbfl_no_encoding_cp936 }; static mbfl_no_encoding php_mb_default_identify_list_tw_hk[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_tw, mbfl_no_encoding_big5 }; static mbfl_no_encoding php_mb_default_identify_list_kr[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_kr, mbfl_no_encoding_uhc }; static mbfl_no_encoding php_mb_default_identify_list_ru[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_koi8r, mbfl_no_encoding_cp1251, mbfl_no_encoding_cp866 }; static mbfl_no_encoding php_mb_default_identify_list_hy[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_armscii8 }; static mbfl_no_encoding php_mb_default_identify_list_tr[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_8859_9 }; static mbfl_no_encoding php_mb_default_identify_list_neut[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8 }; static php_mb_nls_ident_list php_mb_default_identify_list[] = { { mbfl_no_language_japanese, php_mb_default_identify_list_ja, sizeof(php_mb_default_identify_list_ja) / sizeof(php_mb_default_identify_list_ja[0]) }, { mbfl_no_language_korean, php_mb_default_identify_list_kr, sizeof(php_mb_default_identify_list_kr) / sizeof(php_mb_default_identify_list_kr[0]) }, { mbfl_no_language_traditional_chinese, php_mb_default_identify_list_tw_hk, sizeof(php_mb_default_identify_list_tw_hk) / sizeof(php_mb_default_identify_list_tw_hk[0]) }, { mbfl_no_language_simplified_chinese, php_mb_default_identify_list_cn, sizeof(php_mb_default_identify_list_cn) / sizeof(php_mb_default_identify_list_cn[0]) }, { mbfl_no_language_russian, php_mb_default_identify_list_ru, sizeof(php_mb_default_identify_list_ru) / sizeof(php_mb_default_identify_list_ru[0]) }, { mbfl_no_language_armenian, php_mb_default_identify_list_hy, sizeof(php_mb_default_identify_list_hy) / sizeof(php_mb_default_identify_list_hy[0]) }, { mbfl_no_language_turkish, php_mb_default_identify_list_tr, sizeof(php_mb_default_identify_list_tr) / sizeof(php_mb_default_identify_list_tr[0]) }, { mbfl_no_language_neutral, php_mb_default_identify_list_neut, sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0]) } }; /////////////////////////////////////////////////////////////////////////////// // globals typedef std::map<std::string, php_mb_regex_t *> RegexCache; struct MBGlobals final : RequestEventHandler { mbfl_no_language language; mbfl_no_language current_language; mbfl_encoding *internal_encoding; mbfl_encoding *current_internal_encoding; mbfl_encoding *http_output_encoding; mbfl_encoding *current_http_output_encoding; mbfl_encoding *http_input_identify; mbfl_encoding *http_input_identify_get; mbfl_encoding *http_input_identify_post; mbfl_encoding *http_input_identify_cookie; mbfl_encoding *http_input_identify_string; mbfl_encoding **http_input_list; int http_input_list_size; mbfl_encoding **detect_order_list; int detect_order_list_size; mbfl_encoding **current_detect_order_list; int current_detect_order_list_size; mbfl_no_encoding *default_detect_order_list; int default_detect_order_list_size; int filter_illegal_mode; int filter_illegal_substchar; int current_filter_illegal_mode; int current_filter_illegal_substchar; bool encoding_translation; long strict_detection; long illegalchars; mbfl_buffer_converter *outconv; OnigEncoding default_mbctype; OnigEncoding current_mbctype; RegexCache ht_rc; std::string search_str; unsigned int search_pos; php_mb_regex_t *search_re; OnigRegion *search_regs; OnigOptionType regex_default_options; OnigSyntaxType *regex_default_syntax; void vscan(IMarker& mark) const override { } MBGlobals() : language(mbfl_no_language_uni), current_language(mbfl_no_language_uni), internal_encoding((mbfl_encoding*) mbfl_no2encoding(mbfl_no_encoding_utf8)), current_internal_encoding(internal_encoding), http_output_encoding((mbfl_encoding*) &mbfl_encoding_pass), current_http_output_encoding((mbfl_encoding*) &mbfl_encoding_pass), http_input_identify(nullptr), http_input_identify_get(nullptr), http_input_identify_post(nullptr), http_input_identify_cookie(nullptr), http_input_identify_string(nullptr), http_input_list(nullptr), http_input_list_size(0), detect_order_list(nullptr), detect_order_list_size(0), current_detect_order_list(nullptr), current_detect_order_list_size(0), default_detect_order_list ((mbfl_no_encoding *)php_mb_default_identify_list_neut), default_detect_order_list_size (sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0])), filter_illegal_mode(MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR), filter_illegal_substchar(0x3f), /* '?' */ current_filter_illegal_mode(MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR), current_filter_illegal_substchar(0x3f), /* '?' */ encoding_translation(0), strict_detection(0), illegalchars(0), outconv(nullptr), default_mbctype(ONIG_ENCODING_EUC_JP), current_mbctype(ONIG_ENCODING_EUC_JP), search_pos(0), search_re((php_mb_regex_t*)nullptr), search_regs((OnigRegion*)nullptr), regex_default_options(ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE), regex_default_syntax(ONIG_SYNTAX_RUBY) { } void requestInit() override { current_language = language; current_internal_encoding = internal_encoding; current_http_output_encoding = http_output_encoding; current_filter_illegal_mode = filter_illegal_mode; current_filter_illegal_substchar = filter_illegal_substchar; if (!encoding_translation) { illegalchars = 0; } mbfl_encoding **entry = nullptr; int n = 0; if (current_detect_order_list) { return; } if (detect_order_list && detect_order_list_size > 0) { n = detect_order_list_size; entry = (mbfl_encoding **)malloc(n * sizeof(mbfl_encoding*)); std::copy(detect_order_list, detect_order_list + (n * sizeof(mbfl_encoding*)), entry); } else { mbfl_no_encoding *src = default_detect_order_list; n = default_detect_order_list_size; entry = (mbfl_encoding **)malloc(n * sizeof(mbfl_encoding*)); for (int i = 0; i < n; i++) { entry[i] = (mbfl_encoding*) mbfl_no2encoding(src[i]); } } current_detect_order_list = entry; current_detect_order_list_size = n; } void requestShutdown() override { if (current_detect_order_list != nullptr) { free(current_detect_order_list); current_detect_order_list = nullptr; current_detect_order_list_size = 0; } if (outconv != nullptr) { illegalchars += mbfl_buffer_illegalchars(outconv); mbfl_buffer_converter_delete(outconv); outconv = nullptr; } /* clear http input identification. */ http_input_identify = nullptr; http_input_identify_post = nullptr; http_input_identify_get = nullptr; http_input_identify_cookie = nullptr; http_input_identify_string = nullptr; current_mbctype = default_mbctype; search_str.clear(); search_pos = 0; if (search_regs != nullptr) { onig_region_free(search_regs, 1); search_regs = (OnigRegion *)nullptr; } for (RegexCache::const_iterator it = ht_rc.begin(); it != ht_rc.end(); ++it) { onig_free(it->second); } ht_rc.clear(); } }; IMPLEMENT_STATIC_REQUEST_LOCAL(MBGlobals, s_mb_globals); #define MBSTRG(name) s_mb_globals->name /////////////////////////////////////////////////////////////////////////////// // unicode functions /* * A simple array of 32-bit masks for lookup. */ static unsigned long masks32[32] = { 0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020, 0x00000040, 0x00000080, 0x00000100, 0x00000200, 0x00000400, 0x00000800, 0x00001000, 0x00002000, 0x00004000, 0x00008000, 0x00010000, 0x00020000, 0x00040000, 0x00080000, 0x00100000, 0x00200000, 0x00400000, 0x00800000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000 }; static int prop_lookup(unsigned long code, unsigned long n) { long l, r, m; /* * There is an extra node on the end of the offsets to allow this routine * to work right. If the index is 0xffff, then there are no nodes for the * property. */ if ((l = _ucprop_offsets[n]) == 0xffff) return 0; /* * Locate the next offset that is not 0xffff. The sentinel at the end of * the array is the max index value. */ for (m = 1; n + m < _ucprop_size && _ucprop_offsets[n + m] == 0xffff; m++) ; r = _ucprop_offsets[n + m] - 1; while (l <= r) { /* * Determine a "mid" point and adjust to make sure the mid point is at * the beginning of a range pair. */ m = (l + r) >> 1; m -= (m & 1); if (code > _ucprop_ranges[m + 1]) l = m + 2; else if (code < _ucprop_ranges[m]) r = m - 2; else if (code >= _ucprop_ranges[m] && code <= _ucprop_ranges[m + 1]) return 1; } return 0; } static int php_unicode_is_prop(unsigned long code, unsigned long mask1, unsigned long mask2) { unsigned long i; if (mask1 == 0 && mask2 == 0) return 0; for (i = 0; mask1 && i < 32; i++) { if ((mask1 & masks32[i]) && prop_lookup(code, i)) return 1; } for (i = 32; mask2 && i < _ucprop_size; i++) { if ((mask2 & masks32[i & 31]) && prop_lookup(code, i)) return 1; } return 0; } static unsigned long case_lookup(unsigned long code, long l, long r, int field) { long m; /* * Do the binary search. */ while (l <= r) { /* * Determine a "mid" point and adjust to make sure the mid point is at * the beginning of a case mapping triple. */ m = (l + r) >> 1; m -= (m % 3); if (code > _uccase_map[m]) l = m + 3; else if (code < _uccase_map[m]) r = m - 3; else if (code == _uccase_map[m]) return _uccase_map[m + field]; } return code; } static unsigned long php_turkish_toupper(unsigned long code, long l, long r, int field) { if (code == 0x0069L) { return 0x0130L; } return case_lookup(code, l, r, field); } static unsigned long php_turkish_tolower(unsigned long code, long l, long r, int field) { if (code == 0x0049L) { return 0x0131L; } return case_lookup(code, l, r, field); } static unsigned long php_unicode_toupper(unsigned long code, enum mbfl_no_encoding enc) { int field; long l, r; if (php_unicode_is_upper(code)) return code; if (php_unicode_is_lower(code)) { /* * The character is lower case. */ field = 2; l = _uccase_len[0]; r = (l + _uccase_len[1]) - 3; if (enc == mbfl_no_encoding_8859_9) { return php_turkish_toupper(code, l, r, field); } } else { /* * The character is title case. */ field = 1; l = _uccase_len[0] + _uccase_len[1]; r = _uccase_size - 3; } return case_lookup(code, l, r, field); } static unsigned long php_unicode_tolower(unsigned long code, enum mbfl_no_encoding enc) { int field; long l, r; if (php_unicode_is_lower(code)) return code; if (php_unicode_is_upper(code)) { /* * The character is upper case. */ field = 1; l = 0; r = _uccase_len[0] - 3; if (enc == mbfl_no_encoding_8859_9) { return php_turkish_tolower(code, l, r, field); } } else { /* * The character is title case. */ field = 2; l = _uccase_len[0] + _uccase_len[1]; r = _uccase_size - 3; } return case_lookup(code, l, r, field); } static unsigned long php_unicode_totitle(unsigned long code, enum mbfl_no_encoding enc) { int field; long l, r; if (php_unicode_is_title(code)) return code; /* * The offset will always be the same for converting to title case. */ field = 2; if (php_unicode_is_upper(code)) { /* * The character is upper case. */ l = 0; r = _uccase_len[0] - 3; } else { /* * The character is lower case. */ l = _uccase_len[0]; r = (l + _uccase_len[1]) - 3; } return case_lookup(code, l, r, field); } #define BE_ARY_TO_UINT32(ptr) (\ ((unsigned char*)(ptr))[0]<<24 |\ ((unsigned char*)(ptr))[1]<<16 |\ ((unsigned char*)(ptr))[2]<< 8 |\ ((unsigned char*)(ptr))[3] ) #define UINT32_TO_BE_ARY(ptr,val) { \ unsigned int v = val; \ ((unsigned char*)(ptr))[0] = (v>>24) & 0xff,\ ((unsigned char*)(ptr))[1] = (v>>16) & 0xff,\ ((unsigned char*)(ptr))[2] = (v>> 8) & 0xff,\ ((unsigned char*)(ptr))[3] = (v ) & 0xff;\ } /** * Return 0 if input contains any illegal encoding, otherwise 1. * Even if any illegal encoding is detected the result may contain a list * of parsed encodings. */ static int php_mb_parse_encoding_list(const char *value, int value_length, mbfl_encoding ***return_list, int *return_size, int persistent) { int n, l, size, bauto, ret = 1; char *p, *p1, *p2, *endp, *tmpstr; mbfl_encoding *encoding; mbfl_no_encoding *src; mbfl_encoding **entry, **list; list = nullptr; if (value == nullptr || value_length <= 0) { if (return_list) { *return_list = nullptr; } if (return_size) { *return_size = 0; } return 0; } else { mbfl_no_encoding *identify_list; int identify_list_size; identify_list = MBSTRG(default_detect_order_list); identify_list_size = MBSTRG(default_detect_order_list_size); /* copy the value string for work */ if (value[0]=='"' && value[value_length-1]=='"' && value_length>2) { tmpstr = (char *)strndup(value+1, value_length-2); value_length -= 2; } else tmpstr = (char *)strndup(value, value_length); if (tmpstr == nullptr) { return 0; } /* count the number of listed encoding names */ endp = tmpstr + value_length; n = 1; p1 = tmpstr; while ((p2 = (char*)string_memnstr(p1, ",", 1, endp)) != nullptr) { p1 = p2 + 1; n++; } size = n + identify_list_size; /* make list */ list = (mbfl_encoding **)calloc(size, sizeof(mbfl_encoding*)); if (list != nullptr) { entry = list; n = 0; bauto = 0; p1 = tmpstr; do { p2 = p = (char*)string_memnstr(p1, ",", 1, endp); if (p == nullptr) { p = endp; } *p = '\0'; /* trim spaces */ while (p1 < p && (*p1 == ' ' || *p1 == '\t')) { p1++; } p--; while (p > p1 && (*p == ' ' || *p == '\t')) { *p = '\0'; p--; } /* convert to the encoding number and check encoding */ if (strcasecmp(p1, "auto") == 0) { if (!bauto) { bauto = 1; l = identify_list_size; src = identify_list; for (int i = 0; i < l; i++) { *entry++ = (mbfl_encoding*) mbfl_no2encoding(*src++); n++; } } } else { encoding = (mbfl_encoding*) mbfl_name2encoding(p1); if (encoding != nullptr) { *entry++ = encoding; n++; } else { ret = 0; } } p1 = p2 + 1; } while (n < size && p2 != nullptr); if (n > 0) { if (return_list) { *return_list = list; } else { free(list); } } else { free(list); if (return_list) { *return_list = nullptr; } ret = 0; } if (return_size) { *return_size = n; } } else { if (return_list) { *return_list = nullptr; } if (return_size) { *return_size = 0; } ret = 0; } free(tmpstr); } return ret; } static char *php_mb_convert_encoding(const char *input, size_t length, const char *_to_encoding, const char *_from_encodings, unsigned int *output_len) { mbfl_string string, result, *ret; mbfl_encoding *from_encoding, *to_encoding; mbfl_buffer_converter *convd; int size; mbfl_encoding **list; char *output = nullptr; if (output_len) { *output_len = 0; } if (!input) { return nullptr; } /* new encoding */ if (_to_encoding && strlen(_to_encoding)) { to_encoding = (mbfl_encoding*) mbfl_name2encoding(_to_encoding); if (to_encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", _to_encoding); return nullptr; } } else { to_encoding = MBSTRG(current_internal_encoding); } /* initialize string */ mbfl_string_init(&string); mbfl_string_init(&result); from_encoding = MBSTRG(current_internal_encoding); string.no_encoding = from_encoding->no_encoding; string.no_language = MBSTRG(current_language); string.val = (unsigned char *)input; string.len = length; /* pre-conversion encoding */ if (_from_encodings) { list = nullptr; size = 0; php_mb_parse_encoding_list(_from_encodings, strlen(_from_encodings), &list, &size, 0); if (size == 1) { from_encoding = *list; string.no_encoding = from_encoding->no_encoding; } else if (size > 1) { /* auto detect */ from_encoding = (mbfl_encoding*) mbfl_identify_encoding2(&string, (const mbfl_encoding**) list, size, MBSTRG(strict_detection)); if (from_encoding != nullptr) { string.no_encoding = from_encoding->no_encoding; } else { raise_warning("Unable to detect character encoding"); from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; to_encoding = from_encoding; string.no_encoding = from_encoding->no_encoding; } } else { raise_warning("Illegal character encoding specified"); } if (list != nullptr) { free((void *)list); } } /* initialize converter */ convd = mbfl_buffer_converter_new2(from_encoding, to_encoding, string.len); if (convd == nullptr) { raise_warning("Unable to create character encoding converter"); return nullptr; } mbfl_buffer_converter_illegal_mode (convd, MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (convd, MBSTRG(current_filter_illegal_substchar)); /* do it */ ret = mbfl_buffer_converter_feed_result(convd, &string, &result); if (ret) { if (output_len) { *output_len = ret->len; } output = (char *)ret->val; } MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); return output; } static char *php_unicode_convert_case(int case_mode, const char *srcstr, size_t srclen, unsigned int *ret_len, const char *src_encoding) { char *unicode, *newstr; unsigned int unicode_len; unsigned char *unicode_ptr; size_t i; enum mbfl_no_encoding _src_encoding = mbfl_name2no_encoding(src_encoding); unicode = php_mb_convert_encoding(srcstr, srclen, "UCS-4BE", src_encoding, &unicode_len); if (unicode == nullptr) return nullptr; unicode_ptr = (unsigned char *)unicode; switch(case_mode) { case PHP_UNICODE_CASE_UPPER: for (i = 0; i < unicode_len; i+=4) { UINT32_TO_BE_ARY(&unicode_ptr[i], php_unicode_toupper(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } break; case PHP_UNICODE_CASE_LOWER: for (i = 0; i < unicode_len; i+=4) { UINT32_TO_BE_ARY(&unicode_ptr[i], php_unicode_tolower(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } break; case PHP_UNICODE_CASE_TITLE: { int mode = 0; for (i = 0; i < unicode_len; i+=4) { int res = php_unicode_is_prop (BE_ARY_TO_UINT32(&unicode_ptr[i]), UC_MN|UC_ME|UC_CF|UC_LM|UC_SK|UC_LU|UC_LL|UC_LT|UC_PO|UC_OS, 0); if (mode) { if (res) { UINT32_TO_BE_ARY (&unicode_ptr[i], php_unicode_tolower(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } else { mode = 0; } } else { if (res) { mode = 1; UINT32_TO_BE_ARY (&unicode_ptr[i], php_unicode_totitle(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } } } } break; } newstr = php_mb_convert_encoding(unicode, unicode_len, src_encoding, "UCS-4BE", ret_len); free(unicode); return newstr; } /////////////////////////////////////////////////////////////////////////////// // helpers /** * Return 0 if input contains any illegal encoding, otherwise 1. * Even if any illegal encoding is detected the result may contain a list * of parsed encodings. */ static int php_mb_parse_encoding_array(const Array& array, mbfl_encoding ***return_list, int *return_size, int persistent) { int n, l, size, bauto,ret = 1; mbfl_encoding *encoding; mbfl_no_encoding *src; mbfl_encoding **list, **entry; list = nullptr; mbfl_no_encoding *identify_list = MBSTRG(default_detect_order_list); int identify_list_size = MBSTRG(default_detect_order_list_size); size = array.size() + identify_list_size; list = (mbfl_encoding **)calloc(size, sizeof(mbfl_encoding*)); if (list != nullptr) { entry = list; bauto = 0; n = 0; for (ArrayIter iter(array); iter; ++iter) { auto const hash_entry = iter.second().toString(); if (strcasecmp(hash_entry.data(), "auto") == 0) { if (!bauto) { bauto = 1; l = identify_list_size; src = identify_list; for (int j = 0; j < l; j++) { *entry++ = (mbfl_encoding*) mbfl_no2encoding(*src++); n++; } } } else { encoding = (mbfl_encoding*) mbfl_name2encoding(hash_entry.data()); if (encoding != nullptr) { *entry++ = encoding; n++; } else { ret = 0; } } } if (n > 0) { if (return_list) { *return_list = list; } else { free(list); } } else { free(list); if (return_list) { *return_list = nullptr; } ret = 0; } if (return_size) { *return_size = n; } } else { if (return_list) { *return_list = nullptr; } if (return_size) { *return_size = 0; } ret = 0; } return ret; } static bool php_mb_parse_encoding(const Variant& encoding, mbfl_encoding ***return_list, int *return_size, bool persistent) { bool ret; if (encoding.isArray()) { ret = php_mb_parse_encoding_array(encoding.toArray(), return_list, return_size, persistent ? 1 : 0); } else { String enc = encoding.toString(); ret = php_mb_parse_encoding_list(enc.data(), enc.size(), return_list, return_size, persistent ? 1 : 0); } if (!ret) { if (return_list && *return_list) { free(*return_list); *return_list = nullptr; } return_size = 0; } return ret; } static int php_mb_nls_get_default_detect_order_list(mbfl_no_language lang, mbfl_no_encoding **plist, int* plist_size) { size_t i; *plist = (mbfl_no_encoding *) php_mb_default_identify_list_neut; *plist_size = sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0]); for (i = 0; i < sizeof(php_mb_default_identify_list) / sizeof(php_mb_default_identify_list[0]); i++) { if (php_mb_default_identify_list[i].lang == lang) { *plist = php_mb_default_identify_list[i].list; *plist_size = php_mb_default_identify_list[i].list_size; return 1; } } return 0; } static size_t php_mb_mbchar_bytes_ex(const char *s, const mbfl_encoding *enc) { if (enc != nullptr) { if (enc->flag & MBFL_ENCTYPE_MBCS) { if (enc->mblen_table != nullptr) { if (s != nullptr) return enc->mblen_table[*(unsigned char *)s]; } } else if (enc->flag & (MBFL_ENCTYPE_WCS2BE | MBFL_ENCTYPE_WCS2LE)) { return 2; } else if (enc->flag & (MBFL_ENCTYPE_WCS4BE | MBFL_ENCTYPE_WCS4LE)) { return 4; } } return 1; } static int php_mb_stripos(int mode, const char *old_haystack, int old_haystack_len, const char *old_needle, int old_needle_len, long offset, const char *from_encoding) { int n; mbfl_string haystack, needle; n = -1; mbfl_string_init(&haystack); mbfl_string_init(&needle); haystack.no_language = MBSTRG(current_language); haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; needle.no_language = MBSTRG(current_language); needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; do { haystack.val = (unsigned char *)php_unicode_convert_case (PHP_UNICODE_CASE_UPPER, old_haystack, (size_t)old_haystack_len, &haystack.len, from_encoding); if (!haystack.val) { break; } if (haystack.len <= 0) { break; } needle.val = (unsigned char *)php_unicode_convert_case (PHP_UNICODE_CASE_UPPER, old_needle, (size_t)old_needle_len, &needle.len, from_encoding); if (!needle.val) { break; } if (needle.len <= 0) { break; } haystack.no_encoding = needle.no_encoding = mbfl_name2no_encoding(from_encoding); if (haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", from_encoding); break; } int haystack_char_len = mbfl_strlen(&haystack); if (mode) { if ((offset > 0 && offset > haystack_char_len) || (offset < 0 && -offset > haystack_char_len)) { raise_warning("Offset is greater than the length of haystack string"); break; } } else { if (offset < 0 || offset > haystack_char_len) { raise_warning("Offset not contained in string."); break; } } n = mbfl_strpos(&haystack, &needle, offset, mode); } while(0); if (haystack.val) { free(haystack.val); } if (needle.val) { free(needle.val); } return n; } /////////////////////////////////////////////////////////////////////////////// static String convertArg(const Variant& arg) { return arg.isNull() ? null_string : arg.toString(); } Array HHVM_FUNCTION(mb_list_encodings) { Array ret; int i = 0; const mbfl_encoding **encodings = mbfl_get_supported_encodings(); const mbfl_encoding *encoding; while ((encoding = encodings[i++]) != nullptr) { ret.append(String(encoding->name, CopyString)); } return ret; } Variant HHVM_FUNCTION(mb_encoding_aliases, const String& name) { const mbfl_encoding *encoding; int i = 0; encoding = mbfl_name2encoding(name.data()); if (!encoding) { raise_warning("mb_encoding_aliases(): Unknown encoding \"%s\"", name.data()); return false; } Array ret = Array::Create(); if (encoding->aliases != nullptr) { while ((*encoding->aliases)[i] != nullptr) { ret.append((*encoding->aliases)[i]); i++; } } return ret; } Variant HHVM_FUNCTION(mb_list_encodings_alias_names, const Variant& opt_name) { const String name = convertArg(opt_name); const mbfl_encoding **encodings; const mbfl_encoding *encoding; mbfl_no_encoding no_encoding; int i, j; Array ret; if (name.isNull()) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { Array row; if (encoding->aliases != nullptr) { j = 0; while ((*encoding->aliases)[j] != nullptr) { row.append(String((*encoding->aliases)[j], CopyString)); j++; } } ret.set(String(encoding->name, CopyString), row); } } else { no_encoding = mbfl_name2no_encoding(name.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", name.data()); return false; } char *name = (char *)mbfl_no_encoding2name(no_encoding); if (name != nullptr) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { if (strcmp(encoding->name, name) != 0) continue; if (encoding->aliases != nullptr) { j = 0; while ((*encoding->aliases)[j] != nullptr) { ret.append(String((*encoding->aliases)[j], CopyString)); j++; } } break; } } else { return false; } } return ret; } Variant HHVM_FUNCTION(mb_list_mime_names, const Variant& opt_name) { const String name = convertArg(opt_name); const mbfl_encoding **encodings; const mbfl_encoding *encoding; mbfl_no_encoding no_encoding; int i; Array ret; if (name.isNull()) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { if (encoding->mime_name != nullptr) { ret.set(String(encoding->name, CopyString), String(encoding->mime_name, CopyString)); } else{ ret.set(String(encoding->name, CopyString), ""); } } } else { no_encoding = mbfl_name2no_encoding(name.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", name.data()); return false; } char *name = (char *)mbfl_no_encoding2name(no_encoding); if (name != nullptr) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { if (strcmp(encoding->name, name) != 0) continue; if (encoding->mime_name != nullptr) { return String(encoding->mime_name, CopyString); } break; } return empty_string_variant(); } else { return false; } } return ret; } bool HHVM_FUNCTION(mb_check_encoding, const Variant& opt_var, const Variant& opt_encoding) { const String var = convertArg(opt_var); const String encoding = convertArg(opt_encoding); mbfl_buffer_converter *convd; mbfl_no_encoding no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbfl_string string, result, *ret = nullptr; long illegalchars = 0; if (var.isNull()) { return MBSTRG(illegalchars) == 0; } if (!encoding.isNull()) { no_encoding = mbfl_name2no_encoding(encoding.data()); if (no_encoding == mbfl_no_encoding_invalid || no_encoding == mbfl_no_encoding_pass) { raise_warning("Invalid encoding \"%s\"", encoding.data()); return false; } } convd = mbfl_buffer_converter_new(no_encoding, no_encoding, 0); if (convd == nullptr) { raise_warning("Unable to create converter"); return false; } mbfl_buffer_converter_illegal_mode (convd, MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE); mbfl_buffer_converter_illegal_substchar (convd, 0); /* initialize string */ mbfl_string_init_set(&string, mbfl_no_language_neutral, no_encoding); mbfl_string_init(&result); string.val = (unsigned char *)var.data(); string.len = var.size(); ret = mbfl_buffer_converter_feed_result(convd, &string, &result); illegalchars = mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); if (ret != nullptr) { MBSTRG(illegalchars) += illegalchars; if (illegalchars == 0 && string.len == ret->len && memcmp((const char *)string.val, (const char *)ret->val, string.len) == 0) { mbfl_string_clear(&result); return true; } else { mbfl_string_clear(&result); return false; } } else { return false; } } Variant HHVM_FUNCTION(mb_convert_case, const String& str, int mode, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *enc = nullptr; if (encoding.empty()) { enc = MBSTRG(current_internal_encoding)->mime_name; } else { enc = encoding.data(); } unsigned int ret_len; char *newstr = php_unicode_convert_case(mode, str.data(), str.size(), &ret_len, enc); if (newstr) { return String(newstr, ret_len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_convert_encoding, const String& str, const String& to_encoding, const Variant& from_encoding /* = null_variant */) { String encoding = from_encoding.toString(); if (from_encoding.isArray()) { StringBuffer _from_encodings; Array encs = from_encoding.toArray(); for (ArrayIter iter(encs); iter; ++iter) { if (!_from_encodings.empty()) { _from_encodings.append(","); } _from_encodings.append(iter.second().toString()); } encoding = _from_encodings.detach(); } unsigned int size; char *ret = php_mb_convert_encoding(str.data(), str.size(), to_encoding.data(), (!encoding.empty() ? encoding.data() : nullptr), &size); if (ret != nullptr) { return String(ret, size, AttachString); } return false; } Variant HHVM_FUNCTION(mb_convert_kana, const String& str, const Variant& opt_option, const Variant& opt_encoding) { const String option = convertArg(opt_option); const String encoding = convertArg(opt_encoding); mbfl_string string, result, *ret; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); int opt = 0x900; if (!option.empty()) { const char *p = option.data(); int n = option.size(); int i = 0; opt = 0; while (i < n) { i++; switch (*p++) { case 'A': opt |= 0x1; break; case 'a': opt |= 0x10; break; case 'R': opt |= 0x2; break; case 'r': opt |= 0x20; break; case 'N': opt |= 0x4; break; case 'n': opt |= 0x40; break; case 'S': opt |= 0x8; break; case 's': opt |= 0x80; break; case 'K': opt |= 0x100; break; case 'k': opt |= 0x1000; break; case 'H': opt |= 0x200; break; case 'h': opt |= 0x2000; break; case 'V': opt |= 0x800; break; case 'C': opt |= 0x10000; break; case 'c': opt |= 0x20000; break; case 'M': opt |= 0x100000; break; case 'm': opt |= 0x200000; break; } } } /* encoding */ if (!encoding.empty()) { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } ret = mbfl_ja_jp_hantozen(&string, &result, opt); if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } static bool php_mbfl_encoding_detect(const Variant& var, mbfl_encoding_detector *identd, mbfl_string *string) { if (var.isArray() || var.is(KindOfObject)) { Array items = var.toArray(); for (ArrayIter iter(items); iter; ++iter) { if (php_mbfl_encoding_detect(iter.second(), identd, string)) { return true; } } } else if (var.isString()) { String svar = var.toString(); string->val = (unsigned char *)svar.data(); string->len = svar.size(); if (mbfl_encoding_detector_feed(identd, string)) { return true; } } return false; } static Variant php_mbfl_convert(const Variant& var, mbfl_buffer_converter *convd, mbfl_string *string, mbfl_string *result) { if (var.isArray()) { Array ret = empty_array(); Array items = var.toArray(); for (ArrayIter iter(items); iter; ++iter) { ret.set(iter.first(), php_mbfl_convert(iter.second(), convd, string, result)); } return ret; } if (var.is(KindOfObject)) { Object obj = var.toObject(); Array items = var.toArray(); for (ArrayIter iter(items); iter; ++iter) { obj->o_set(iter.first().toString(), php_mbfl_convert(iter.second(), convd, string, result)); } return var; // which still has obj } if (var.isString()) { String svar = var.toString(); string->val = (unsigned char *)svar.data(); string->len = svar.size(); mbfl_string *ret = mbfl_buffer_converter_feed_result(convd, string, result); return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return var; } Variant HHVM_FUNCTION(mb_convert_variables, const String& to_encoding, const Variant& from_encoding, VRefParam vars, const Array& args /* = null_array */) { mbfl_string string, result; mbfl_encoding *_from_encoding, *_to_encoding; mbfl_encoding_detector *identd; mbfl_buffer_converter *convd; int elistsz; mbfl_encoding **elist; char *name; /* new encoding */ _to_encoding = (mbfl_encoding*) mbfl_name2encoding(to_encoding.data()); if (_to_encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", to_encoding.data()); return false; } /* initialize string */ mbfl_string_init(&string); mbfl_string_init(&result); _from_encoding = MBSTRG(current_internal_encoding); string.no_encoding = _from_encoding->no_encoding; string.no_language = MBSTRG(current_language); /* pre-conversion encoding */ elist = nullptr; elistsz = 0; php_mb_parse_encoding(from_encoding, &elist, &elistsz, false); if (elistsz <= 0) { _from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } else if (elistsz == 1) { _from_encoding = *elist; } else { /* auto detect */ _from_encoding = nullptr; identd = mbfl_encoding_detector_new2((const mbfl_encoding**) elist, elistsz, MBSTRG(strict_detection)); if (identd != nullptr) { for (int n = -1; n < args.size(); n++) { if (php_mbfl_encoding_detect(n < 0 ? (Variant&)vars : args[n], identd, &string)) { break; } } _from_encoding = (mbfl_encoding*) mbfl_encoding_detector_judge2(identd); mbfl_encoding_detector_delete(identd); } if (_from_encoding == nullptr) { raise_warning("Unable to detect encoding"); _from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } } if (elist != nullptr) { free((void *)elist); } /* create converter */ convd = nullptr; if (_from_encoding != &mbfl_encoding_pass) { convd = mbfl_buffer_converter_new2(_from_encoding, _to_encoding, 0); if (convd == nullptr) { raise_warning("Unable to create converter"); return false; } mbfl_buffer_converter_illegal_mode (convd, MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (convd, MBSTRG(current_filter_illegal_substchar)); } /* convert */ if (convd != nullptr) { vars.assignIfRef(php_mbfl_convert(vars, convd, &string, &result)); for (int n = 0; n < args.size(); n++) { const_cast<Array&>(args).set(n, php_mbfl_convert(args[n], convd, &string, &result)); } MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); } if (_from_encoding != nullptr) { name = (char*) _from_encoding->name; if (name != nullptr) { return String(name, CopyString); } } return false; } Variant HHVM_FUNCTION(mb_decode_mimeheader, const String& str) { mbfl_string string, result, *ret; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); mbfl_string_init(&result); ret = mbfl_mime_header_decode(&string, &result, MBSTRG(current_internal_encoding)->no_encoding); if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } static Variant php_mb_numericentity_exec(const String& str, const Variant& convmap, const String& encoding, bool is_hex, int type) { int mapsize=0; mbfl_string string, result, *ret; mbfl_no_encoding no_encoding; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); if (type == 0 && is_hex) { type = 2; /* output in hex format */ } /* encoding */ if (!encoding.empty()) { no_encoding = mbfl_name2no_encoding(encoding.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } else { string.no_encoding = no_encoding; } } /* conversion map */ int *iconvmap = nullptr; if (convmap.isArray()) { Array convs = convmap.toArray(); mapsize = convs.size(); if (mapsize > 0) { iconvmap = (int*)malloc(mapsize * sizeof(int)); int *mapelm = iconvmap; for (ArrayIter iter(convs); iter; ++iter) { *mapelm++ = iter.second().toInt32(); } } } if (iconvmap == nullptr) { return false; } mapsize /= 4; ret = mbfl_html_numeric_entity(&string, &result, iconvmap, mapsize, type); free(iconvmap); if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_decode_numericentity, const String& str, const Variant& convmap, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); return php_mb_numericentity_exec(str, convmap, encoding, false, 1); } Variant HHVM_FUNCTION(mb_detect_encoding, const String& str, const Variant& encoding_list /* = null_variant */, const Variant& strict /* = null_variant */) { mbfl_string string; mbfl_encoding *ret; mbfl_encoding **elist, **list; int size; /* make encoding list */ list = nullptr; size = 0; php_mb_parse_encoding(encoding_list, &list, &size, false); if (size > 0 && list != nullptr) { elist = list; } else { elist = MBSTRG(current_detect_order_list); size = MBSTRG(current_detect_order_list_size); } long nstrict = 0; if (!strict.isNull()) { nstrict = strict.toInt64(); } else { nstrict = MBSTRG(strict_detection); } mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.val = (unsigned char *)str.data(); string.len = str.size(); ret = (mbfl_encoding*) mbfl_identify_encoding2(&string, (const mbfl_encoding**) elist, size, nstrict); if (list != nullptr) { free(list); } if (ret != nullptr) { return String(ret->name, CopyString); } return false; } Variant HHVM_FUNCTION(mb_detect_order, const Variant& encoding_list /* = null_variant */) { int n, size; mbfl_encoding **list, **entry; if (encoding_list.isNull()) { Array ret; entry = MBSTRG(current_detect_order_list); n = MBSTRG(current_detect_order_list_size); while (n > 0) { char *name = (char*) (*entry)->name; if (name) { ret.append(String(name, CopyString)); } entry++; n--; } return ret; } list = nullptr; size = 0; if (!php_mb_parse_encoding(encoding_list, &list, &size, false) || list == nullptr) { return false; } if (MBSTRG(current_detect_order_list)) { free(MBSTRG(current_detect_order_list)); } MBSTRG(current_detect_order_list) = list; MBSTRG(current_detect_order_list_size) = size; return true; } Variant HHVM_FUNCTION(mb_encode_mimeheader, const String& str, const Variant& opt_charset, const Variant& opt_transfer_encoding, const String& linefeed /* = "\r\n" */, int indent /* = 0 */) { const String charset = convertArg(opt_charset); const String transfer_encoding = convertArg(opt_transfer_encoding); mbfl_no_encoding charsetenc, transenc; mbfl_string string, result, *ret; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); charsetenc = mbfl_no_encoding_pass; transenc = mbfl_no_encoding_base64; if (!charset.empty()) { charsetenc = mbfl_name2no_encoding(charset.data()); if (charsetenc == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", charset.data()); return false; } } else { const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language)); if (lang != nullptr) { charsetenc = lang->mail_charset; transenc = lang->mail_header_encoding; } } if (!transfer_encoding.empty()) { char ch = *transfer_encoding.data(); if (ch == 'B' || ch == 'b') { transenc = mbfl_no_encoding_base64; } else if (ch == 'Q' || ch == 'q') { transenc = mbfl_no_encoding_qprint; } } mbfl_string_init(&result); ret = mbfl_mime_header_encode(&string, &result, charsetenc, transenc, linefeed.data(), indent); if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_encode_numericentity, const String& str, const Variant& convmap, const Variant& opt_encoding /* = null_variant */, bool is_hex /* = false */) { const String encoding = convertArg(opt_encoding); return php_mb_numericentity_exec(str, convmap, encoding, is_hex, 0); } const StaticString s_internal_encoding("internal_encoding"), s_http_input("http_input"), s_http_output("http_output"), s_mail_charset("mail_charset"), s_mail_header_encoding("mail_header_encoding"), s_mail_body_encoding("mail_body_encoding"), s_illegal_chars("illegal_chars"), s_encoding_translation("encoding_translation"), s_On("On"), s_Off("Off"), s_language("language"), s_detect_order("detect_order"), s_substitute_character("substitute_character"), s_strict_detection("strict_detection"), s_none("none"), s_long("long"), s_entity("entity"); Variant HHVM_FUNCTION(mb_get_info, const Variant& opt_type) { const String type = convertArg(opt_type); const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language)); mbfl_encoding **entry; int n; char *name; if (type.empty() || strcasecmp(type.data(), "all") == 0) { Array ret; if (MBSTRG(current_internal_encoding) != nullptr && (name = (char *) MBSTRG(current_internal_encoding)->name) != nullptr) { ret.set(s_internal_encoding, String(name, CopyString)); } if (MBSTRG(http_input_identify) != nullptr && (name = (char *)MBSTRG(http_input_identify)->name) != nullptr) { ret.set(s_http_input, String(name, CopyString)); } if (MBSTRG(current_http_output_encoding) != nullptr && (name = (char *)MBSTRG(current_http_output_encoding)->name) != nullptr) { ret.set(s_http_output, String(name, CopyString)); } if (lang != nullptr) { if ((name = (char *)mbfl_no_encoding2name (lang->mail_charset)) != nullptr) { ret.set(s_mail_charset, String(name, CopyString)); } if ((name = (char *)mbfl_no_encoding2name (lang->mail_header_encoding)) != nullptr) { ret.set(s_mail_header_encoding, String(name, CopyString)); } if ((name = (char *)mbfl_no_encoding2name (lang->mail_body_encoding)) != nullptr) { ret.set(s_mail_body_encoding, String(name, CopyString)); } } ret.set(s_illegal_chars, MBSTRG(illegalchars)); ret.set(s_encoding_translation, MBSTRG(encoding_translation) ? s_On : s_Off); if ((name = (char *)mbfl_no_language2name (MBSTRG(current_language))) != nullptr) { ret.set(s_language, String(name, CopyString)); } n = MBSTRG(current_detect_order_list_size); entry = MBSTRG(current_detect_order_list); if (n > 0) { Array row; while (n > 0) { if ((name = (char *)(*entry)->name) != nullptr) { row.append(String(name, CopyString)); } entry++; n--; } ret.set(s_detect_order, row); } switch (MBSTRG(current_filter_illegal_mode)) { case MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE: ret.set(s_substitute_character, s_none); break; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG: ret.set(s_substitute_character, s_long); break; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY: ret.set(s_substitute_character, s_entity); break; default: ret.set(s_substitute_character, MBSTRG(current_filter_illegal_substchar)); } ret.set(s_strict_detection, MBSTRG(strict_detection) ? s_On : s_Off); return ret; } else if (strcasecmp(type.data(), "internal_encoding") == 0) { if (MBSTRG(current_internal_encoding) != nullptr && (name = (char *)MBSTRG(current_internal_encoding)->name) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "http_input") == 0) { if (MBSTRG(http_input_identify) != nullptr && (name = (char *)MBSTRG(http_input_identify)->name) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "http_output") == 0) { if (MBSTRG(current_http_output_encoding) != nullptr && (name = (char *)MBSTRG(current_http_output_encoding)->name) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "mail_charset") == 0) { if (lang != nullptr && (name = (char *)mbfl_no_encoding2name (lang->mail_charset)) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "mail_header_encoding") == 0) { if (lang != nullptr && (name = (char *)mbfl_no_encoding2name (lang->mail_header_encoding)) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "mail_body_encoding") == 0) { if (lang != nullptr && (name = (char *)mbfl_no_encoding2name (lang->mail_body_encoding)) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "illegal_chars") == 0) { return MBSTRG(illegalchars); } else if (strcasecmp(type.data(), "encoding_translation") == 0) { return MBSTRG(encoding_translation) ? "On" : "Off"; } else if (strcasecmp(type.data(), "language") == 0) { if ((name = (char *)mbfl_no_language2name (MBSTRG(current_language))) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "detect_order") == 0) { n = MBSTRG(current_detect_order_list_size); entry = MBSTRG(current_detect_order_list); if (n > 0) { Array ret; while (n > 0) { name = (char *)(*entry)->name; if (name) { ret.append(String(name, CopyString)); } entry++; n--; } } } else if (strcasecmp(type.data(), "substitute_character") == 0) { if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE) { return s_none; } else if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG) { return s_long; } else if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY) { return s_entity; } else { return MBSTRG(current_filter_illegal_substchar); } } else if (strcasecmp(type.data(), "strict_detection") == 0) { return MBSTRG(strict_detection) ? s_On : s_Off; } return false; } Variant HHVM_FUNCTION(mb_http_input, const Variant& opt_type) { const String type = convertArg(opt_type); int n; char *name; mbfl_encoding **entry; mbfl_encoding *result = nullptr; if (type.empty()) { result = MBSTRG(http_input_identify); } else { switch (*type.data()) { case 'G': case 'g': result = MBSTRG(http_input_identify_get); break; case 'P': case 'p': result = MBSTRG(http_input_identify_post); break; case 'C': case 'c': result = MBSTRG(http_input_identify_cookie); break; case 'S': case 's': result = MBSTRG(http_input_identify_string); break; case 'I': case 'i': { Array ret; entry = MBSTRG(http_input_list); n = MBSTRG(http_input_list_size); while (n > 0) { name = (char *)(*entry)->name; if (name) { ret.append(String(name, CopyString)); } entry++; n--; } return ret; } case 'L': case 'l': { entry = MBSTRG(http_input_list); n = MBSTRG(http_input_list_size); StringBuffer list; while (n > 0) { name = (char *)(*entry)->name; if (name) { if (list.empty()) { list.append(name); } else { list.append(','); list.append(name); } } entry++; n--; } if (list.empty()) { return false; } return list.detach(); } default: result = MBSTRG(http_input_identify); break; } } if (result != nullptr && (name = (char *)(result)->name) != nullptr) { return String(name, CopyString); } return false; } Variant HHVM_FUNCTION(mb_http_output, const Variant& opt_encoding) { const String encoding_name = convertArg(opt_encoding); if (encoding_name.empty()) { char *name = (char *)(MBSTRG(current_http_output_encoding)->name); if (name != nullptr) { return String(name, CopyString); } return false; } mbfl_encoding *encoding = (mbfl_encoding*) mbfl_name2encoding(encoding_name.data()); if (encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", encoding_name.data()); return false; } MBSTRG(current_http_output_encoding) = encoding; return true; } Variant HHVM_FUNCTION(mb_internal_encoding, const Variant& opt_encoding) { const String encoding_name = convertArg(opt_encoding); if (encoding_name.empty()) { char *name = (char *)(MBSTRG(current_internal_encoding)->name); if (name != nullptr) { return String(name, CopyString); } return false; } mbfl_encoding *encoding = (mbfl_encoding*) mbfl_name2encoding(encoding_name.data()); if (encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", encoding_name.data()); return false; } MBSTRG(current_internal_encoding) = encoding; return true; } Variant HHVM_FUNCTION(mb_language, const Variant& opt_language) { const String language = convertArg(opt_language); if (language.empty()) { return String(mbfl_no_language2name(MBSTRG(current_language)), CopyString); } mbfl_no_language no_language = mbfl_name2no_language(language.data()); if (no_language == mbfl_no_language_invalid) { raise_warning("Unknown language \"%s\"", language.data()); return false; } php_mb_nls_get_default_detect_order_list (no_language, &MBSTRG(default_detect_order_list), &MBSTRG(default_detect_order_list_size)); MBSTRG(current_language) = no_language; return true; } String HHVM_FUNCTION(mb_output_handler, const String& contents, int status) { mbfl_string string, result; int last_feed; mbfl_encoding *encoding = MBSTRG(current_http_output_encoding); /* start phase only */ if (status & k_PHP_OUTPUT_HANDLER_START) { /* delete the converter just in case. */ if (MBSTRG(outconv)) { MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv)); mbfl_buffer_converter_delete(MBSTRG(outconv)); MBSTRG(outconv) = nullptr; } if (encoding == nullptr) { return contents; } /* analyze mime type */ String mimetype = g_context->getMimeType(); if (!mimetype.empty()) { const char *charset = encoding->mime_name; if (charset) { g_context->setContentType(mimetype, charset); } /* activate the converter */ MBSTRG(outconv) = mbfl_buffer_converter_new2 (MBSTRG(current_internal_encoding), encoding, 0); } } /* just return if the converter is not activated. */ if (MBSTRG(outconv) == nullptr) { return contents; } /* flag */ last_feed = ((status & k_PHP_OUTPUT_HANDLER_END) != 0); /* mode */ mbfl_buffer_converter_illegal_mode (MBSTRG(outconv), MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (MBSTRG(outconv), MBSTRG(current_filter_illegal_substchar)); /* feed the string */ mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)contents.data(); string.len = contents.size(); mbfl_buffer_converter_feed(MBSTRG(outconv), &string); if (last_feed) { mbfl_buffer_converter_flush(MBSTRG(outconv)); } /* get the converter output, and return it */ mbfl_buffer_converter_result(MBSTRG(outconv), &result); /* delete the converter if it is the last feed. */ if (last_feed) { MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv)); mbfl_buffer_converter_delete(MBSTRG(outconv)); MBSTRG(outconv) = nullptr; } return String(reinterpret_cast<char*>(result.val), result.len, AttachString); } typedef struct _php_mb_encoding_handler_info_t { int data_type; const char *separator; unsigned int force_register_globals: 1; unsigned int report_errors: 1; enum mbfl_no_language to_language; mbfl_encoding *to_encoding; enum mbfl_no_language from_language; int num_from_encodings; mbfl_encoding **from_encodings; } php_mb_encoding_handler_info_t; static mbfl_encoding* _php_mb_encoding_handler_ex (const php_mb_encoding_handler_info_t *info, Array& arg, char *res) { char *var, *val; const char *s1, *s2; char *strtok_buf = nullptr, **val_list = nullptr; int n, num, *len_list = nullptr; unsigned int val_len; mbfl_string string, resvar, resval; mbfl_encoding *from_encoding = nullptr; mbfl_encoding_detector *identd = nullptr; mbfl_buffer_converter *convd = nullptr; mbfl_string_init_set(&string, info->to_language, info->to_encoding->no_encoding); mbfl_string_init_set(&resvar, info->to_language, info->to_encoding->no_encoding); mbfl_string_init_set(&resval, info->to_language, info->to_encoding->no_encoding); if (!res || *res == '\0') { goto out; } /* count the variables(separators) contained in the "res". * separator may contain multiple separator chars. */ num = 1; for (s1=res; *s1 != '\0'; s1++) { for (s2=info->separator; *s2 != '\0'; s2++) { if (*s1 == *s2) { num++; } } } num *= 2; /* need space for variable name and value */ val_list = (char **)calloc(num, sizeof(char *)); len_list = (int *)calloc(num, sizeof(int)); /* split and decode the query */ n = 0; strtok_buf = nullptr; var = strtok_r(res, info->separator, &strtok_buf); while (var) { val = strchr(var, '='); if (val) { /* have a value */ len_list[n] = url_decode_ex(var, val-var); val_list[n] = var; n++; *val++ = '\0'; val_list[n] = val; len_list[n] = url_decode_ex(val, strlen(val)); } else { len_list[n] = url_decode_ex(var, strlen(var)); val_list[n] = var; n++; val_list[n] = const_cast<char*>(""); len_list[n] = 0; } n++; var = strtok_r(nullptr, info->separator, &strtok_buf); } num = n; /* make sure to process initilized vars only */ /* initialize converter */ if (info->num_from_encodings <= 0) { from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } else if (info->num_from_encodings == 1) { from_encoding = info->from_encodings[0]; } else { /* auto detect */ from_encoding = nullptr; identd = mbfl_encoding_detector_new ((enum mbfl_no_encoding *)info->from_encodings, info->num_from_encodings, MBSTRG(strict_detection)); if (identd) { n = 0; while (n < num) { string.val = (unsigned char *)val_list[n]; string.len = len_list[n]; if (mbfl_encoding_detector_feed(identd, &string)) { break; } n++; } from_encoding = (mbfl_encoding*) mbfl_encoding_detector_judge2(identd); mbfl_encoding_detector_delete(identd); } if (from_encoding == nullptr) { if (info->report_errors) { raise_warning("Unable to detect encoding"); } from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } } convd = nullptr; if (from_encoding != (mbfl_encoding*) &mbfl_encoding_pass) { convd = mbfl_buffer_converter_new2(from_encoding, info->to_encoding, 0); if (convd != nullptr) { mbfl_buffer_converter_illegal_mode (convd, MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (convd, MBSTRG(current_filter_illegal_substchar)); } else { if (info->report_errors) { raise_warning("Unable to create converter"); } goto out; } } /* convert encoding */ string.no_encoding = from_encoding->no_encoding; n = 0; while (n < num) { string.val = (unsigned char *)val_list[n]; string.len = len_list[n]; if (convd != nullptr && mbfl_buffer_converter_feed_result(convd, &string, &resvar) != nullptr) { var = (char *)resvar.val; } else { var = val_list[n]; } n++; string.val = (unsigned char *)val_list[n]; string.len = len_list[n]; if (convd != nullptr && mbfl_buffer_converter_feed_result(convd, &string, &resval) != nullptr) { val = (char *)resval.val; val_len = resval.len; } else { val = val_list[n]; val_len = len_list[n]; } n++; arg.set(String(var, CopyString), String(val, val_len, CopyString)); if (convd != nullptr) { mbfl_string_clear(&resvar); mbfl_string_clear(&resval); } } out: if (convd != nullptr) { MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); } if (val_list != nullptr) { free((void *)val_list); } if (len_list != nullptr) { free((void *)len_list); } return from_encoding; } bool HHVM_FUNCTION(mb_parse_str, const String& encoded_string, VRefParam result /* = null */) { php_mb_encoding_handler_info_t info; info.data_type = PARSE_STRING; info.separator = ";&"; info.force_register_globals = false; info.report_errors = 1; info.to_encoding = MBSTRG(current_internal_encoding); info.to_language = MBSTRG(current_language); info.from_encodings = MBSTRG(http_input_list); info.num_from_encodings = MBSTRG(http_input_list_size); info.from_language = MBSTRG(current_language); char *encstr = strndup(encoded_string.data(), encoded_string.size()); Array resultArr = Array::Create(); mbfl_encoding *detected = _php_mb_encoding_handler_ex(&info, resultArr, encstr); free(encstr); result.assignIfRef(resultArr); MBSTRG(http_input_identify) = detected; return detected != nullptr; } Variant HHVM_FUNCTION(mb_preferred_mime_name, const String& encoding) { mbfl_no_encoding no_encoding = mbfl_name2no_encoding(encoding.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } const char *preferred_name = mbfl_no2preferred_mime_name(no_encoding); if (preferred_name == nullptr || *preferred_name == '\0') { raise_warning("No MIME preferred name corresponding to \"%s\"", encoding.data()); return false; } return String(preferred_name, CopyString); } static Variant php_mb_substr(const String& str, int from, const Variant& vlen, const String& encoding, bool substr) { mbfl_string string; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); if (!encoding.empty()) { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } int len = vlen.toInt64(); int size = 0; if (substr) { int size_tmp = -1; if (vlen.isNull() || len == 0x7FFFFFFF) { size_tmp = mbfl_strlen(&string); len = size_tmp; } if (from < 0 || len < 0) { size = size_tmp < 0 ? mbfl_strlen(&string) : size_tmp; } } else { size = str.size(); if (vlen.isNull() || len == 0x7FFFFFFF) { len = size; } } /* if "from" position is negative, count start position from the end * of the string */ if (from < 0) { from = size + from; if (from < 0) { from = 0; } } /* if "length" position is negative, set it to the length * needed to stop that many chars from the end of the string */ if (len < 0) { len = (size - from) + len; if (len < 0) { len = 0; } } if (!substr && from > size) { return false; } mbfl_string result; mbfl_string *ret; if (substr) { ret = mbfl_substr(&string, &result, from, len); } else { ret = mbfl_strcut(&string, &result, from, len); } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_substr, const String& str, int start, const Variant& length /*= uninit_null() */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); return php_mb_substr(str, start, length, encoding, true); } Variant HHVM_FUNCTION(mb_strcut, const String& str, int start, const Variant& length /*= uninit_null() */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); return php_mb_substr(str, start, length, encoding, false); } Variant HHVM_FUNCTION(mb_strimwidth, const String& str, int start, int width, const Variant& opt_trimmarker, const Variant& opt_encoding) { const String trimmarker = convertArg(opt_trimmarker); const String encoding = convertArg(opt_encoding); mbfl_string string, result, marker, *ret; mbfl_string_init(&string); mbfl_string_init(&marker); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; marker.no_language = MBSTRG(current_language); marker.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; marker.val = nullptr; marker.len = 0; if (!encoding.empty()) { string.no_encoding = marker.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } string.val = (unsigned char *)str.data(); string.len = str.size(); if (start < 0 || start > str.size()) { raise_warning("Start position is out of reange"); return false; } if (width < 0) { raise_warning("Width is negative value"); return false; } marker.val = (unsigned char *)trimmarker.data(); marker.len = trimmarker.size(); ret = mbfl_strimwidth(&string, &marker, &result, start, width); if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_stripos, const String& haystack, const String& needle, int offset /* = 0 */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } if (needle.empty()) { raise_warning("Empty delimiter"); return false; } int n = php_mb_stripos(0, haystack.data(), haystack.size(), needle.data(), needle.size(), offset, from_encoding); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_strripos, const String& haystack, const String& needle, int offset /* = 0 */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } int n = php_mb_stripos(1, haystack.data(), haystack.size(), needle.data(), needle.size(), offset, from_encoding); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_stristr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!mbs_needle.len) { raise_warning("Empty delimiter."); return false; } const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(from_encoding); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", from_encoding); return false; } int n = php_mb_stripos(0, (const char*)mbs_haystack.val, mbs_haystack.len, (const char *)mbs_needle.val, mbs_needle.len, 0, from_encoding); if (n < 0) { return false; } int mblen = mbfl_strlen(&mbs_haystack); mbfl_string result, *ret = nullptr; if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strlen, const String& str, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string string; mbfl_string_init(&string); string.val = (unsigned char *)str.data(); string.len = str.size(); string.no_language = MBSTRG(current_language); if (encoding.empty()) { string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; } else { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } int n = mbfl_strlen(&string); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_strpos, const String& haystack, const String& needle, int offset /* = 0 */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (offset < 0 || offset > mbfl_strlen(&mbs_haystack)) { raise_warning("Offset not contained in string."); return false; } if (mbs_needle.len == 0) { raise_warning("Empty delimiter."); return false; } int reverse = 0; int n = mbfl_strpos(&mbs_haystack, &mbs_needle, offset, reverse); if (n >= 0) { return n; } switch (-n) { case 1: break; case 2: raise_warning("Needle has not positive length."); break; case 4: raise_warning("Unknown encoding or conversion error."); break; case 8: raise_warning("Argument is empty."); break; default: raise_warning("Unknown error in mb_strpos."); break; } return false; } Variant HHVM_FUNCTION(mb_strrpos, const String& haystack, const String& needle, const Variant& offset /* = 0LL */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); const char *enc_name = encoding.data(); long noffset = 0; String soffset = offset.toString(); if (offset.isString()) { enc_name = soffset.data(); int str_flg = 1; if (enc_name != nullptr) { switch (*enc_name) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ' ': case '-': case '.': break; default : str_flg = 0; break; } } if (str_flg) { noffset = offset.toInt32(); enc_name = encoding.data(); } } else { noffset = offset.toInt32(); } if (!enc_name && !*enc_name) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(enc_name); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", enc_name); return false; } } if (mbs_haystack.len <= 0) { return false; } if (mbs_needle.len <= 0) { return false; } if ((noffset > 0 && noffset > mbfl_strlen(&mbs_haystack)) || (noffset < 0 && -noffset > mbfl_strlen(&mbs_haystack))) { raise_notice("Offset is greater than the length of haystack string"); return false; } int n = mbfl_strpos(&mbs_haystack, &mbs_needle, noffset, 1); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_strrchr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (mbs_haystack.len <= 0) { return false; } if (mbs_needle.len <= 0) { return false; } mbfl_string result, *ret = nullptr; int n = mbfl_strpos(&mbs_haystack, &mbs_needle, 0, 1); if (n >= 0) { int mblen = mbfl_strlen(&mbs_haystack); if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strrichr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(from_encoding); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", from_encoding); return false; } int n = php_mb_stripos(1, (const char*)mbs_haystack.val, mbs_haystack.len, (const char*)mbs_needle.val, mbs_needle.len, 0, from_encoding); if (n < 0) { return false; } mbfl_string result, *ret = nullptr; int mblen = mbfl_strlen(&mbs_haystack); if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strstr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (mbs_needle.len <= 0) { raise_warning("Empty delimiter."); return false; } mbfl_string result, *ret = nullptr; int n = mbfl_strpos(&mbs_haystack, &mbs_needle, 0, 0); if (n >= 0) { int mblen = mbfl_strlen(&mbs_haystack); if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strtolower, const String& str, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } unsigned int ret_len; char *newstr = php_unicode_convert_case(PHP_UNICODE_CASE_LOWER, str.data(), str.size(), &ret_len, from_encoding); if (newstr) { return String(newstr, ret_len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strtoupper, const String& str, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } unsigned int ret_len; char *newstr = php_unicode_convert_case(PHP_UNICODE_CASE_UPPER, str.data(), str.size(), &ret_len, from_encoding); if (newstr) { return String(newstr, ret_len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strwidth, const String& str, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string string; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); if (!encoding.empty()) { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } int n = mbfl_strwidth(&string); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_substitute_character, const Variant& substrchar /* = null_variant */) { if (substrchar.isNull()) { switch (MBSTRG(current_filter_illegal_mode)) { case MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE: return "none"; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG: return "long"; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY: return "entity"; default: return MBSTRG(current_filter_illegal_substchar); } } if (substrchar.isString()) { String s = substrchar.toString(); if (strcasecmp("none", s.data()) == 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE; return true; } if (strcasecmp("long", s.data()) == 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG; return true; } if (strcasecmp("entity", s.data()) == 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY; return true; } } int64_t n = substrchar.toInt64(); if (n < 0xffff && n > 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR; MBSTRG(current_filter_illegal_substchar) = n; } else { raise_warning("Unknown character."); return false; } return true; } Variant HHVM_FUNCTION(mb_substr_count, const String& haystack, const String& needle, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (mbs_needle.len <= 0) { raise_warning("Empty substring."); return false; } int n = mbfl_substr_count(&mbs_haystack, &mbs_needle); if (n >= 0) { return n; } return false; } /////////////////////////////////////////////////////////////////////////////// // regex helpers typedef struct _php_mb_regex_enc_name_map_t { const char *names; OnigEncoding code; } php_mb_regex_enc_name_map_t; static php_mb_regex_enc_name_map_t enc_name_map[] ={ { "EUC-JP\0EUCJP\0X-EUC-JP\0UJIS\0EUCJP\0EUCJP-WIN\0", ONIG_ENCODING_EUC_JP }, { "UTF-8\0UTF8\0", ONIG_ENCODING_UTF8 }, { "UTF-16\0UTF-16BE\0", ONIG_ENCODING_UTF16_BE }, { "UTF-16LE\0", ONIG_ENCODING_UTF16_LE }, { "UCS-4\0UTF-32\0UTF-32BE\0", ONIG_ENCODING_UTF32_BE }, { "UCS-4LE\0UTF-32LE\0", ONIG_ENCODING_UTF32_LE }, { "SJIS\0CP932\0MS932\0SHIFT_JIS\0SJIS-WIN\0WINDOWS-31J\0", ONIG_ENCODING_SJIS }, { "BIG5\0BIG-5\0BIGFIVE\0CN-BIG5\0BIG-FIVE\0", ONIG_ENCODING_BIG5 }, { "EUC-CN\0EUCCN\0EUC_CN\0GB-2312\0GB2312\0", ONIG_ENCODING_EUC_CN }, { "EUC-TW\0EUCTW\0EUC_TW\0", ONIG_ENCODING_EUC_TW }, { "EUC-KR\0EUCKR\0EUC_KR\0", ONIG_ENCODING_EUC_KR }, { "KOI8R\0KOI8-R\0KOI-8R\0", ONIG_ENCODING_KOI8_R }, { "ISO-8859-1\0ISO8859-1\0ISO_8859_1\0ISO8859_1\0", ONIG_ENCODING_ISO_8859_1 }, { "ISO-8859-2\0ISO8859-2\0ISO_8859_2\0ISO8859_2\0", ONIG_ENCODING_ISO_8859_2 }, { "ISO-8859-3\0ISO8859-3\0ISO_8859_3\0ISO8859_3\0", ONIG_ENCODING_ISO_8859_3 }, { "ISO-8859-4\0ISO8859-4\0ISO_8859_4\0ISO8859_4\0", ONIG_ENCODING_ISO_8859_4 }, { "ISO-8859-5\0ISO8859-5\0ISO_8859_5\0ISO8859_5\0", ONIG_ENCODING_ISO_8859_5 }, { "ISO-8859-6\0ISO8859-6\0ISO_8859_6\0ISO8859_6\0", ONIG_ENCODING_ISO_8859_6 }, { "ISO-8859-7\0ISO8859-7\0ISO_8859_7\0ISO8859_7\0", ONIG_ENCODING_ISO_8859_7 }, { "ISO-8859-8\0ISO8859-8\0ISO_8859_8\0ISO8859_8\0", ONIG_ENCODING_ISO_8859_8 }, { "ISO-8859-9\0ISO8859-9\0ISO_8859_9\0ISO8859_9\0", ONIG_ENCODING_ISO_8859_9 }, { "ISO-8859-10\0ISO8859-10\0ISO_8859_10\0ISO8859_10\0", ONIG_ENCODING_ISO_8859_10 }, { "ISO-8859-11\0ISO8859-11\0ISO_8859_11\0ISO8859_11\0", ONIG_ENCODING_ISO_8859_11 }, { "ISO-8859-13\0ISO8859-13\0ISO_8859_13\0ISO8859_13\0", ONIG_ENCODING_ISO_8859_13 }, { "ISO-8859-14\0ISO8859-14\0ISO_8859_14\0ISO8859_14\0", ONIG_ENCODING_ISO_8859_14 }, { "ISO-8859-15\0ISO8859-15\0ISO_8859_15\0ISO8859_15\0", ONIG_ENCODING_ISO_8859_15 }, { "ISO-8859-16\0ISO8859-16\0ISO_8859_16\0ISO8859_16\0", ONIG_ENCODING_ISO_8859_16 }, { "ASCII\0US-ASCII\0US_ASCII\0ISO646\0", ONIG_ENCODING_ASCII }, { nullptr, ONIG_ENCODING_UNDEF } }; static OnigEncoding php_mb_regex_name2mbctype(const char *pname) { const char *p; php_mb_regex_enc_name_map_t *mapping; if (pname == nullptr) { return ONIG_ENCODING_UNDEF; } for (mapping = enc_name_map; mapping->names != nullptr; mapping++) { for (p = mapping->names; *p != '\0'; p += (strlen(p) + 1)) { if (strcasecmp(p, pname) == 0) { return mapping->code; } } } return ONIG_ENCODING_UNDEF; } static const char *php_mb_regex_mbctype2name(OnigEncoding mbctype) { php_mb_regex_enc_name_map_t *mapping; for (mapping = enc_name_map; mapping->names != nullptr; mapping++) { if (mapping->code == mbctype) { return mapping->names; } } return nullptr; } /* * regex cache */ static php_mb_regex_t *php_mbregex_compile_pattern(const String& pattern, OnigOptionType options, OnigEncoding enc, OnigSyntaxType *syntax) { int err_code = 0; OnigErrorInfo err_info; OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; php_mb_regex_t *rc = nullptr; std::string spattern = std::string(pattern.data(), pattern.size()); RegexCache &cache = MBSTRG(ht_rc); RegexCache::const_iterator it = cache.find(spattern); if (it != cache.end()) { rc = it->second; } if (!rc || rc->options != options || rc->enc != enc || rc->syntax != syntax) { if (rc) { onig_free(rc); rc = nullptr; } if ((err_code = onig_new(&rc, (OnigUChar *)pattern.data(), (OnigUChar *)(pattern.data() + pattern.size()), options,enc, syntax, &err_info)) != ONIG_NORMAL) { onig_error_code_to_str(err_str, err_code, err_info); raise_warning("mbregex compile err: %s", err_str); return nullptr; } MBSTRG(ht_rc)[spattern] = rc; } return rc; } static size_t _php_mb_regex_get_option_string(char *str, size_t len, OnigOptionType option, OnigSyntaxType *syntax) { size_t len_left = len; size_t len_req = 0; char *p = str; char c; if ((option & ONIG_OPTION_IGNORECASE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'i'; } ++len_req; } if ((option & ONIG_OPTION_EXTEND) != 0) { if (len_left > 0) { --len_left; *(p++) = 'x'; } ++len_req; } if ((option & (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) == (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) { if (len_left > 0) { --len_left; *(p++) = 'p'; } ++len_req; } else { if ((option & ONIG_OPTION_MULTILINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'm'; } ++len_req; } if ((option & ONIG_OPTION_SINGLELINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 's'; } ++len_req; } } if ((option & ONIG_OPTION_FIND_LONGEST) != 0) { if (len_left > 0) { --len_left; *(p++) = 'l'; } ++len_req; } if ((option & ONIG_OPTION_FIND_NOT_EMPTY) != 0) { if (len_left > 0) { --len_left; *(p++) = 'n'; } ++len_req; } c = 0; if (syntax == ONIG_SYNTAX_JAVA) { c = 'j'; } else if (syntax == ONIG_SYNTAX_GNU_REGEX) { c = 'u'; } else if (syntax == ONIG_SYNTAX_GREP) { c = 'g'; } else if (syntax == ONIG_SYNTAX_EMACS) { c = 'c'; } else if (syntax == ONIG_SYNTAX_RUBY) { c = 'r'; } else if (syntax == ONIG_SYNTAX_PERL) { c = 'z'; } else if (syntax == ONIG_SYNTAX_POSIX_BASIC) { c = 'b'; } else if (syntax == ONIG_SYNTAX_POSIX_EXTENDED) { c = 'd'; } if (c != 0) { if (len_left > 0) { --len_left; *(p++) = c; } ++len_req; } if (len_left > 0) { --len_left; *(p++) = '\0'; } ++len_req; if (len < len_req) { return len_req; } return 0; } static void _php_mb_regex_init_options(const char *parg, int narg, OnigOptionType *option, OnigSyntaxType **syntax, int *eval) { int n; char c; int optm = 0; *syntax = ONIG_SYNTAX_RUBY; if (parg != nullptr) { n = 0; while (n < narg) { c = parg[n++]; switch (c) { case 'i': optm |= ONIG_OPTION_IGNORECASE; break; case 'x': optm |= ONIG_OPTION_EXTEND; break; case 'm': optm |= ONIG_OPTION_MULTILINE; break; case 's': optm |= ONIG_OPTION_SINGLELINE; break; case 'p': optm |= ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE; break; case 'l': optm |= ONIG_OPTION_FIND_LONGEST; break; case 'n': optm |= ONIG_OPTION_FIND_NOT_EMPTY; break; case 'j': *syntax = ONIG_SYNTAX_JAVA; break; case 'u': *syntax = ONIG_SYNTAX_GNU_REGEX; break; case 'g': *syntax = ONIG_SYNTAX_GREP; break; case 'c': *syntax = ONIG_SYNTAX_EMACS; break; case 'r': *syntax = ONIG_SYNTAX_RUBY; break; case 'z': *syntax = ONIG_SYNTAX_PERL; break; case 'b': *syntax = ONIG_SYNTAX_POSIX_BASIC; break; case 'd': *syntax = ONIG_SYNTAX_POSIX_EXTENDED; break; case 'e': if (eval != nullptr) *eval = 1; break; default: break; } } if (option != nullptr) *option|=optm; } } /////////////////////////////////////////////////////////////////////////////// // regex functions bool HHVM_FUNCTION(mb_ereg_match, const String& pattern, const String& str, const Variant& opt_option) { const String option = convertArg(opt_option); OnigSyntaxType *syntax; OnigOptionType noption = 0; if (!option.empty()) { _php_mb_regex_init_options(option.data(), option.size(), &noption, &syntax, nullptr); } else { noption |= MBSTRG(regex_default_options); syntax = MBSTRG(regex_default_syntax); } php_mb_regex_t *re; if ((re = php_mbregex_compile_pattern (pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) { return false; } /* match */ int err = onig_match(re, (OnigUChar *)str.data(), (OnigUChar *)(str.data() + str.size()), (OnigUChar *)str.data(), nullptr, 0); return err >= 0; } static Variant _php_mb_regex_ereg_replace_exec(const Variant& pattern, const String& replacement, const String& str, const String& option, OnigOptionType options) { const char *p; php_mb_regex_t *re; OnigSyntaxType *syntax; OnigRegion *regs = nullptr; StringBuffer out_buf; int i, err, eval, n; OnigUChar *pos; OnigUChar *string_lim; char pat_buf[2]; const mbfl_encoding *enc; { const char *current_enc_name; current_enc_name = php_mb_regex_mbctype2name(MBSTRG(current_mbctype)); if (current_enc_name == nullptr || (enc = mbfl_name2encoding(current_enc_name)) == nullptr) { raise_warning("Unknown error"); return false; } } eval = 0; { if (!option.empty()) { _php_mb_regex_init_options(option.data(), option.size(), &options, &syntax, &eval); } else { options |= MBSTRG(regex_default_options); syntax = MBSTRG(regex_default_syntax); } } String spattern; if (pattern.isString()) { spattern = pattern.toString(); } else { /* FIXME: this code is not multibyte aware! */ pat_buf[0] = pattern.toByte(); pat_buf[1] = '\0'; spattern = String(pat_buf, 1, CopyString); } /* create regex pattern buffer */ re = php_mbregex_compile_pattern(spattern, options, MBSTRG(current_mbctype), syntax); if (re == nullptr) { return false; } if (eval) { throw_not_supported("ereg_replace", "dynamic coding"); } /* do the actual work */ err = 0; pos = (OnigUChar*)str.data(); string_lim = (OnigUChar*)(str.data() + str.size()); regs = onig_region_new(); while (err >= 0) { err = onig_search(re, (OnigUChar *)str.data(), (OnigUChar *)string_lim, pos, (OnigUChar *)string_lim, regs, 0); if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); raise_warning("mbregex search failure: %s", err_str); break; } if (err >= 0) { #if moriyoshi_0 if (regs->beg[0] == regs->end[0]) { raise_warning("Empty regular expression"); break; } #endif /* copy the part of the string before the match */ out_buf.append((const char *)pos, (OnigUChar *)(str.data() + regs->beg[0]) - pos); /* copy replacement and backrefs */ i = 0; p = replacement.data(); while (i < replacement.size()) { int fwd = (int)php_mb_mbchar_bytes_ex(p, enc); n = -1; if ((replacement.size() - i) >= 2 && fwd == 1 && p[0] == '\\' && p[1] >= '0' && p[1] <= '9') { n = p[1] - '0'; } if (n >= 0 && n < regs->num_regs) { if (regs->beg[n] >= 0 && regs->beg[n] < regs->end[n] && regs->end[n] <= str.size()) { out_buf.append(str.data() + regs->beg[n], regs->end[n] - regs->beg[n]); } p += 2; i += 2; } else { out_buf.append(p, fwd); p += fwd; i += fwd; } } n = regs->end[0]; if ((pos - (OnigUChar *)str.data()) < n) { pos = (OnigUChar *)(str.data() + n); } else { if (pos < string_lim) { out_buf.append((const char *)pos, 1); } pos++; } } else { /* nomatch */ /* stick that last bit of string on our output */ if (string_lim - pos > 0) { out_buf.append((const char *)pos, string_lim - pos); } } onig_region_free(regs, 0); } if (regs != nullptr) { onig_region_free(regs, 1); } if (err <= -2) { return false; } return out_buf.detach(); } Variant HHVM_FUNCTION(mb_ereg_replace, const Variant& pattern, const String& replacement, const String& str, const Variant& opt_option) { const String option = convertArg(opt_option); return _php_mb_regex_ereg_replace_exec(pattern, replacement, str, option, 0); } Variant HHVM_FUNCTION(mb_eregi_replace, const Variant& pattern, const String& replacement, const String& str, const Variant& opt_option) { const String option = convertArg(opt_option); return _php_mb_regex_ereg_replace_exec(pattern, replacement, str, option, ONIG_OPTION_IGNORECASE); } int64_t HHVM_FUNCTION(mb_ereg_search_getpos) { return MBSTRG(search_pos); } bool HHVM_FUNCTION(mb_ereg_search_setpos, int position) { if (position < 0 || position >= (int)MBSTRG(search_str).size()) { raise_warning("Position is out of range"); MBSTRG(search_pos) = 0; return false; } MBSTRG(search_pos) = position; return true; } Variant HHVM_FUNCTION(mb_ereg_search_getregs) { OnigRegion *search_regs = MBSTRG(search_regs); if (search_regs && !MBSTRG(search_str).empty()) { Array ret; OnigUChar *str = (OnigUChar *)MBSTRG(search_str).data(); int len = MBSTRG(search_str).size(); int n = search_regs->num_regs; for (int i = 0; i < n; i++) { int beg = search_regs->beg[i]; int end = search_regs->end[i]; if (beg >= 0 && beg <= end && end <= len) { ret.append(String((const char *)(str + beg), end - beg, CopyString)); } else { ret.append(false); } } return ret; } return false; } bool HHVM_FUNCTION(mb_ereg_search_init, const String& str, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); OnigOptionType noption = MBSTRG(regex_default_options); OnigSyntaxType *syntax = MBSTRG(regex_default_syntax); if (!option.empty()) { noption = 0; _php_mb_regex_init_options(option.data(), option.size(), &noption, &syntax, nullptr); } if (!pattern.empty()) { if ((MBSTRG(search_re) = php_mbregex_compile_pattern (pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) { return false; } } MBSTRG(search_str) = std::string(str.data(), str.size()); MBSTRG(search_pos) = 0; if (MBSTRG(search_regs) != nullptr) { onig_region_free(MBSTRG(search_regs), 1); MBSTRG(search_regs) = (OnigRegion *)nullptr; } return true; } /* regex search */ static Variant _php_mb_regex_ereg_search_exec(const String& pattern, const String& option, int mode) { int n, i, err, pos, len, beg, end; OnigUChar *str; OnigSyntaxType *syntax = MBSTRG(regex_default_syntax); OnigOptionType noption; noption = MBSTRG(regex_default_options); if (!option.empty()) { noption = 0; _php_mb_regex_init_options(option.data(), option.size(), &noption, &syntax, nullptr); } if (!pattern.empty()) { if ((MBSTRG(search_re) = php_mbregex_compile_pattern (pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) { return false; } } pos = MBSTRG(search_pos); str = nullptr; len = 0; if (!MBSTRG(search_str).empty()) { str = (OnigUChar *)MBSTRG(search_str).data(); len = MBSTRG(search_str).size(); } if (MBSTRG(search_re) == nullptr) { raise_warning("No regex given"); return false; } if (str == nullptr) { raise_warning("No string given"); return false; } if (MBSTRG(search_regs)) { onig_region_free(MBSTRG(search_regs), 1); } MBSTRG(search_regs) = onig_region_new(); err = onig_search(MBSTRG(search_re), str, str + len, str + pos, str + len, MBSTRG(search_regs), 0); Variant ret; if (err == ONIG_MISMATCH) { MBSTRG(search_pos) = len; ret = false; } else if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); raise_warning("mbregex search failure in mbregex_search(): %s", err_str); ret = false; } else { if (MBSTRG(search_regs)->beg[0] == MBSTRG(search_regs)->end[0]) { raise_warning("Empty regular expression"); } switch (mode) { case 1: { beg = MBSTRG(search_regs)->beg[0]; end = MBSTRG(search_regs)->end[0]; ret = make_packed_array(beg, end - beg); } break; case 2: n = MBSTRG(search_regs)->num_regs; ret = Variant(Array::Create()); for (i = 0; i < n; i++) { beg = MBSTRG(search_regs)->beg[i]; end = MBSTRG(search_regs)->end[i]; if (beg >= 0 && beg <= end && end <= len) { ret.toArrRef().append( String((const char *)(str + beg), end - beg, CopyString)); } else { ret.toArrRef().append(false); } } break; default: ret = true; break; } end = MBSTRG(search_regs)->end[0]; if (pos < end) { MBSTRG(search_pos) = end; } else { MBSTRG(search_pos) = pos + 1; } } if (err < 0) { onig_region_free(MBSTRG(search_regs), 1); MBSTRG(search_regs) = (OnigRegion *)nullptr; } return ret; } Variant HHVM_FUNCTION(mb_ereg_search, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); return _php_mb_regex_ereg_search_exec(pattern, option, 0); } Variant HHVM_FUNCTION(mb_ereg_search_pos, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); return _php_mb_regex_ereg_search_exec(pattern, option, 1); } Variant HHVM_FUNCTION(mb_ereg_search_regs, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); return _php_mb_regex_ereg_search_exec(pattern, option, 2); } static Variant _php_mb_regex_ereg_exec(const Variant& pattern, const String& str, Variant *regs, int icase) { php_mb_regex_t *re; OnigRegion *regions = nullptr; int i, match_len, beg, end; OnigOptionType options; options = MBSTRG(regex_default_options); if (icase) { options |= ONIG_OPTION_IGNORECASE; } /* compile the regular expression from the supplied regex */ String spattern; if (!pattern.isString()) { /* we convert numbers to integers and treat them as a string */ if (pattern.is(KindOfDouble)) { spattern = String(pattern.toInt64()); /* get rid of decimal places */ } else { spattern = pattern.toString(); } } else { spattern = pattern.toString(); } re = php_mbregex_compile_pattern(spattern, options, MBSTRG(current_mbctype), MBSTRG(regex_default_syntax)); if (re == nullptr) { return false; } regions = onig_region_new(); /* actually execute the regular expression */ if (onig_search(re, (OnigUChar *)str.data(), (OnigUChar *)(str.data() + str.size()), (OnigUChar *)str.data(), (OnigUChar *)(str.data() + str.size()), regions, 0) < 0) { onig_region_free(regions, 1); return false; } const char *s = str.data(); int string_len = str.size(); match_len = regions->end[0] - regions->beg[0]; PackedArrayInit regsPai(regions->num_regs); for (i = 0; i < regions->num_regs; i++) { beg = regions->beg[i]; end = regions->end[i]; if (beg >= 0 && beg < end && end <= string_len) { regsPai.append(String(s + beg, end - beg, CopyString)); } else { regsPai.append(false); } } if (regs) *regs = regsPai.toArray(); if (match_len == 0) { match_len = 1; } if (regions != nullptr) { onig_region_free(regions, 1); } return match_len; } Variant HHVM_FUNCTION(mb_ereg, const Variant& pattern, const String& str, VRefParam regs /* = null */) { return _php_mb_regex_ereg_exec(pattern, str, regs.getVariantOrNull(), 0); } Variant HHVM_FUNCTION(mb_eregi, const Variant& pattern, const String& str, VRefParam regs /* = null */) { return _php_mb_regex_ereg_exec(pattern, str, regs.getVariantOrNull(), 1); } Variant HHVM_FUNCTION(mb_regex_encoding, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); if (encoding.empty()) { const char *retval = php_mb_regex_mbctype2name(MBSTRG(current_mbctype)); if (retval != nullptr) { return String(retval, CopyString); } return false; } OnigEncoding mbctype = php_mb_regex_name2mbctype(encoding.data()); if (mbctype == ONIG_ENCODING_UNDEF) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } MBSTRG(current_mbctype) = mbctype; return true; } static void php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax) { if (prev_options != nullptr) { *prev_options = MBSTRG(regex_default_options); } if (prev_syntax != nullptr) { *prev_syntax = MBSTRG(regex_default_syntax); } MBSTRG(regex_default_options) = options; MBSTRG(regex_default_syntax) = syntax; } String HHVM_FUNCTION(mb_regex_set_options, const Variant& opt_options) { const String options = convertArg(opt_options); OnigOptionType opt; OnigSyntaxType *syntax; char buf[16]; if (!options.empty()) { opt = 0; syntax = nullptr; _php_mb_regex_init_options(options.data(), options.size(), &opt, &syntax, nullptr); php_mb_regex_set_options(opt, syntax, nullptr, nullptr); } else { opt = MBSTRG(regex_default_options); syntax = MBSTRG(regex_default_syntax); } _php_mb_regex_get_option_string(buf, sizeof(buf), opt, syntax); return String(buf, CopyString); } Variant HHVM_FUNCTION(mb_split, const String& pattern, const String& str, int count /* = -1 */) { php_mb_regex_t *re; OnigRegion *regs = nullptr; int n, err; if (count == 0) { count = 1; } /* create regex pattern buffer */ if ((re = php_mbregex_compile_pattern(pattern, MBSTRG(regex_default_options), MBSTRG(current_mbctype), MBSTRG(regex_default_syntax))) == nullptr) { return false; } Array ret; OnigUChar *pos0 = (OnigUChar *)str.data(); OnigUChar *pos_end = (OnigUChar *)(str.data() + str.size()); OnigUChar *pos = pos0; err = 0; regs = onig_region_new(); /* churn through str, generating array entries as we go */ while ((--count != 0) && (err = onig_search(re, pos0, pos_end, pos, pos_end, regs, 0)) >= 0) { if (regs->beg[0] == regs->end[0]) { raise_warning("Empty regular expression"); break; } /* add it to the array */ if (regs->beg[0] < str.size() && regs->beg[0] >= (pos - pos0)) { ret.append(String((const char *)pos, ((OnigUChar *)(str.data() + regs->beg[0]) - pos), CopyString)); } else { err = -2; break; } /* point at our new starting point */ n = regs->end[0]; if ((pos - pos0) < n) { pos = pos0 + n; } if (count < 0) { count = 0; } onig_region_free(regs, 0); } onig_region_free(regs, 1); /* see if we encountered an error */ if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); raise_warning("mbregex search failure in mbsplit(): %s", err_str); return false; } /* otherwise we just have one last element to add to the array */ n = pos_end - pos; if (n > 0) { ret.append(String((const char *)pos, n, CopyString)); } else { ret.append(""); } return ret; } /////////////////////////////////////////////////////////////////////////////// #define SKIP_LONG_HEADER_SEP_MBSTRING(str, pos) \ if (str[pos] == '\r' && str[pos + 1] == '\n' && \ (str[pos + 2] == ' ' || str[pos + 2] == '\t')) { \ pos += 2; \ while (str[pos + 1] == ' ' || str[pos + 1] == '\t') { \ pos++; \ } \ continue; \ } static int _php_mbstr_parse_mail_headers(Array &ht, const char *str, size_t str_len) { const char *ps; size_t icnt; int state = 0; int crlf_state = -1; StringBuffer token; String fld_name, fld_val; ps = str; icnt = str_len; /* * C o n t e n t - T y p e : t e x t / h t m l \r\n * ^ ^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^ ^^^^ * state 0 1 2 3 * * C o n t e n t - T y p e : t e x t / h t m l \r\n * ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ * crlf_state -1 0 1 -1 * */ while (icnt > 0) { switch (*ps) { case ':': if (crlf_state == 1) { token.append('\r'); } if (state == 0 || state == 1) { fld_name = token.detach(); state = 2; } else { token.append(*ps); } crlf_state = 0; break; case '\n': if (crlf_state == -1) { goto out; } crlf_state = -1; break; case '\r': if (crlf_state == 1) { token.append('\r'); } else { crlf_state = 1; } break; case ' ': case '\t': if (crlf_state == -1) { if (state == 3) { /* continuing from the previous line */ state = 4; } else { /* simply skipping this new line */ state = 5; } } else { if (crlf_state == 1) { token.append('\r'); } if (state == 1 || state == 3) { token.append(*ps); } } crlf_state = 0; break; default: switch (state) { case 0: token.clear(); state = 1; break; case 2: if (crlf_state != -1) { token.clear(); state = 3; break; } /* break is missing intentionally */ case 3: if (crlf_state == -1) { fld_val = token.detach(); if (!fld_name.empty() && !fld_val.empty()) { /* FIXME: some locale free implementation is * really required here,,, */ ht.set(HHVM_FN(strtoupper)(fld_name), fld_val); } state = 1; } break; case 4: token.append(' '); state = 3; break; } if (crlf_state == 1) { token.append('\r'); } token.append(*ps); crlf_state = 0; break; } ps++, icnt--; } out: if (state == 2) { token.clear(); state = 3; } if (state == 3) { fld_val = token.detach(); if (!fld_name.empty() && !fld_val.empty()) { /* FIXME: some locale free implementation is * really required here,,, */ ht.set(HHVM_FN(strtoupper)(fld_name), fld_val); } } return state; } static int php_mail(const char *to, const char *subject, const char *message, const char *headers, const char *extra_cmd) { const char *sendmail_path = "/usr/sbin/sendmail -t -i"; String sendmail_cmd = sendmail_path; if (extra_cmd != nullptr) { sendmail_cmd += " "; sendmail_cmd += extra_cmd; } /* Since popen() doesn't indicate if the internal fork() doesn't work * (e.g. the shell can't be executed) we explicitly set it to 0 to be * sure we don't catch any older errno value. */ errno = 0; FILE *sendmail = popen(sendmail_cmd.data(), "w"); if (sendmail == nullptr) { raise_warning("Could not execute mail delivery program '%s'", sendmail_path); return 0; } if (EACCES == errno) { raise_warning("Permission denied: unable to execute shell to run " "mail delivery binary '%s'", sendmail_path); pclose(sendmail); return 0; } fprintf(sendmail, "To: %s\n", to); fprintf(sendmail, "Subject: %s\n", subject); if (headers != nullptr) { fprintf(sendmail, "%s\n", headers); } fprintf(sendmail, "\n%s\n", message); int ret = pclose(sendmail); #if defined(EX_TEMPFAIL) if ((ret != EX_OK) && (ret != EX_TEMPFAIL)) return 0; #elif defined(EX_OK) if (ret != EX_OK) return 0; #else if (ret != 0) return 0; #endif return 1; } bool HHVM_FUNCTION(mb_send_mail, const String& to, const String& subject, const String& message, const Variant& opt_headers, const Variant& opt_extra_cmd) { const String headers = convertArg(opt_headers); const String extra_cmd = convertArg(opt_extra_cmd); /* initialize */ /* automatic allocateable buffer for additional header */ mbfl_memory_device device; mbfl_memory_device_init(&device, 0, 0); mbfl_string orig_str, conv_str; mbfl_string_init(&orig_str); mbfl_string_init(&conv_str); /* character-set, transfer-encoding */ mbfl_no_encoding tran_cs, /* transfar text charset */ head_enc, /* header transfar encoding */ body_enc; /* body transfar encoding */ tran_cs = mbfl_no_encoding_utf8; head_enc = mbfl_no_encoding_base64; body_enc = mbfl_no_encoding_base64; const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language)); if (lang != nullptr) { tran_cs = lang->mail_charset; head_enc = lang->mail_header_encoding; body_enc = lang->mail_body_encoding; } Array ht_headers; if (!headers.empty()) { _php_mbstr_parse_mail_headers(ht_headers, headers.data(), headers.size()); } struct { unsigned int cnt_type:1; unsigned int cnt_trans_enc:1; } suppressed_hdrs = { 0, 0 }; static const StaticString s_CONTENT_TYPE("CONTENT-TYPE"); String s = ht_headers[s_CONTENT_TYPE].toString(); if (!s.isNull()) { char *tmp; char *param_name; char *charset = nullptr; char *p = const_cast<char*>(strchr(s.data(), ';')); if (p != nullptr) { /* skipping the padded spaces */ do { ++p; } while (*p == ' ' || *p == '\t'); if (*p != '\0') { if ((param_name = strtok_r(p, "= ", &tmp)) != nullptr) { if (strcasecmp(param_name, "charset") == 0) { mbfl_no_encoding _tran_cs = tran_cs; charset = strtok_r(nullptr, "= ", &tmp); if (charset != nullptr) { _tran_cs = mbfl_name2no_encoding(charset); } if (_tran_cs == mbfl_no_encoding_invalid) { raise_warning("Unsupported charset \"%s\" - " "will be regarded as ascii", charset); _tran_cs = mbfl_no_encoding_ascii; } tran_cs = _tran_cs; } } } } suppressed_hdrs.cnt_type = 1; } static const StaticString s_CONTENT_TRANSFER_ENCODING("CONTENT-TRANSFER-ENCODING"); s = ht_headers[s_CONTENT_TRANSFER_ENCODING].toString(); if (!s.isNull()) { mbfl_no_encoding _body_enc = mbfl_name2no_encoding(s.data()); switch (_body_enc) { case mbfl_no_encoding_base64: case mbfl_no_encoding_7bit: case mbfl_no_encoding_8bit: body_enc = _body_enc; break; default: raise_warning("Unsupported transfer encoding \"%s\" - " "will be regarded as 8bit", s.data()); body_enc = mbfl_no_encoding_8bit; break; } suppressed_hdrs.cnt_trans_enc = 1; } /* To: */ char *to_r = nullptr; int err = 0; if (!to.empty()) { int to_len = to.size(); if (to_len > 0) { to_r = strndup(to.data(), to_len); for (; to_len; to_len--) { if (!isspace((unsigned char)to_r[to_len - 1])) { break; } to_r[to_len - 1] = '\0'; } for (int i = 0; to_r[i]; i++) { if (iscntrl((unsigned char)to_r[i])) { /** * According to RFC 822, section 3.1.1 long headers may be * separated into parts using CRLF followed at least one * linear-white-space character ('\t' or ' '). * To prevent these separators from being replaced with a space, * we use the SKIP_LONG_HEADER_SEP_MBSTRING to skip over them. */ SKIP_LONG_HEADER_SEP_MBSTRING(to_r, i); to_r[i] = ' '; } } } else { to_r = (char*)to.data(); } } else { raise_warning("Missing To: field"); err = 1; } /* Subject: */ String encoded_subject; if (!subject.isNull()) { orig_str.no_language = MBSTRG(current_language); orig_str.val = (unsigned char *)subject.data(); orig_str.len = subject.size(); orig_str.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; if (orig_str.no_encoding == mbfl_no_encoding_invalid || orig_str.no_encoding == mbfl_no_encoding_pass) { mbfl_encoding *encoding = (mbfl_encoding*) mbfl_identify_encoding2(&orig_str, (const mbfl_encoding**) MBSTRG(current_detect_order_list), MBSTRG(current_detect_order_list_size), MBSTRG(strict_detection)); orig_str.no_encoding = encoding != nullptr ? encoding->no_encoding : mbfl_no_encoding_invalid; } mbfl_string *pstr = mbfl_mime_header_encode (&orig_str, &conv_str, tran_cs, head_enc, "\n", sizeof("Subject: [PHP-jp nnnnnnnn]")); if (pstr != nullptr) { encoded_subject = String(reinterpret_cast<char*>(pstr->val), pstr->len, AttachString); } } else { raise_warning("Missing Subject: field"); err = 1; } /* message body */ String encoded_message; if (!message.empty()) { orig_str.no_language = MBSTRG(current_language); orig_str.val = (unsigned char*)message.data(); orig_str.len = message.size(); orig_str.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; if (orig_str.no_encoding == mbfl_no_encoding_invalid || orig_str.no_encoding == mbfl_no_encoding_pass) { mbfl_encoding *encoding = (mbfl_encoding*) mbfl_identify_encoding2(&orig_str, (const mbfl_encoding**) MBSTRG(current_detect_order_list), MBSTRG(current_detect_order_list_size), MBSTRG(strict_detection)); orig_str.no_encoding = encoding != nullptr ? encoding->no_encoding : mbfl_no_encoding_invalid; } mbfl_string *pstr = nullptr; { mbfl_string tmpstr; if (mbfl_convert_encoding(&orig_str, &tmpstr, tran_cs) != nullptr) { tmpstr.no_encoding = mbfl_no_encoding_8bit; pstr = mbfl_convert_encoding(&tmpstr, &conv_str, body_enc); free(tmpstr.val); } } if (pstr != nullptr) { encoded_message = String(reinterpret_cast<char*>(pstr->val), pstr->len, AttachString); } } else { /* this is not really an error, so it is allowed. */ raise_warning("Empty message body"); } /* other headers */ #define PHP_MBSTR_MAIL_MIME_HEADER1 "Mime-Version: 1.0" #define PHP_MBSTR_MAIL_MIME_HEADER2 "Content-Type: text/plain" #define PHP_MBSTR_MAIL_MIME_HEADER3 "; charset=" #define PHP_MBSTR_MAIL_MIME_HEADER4 "Content-Transfer-Encoding: " if (!headers.empty()) { const char *p = headers.data(); int n = headers.size(); mbfl_memory_device_strncat(&device, p, n); if (n > 0 && p[n - 1] != '\n') { mbfl_memory_device_strncat(&device, "\n", 1); } } mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER1, sizeof(PHP_MBSTR_MAIL_MIME_HEADER1) - 1); mbfl_memory_device_strncat(&device, "\n", 1); if (!suppressed_hdrs.cnt_type) { mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER2, sizeof(PHP_MBSTR_MAIL_MIME_HEADER2) - 1); char *p = (char *)mbfl_no2preferred_mime_name(tran_cs); if (p != nullptr) { mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER3, sizeof(PHP_MBSTR_MAIL_MIME_HEADER3) - 1); mbfl_memory_device_strcat(&device, p); } mbfl_memory_device_strncat(&device, "\n", 1); } if (!suppressed_hdrs.cnt_trans_enc) { mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER4, sizeof(PHP_MBSTR_MAIL_MIME_HEADER4) - 1); const char *p = (char *)mbfl_no2preferred_mime_name(body_enc); if (p == nullptr) { p = "7bit"; } mbfl_memory_device_strcat(&device, p); mbfl_memory_device_strncat(&device, "\n", 1); } mbfl_memory_device_unput(&device); mbfl_memory_device_output('\0', &device); char *all_headers = (char *)device.buffer; String cmd = string_escape_shell_cmd(extra_cmd.c_str()); bool ret = (!err && php_mail(to_r, encoded_subject.data(), encoded_message.data(), all_headers, cmd.data())); mbfl_memory_device_clear(&device); return ret; } static struct mbstringExtension final : Extension { mbstringExtension() : Extension("mbstring", NO_EXTENSION_VERSION_YET) {} void moduleInit() override { // TODO make these PHP_INI_ALL and thread local once we use them IniSetting::Bind(this, IniSetting::PHP_INI_SYSTEM, "mbstring.http_input", &http_input); IniSetting::Bind(this, IniSetting::PHP_INI_SYSTEM, "mbstring.http_output", &http_output); IniSetting::Bind(this, IniSetting::PHP_INI_ALL, "mbstring.substitute_character", &MBSTRG(current_filter_illegal_mode)); HHVM_RC_INT(MB_OVERLOAD_MAIL, 1); HHVM_RC_INT(MB_OVERLOAD_STRING, 2); HHVM_RC_INT(MB_OVERLOAD_REGEX, 4); HHVM_RC_INT(MB_CASE_UPPER, PHP_UNICODE_CASE_UPPER); HHVM_RC_INT(MB_CASE_LOWER, PHP_UNICODE_CASE_LOWER); HHVM_RC_INT(MB_CASE_TITLE, PHP_UNICODE_CASE_TITLE); HHVM_FE(mb_list_encodings); HHVM_FE(mb_list_encodings_alias_names); HHVM_FE(mb_list_mime_names); HHVM_FE(mb_check_encoding); HHVM_FE(mb_convert_case); HHVM_FE(mb_convert_encoding); HHVM_FE(mb_convert_kana); HHVM_FE(mb_convert_variables); HHVM_FE(mb_decode_mimeheader); HHVM_FE(mb_decode_numericentity); HHVM_FE(mb_detect_encoding); HHVM_FE(mb_detect_order); HHVM_FE(mb_encode_mimeheader); HHVM_FE(mb_encode_numericentity); HHVM_FE(mb_encoding_aliases); HHVM_FE(mb_ereg_match); HHVM_FE(mb_ereg_replace); HHVM_FE(mb_ereg_search_getpos); HHVM_FE(mb_ereg_search_getregs); HHVM_FE(mb_ereg_search_init); HHVM_FE(mb_ereg_search_pos); HHVM_FE(mb_ereg_search_regs); HHVM_FE(mb_ereg_search_setpos); HHVM_FE(mb_ereg_search); HHVM_FE(mb_ereg); HHVM_FE(mb_eregi_replace); HHVM_FE(mb_eregi); HHVM_FE(mb_get_info); HHVM_FE(mb_http_input); HHVM_FE(mb_http_output); HHVM_FE(mb_internal_encoding); HHVM_FE(mb_language); HHVM_FE(mb_output_handler); HHVM_FE(mb_parse_str); HHVM_FE(mb_preferred_mime_name); HHVM_FE(mb_regex_encoding); HHVM_FE(mb_regex_set_options); HHVM_FE(mb_send_mail); HHVM_FE(mb_split); HHVM_FE(mb_strcut); HHVM_FE(mb_strimwidth); HHVM_FE(mb_stripos); HHVM_FE(mb_stristr); HHVM_FE(mb_strlen); HHVM_FE(mb_strpos); HHVM_FE(mb_strrchr); HHVM_FE(mb_strrichr); HHVM_FE(mb_strripos); HHVM_FE(mb_strrpos); HHVM_FE(mb_strstr); HHVM_FE(mb_strtolower); HHVM_FE(mb_strtoupper); HHVM_FE(mb_strwidth); HHVM_FE(mb_substitute_character); HHVM_FE(mb_substr_count); HHVM_FE(mb_substr); loadSystemlib(); } static std::string http_input; static std::string http_output; static std::string substitute_character; } s_mbstring_extension; std::string mbstringExtension::http_input = "pass"; std::string mbstringExtension::http_output = "pass"; /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-787/cpp/bad_5228_0
crossvul-cpp_data_bad_839_0
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "StructuredHeadersUtilities.h" #include <boost/archive/iterators/binary_from_base64.hpp> #include <boost/archive/iterators/base64_from_binary.hpp> #include <boost/archive/iterators/transform_width.hpp> #include "StructuredHeadersConstants.h" namespace proxygen { namespace StructuredHeaders { bool isLcAlpha(char c) { return c >= 0x61 && c <= 0x7A; } bool isValidIdentifierChar(char c) { return isLcAlpha(c) || std::isdigit(c) || c == '_' || c == '-' || c == '*' || c == '/'; } bool isValidEncodedBinaryContentChar( char c) { return std::isalpha(c) || std::isdigit(c) || c == '+' || c == '/' || c == '='; } bool isValidStringChar(char c) { /* * The difference between the character restriction here and that mentioned * in section 3.7 of version 6 of the Structured Headers draft is that this * function accepts \ and DQUOTE characters. These characters are allowed * as long as they are present as a part of an escape sequence, which is * checked for in the parseString() function in the StructuredHeadersBuffer. */ return c >= 0x20 && c <= 0x7E; } bool isValidIdentifier(const std::string& s) { if (s.size() == 0 || !isLcAlpha(s[0])) { return false; } for (char c : s) { if (!isValidIdentifierChar(c)) { return false; } } return true; } bool isValidString(const std::string& s) { for (char c : s) { if (!isValidStringChar(c)) { return false; } } return true; } bool isValidEncodedBinaryContent( const std::string& s) { if (s.size() % 4 != 0) { return false; } bool equalSeen = false; for (auto it = s.begin(); it != s.end(); it++) { if (*it == '=') { equalSeen = true; } else if (equalSeen || !isValidEncodedBinaryContentChar(*it)) { return false; } } return true; } bool itemTypeMatchesContent( const StructuredHeaderItem& input) { switch (input.tag) { case StructuredHeaderItem::Type::BINARYCONTENT: case StructuredHeaderItem::Type::IDENTIFIER: case StructuredHeaderItem::Type::STRING: return input.value.type() == typeid(std::string); case StructuredHeaderItem::Type::INT64: return input.value.type() == typeid(int64_t); case StructuredHeaderItem::Type::DOUBLE: return input.value.type() == typeid(double); case StructuredHeaderItem::Type::NONE: return true; } return false; } std::string decodeBase64( const std::string& encoded) { if (encoded.size() == 0) { // special case, to prevent an integer overflow down below. return ""; } using namespace boost::archive::iterators; using b64it = transform_width<binary_from_base64<std::string::const_iterator>, 8, 6>; std::string decoded = std::string(b64it(std::begin(encoded)), b64it(std::end(encoded))); uint32_t numPadding = std::count(encoded.begin(), encoded.end(), '='); decoded.erase(decoded.end() - numPadding, decoded.end()); return decoded; } std::string encodeBase64(const std::string& input) { using namespace boost::archive::iterators; using b64it = base64_from_binary<transform_width<const char*, 6, 8>>; auto data = input.data(); std::string encoded(b64it(data), b64it(data + (input.length()))); encoded.append((3 - (input.length() % 3)) % 3, '='); return encoded; } } }
./CrossVul/dataset_final_sorted/CWE-787/cpp/bad_839_0